pfeed 0.0.1.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pfeed/.DS_Store +0 -0
- pfeed/__init__.py +20 -0
- pfeed/config/logging.yml +47 -0
- pfeed/const/commons.py +2 -0
- pfeed/const/paths.py +9 -0
- pfeed/datastore.py +117 -0
- pfeed/feeds/__init__.py +2 -0
- pfeed/feeds/base_feed.py +3 -0
- pfeed/feeds/bybit_feed.py +93 -0
- pfeed/feeds/custom_csv_feed.py +13 -0
- pfeed/feeds/yahoo_finance_feed.py +96 -0
- pfeed/filepath.py +36 -0
- pfeed/main.py +72 -0
- pfeed/sources/.DS_Store +0 -0
- pfeed/sources/__init__.py +1 -0
- pfeed/sources/bybit/__init__.py +2 -0
- pfeed/sources/bybit/api.py +63 -0
- pfeed/sources/bybit/config.yml +4 -0
- pfeed/sources/bybit/const.py +42 -0
- pfeed/sources/bybit/eda.ipynb +29050 -0
- pfeed/sources/bybit/etl.py +161 -0
- pfeed/sources/bybit/historical.py +151 -0
- pfeed/utils/utils.py +77 -0
- pfeed-0.0.1.dev1.dist-info/LICENSE +201 -0
- pfeed-0.0.1.dev1.dist-info/METADATA +42 -0
- pfeed-0.0.1.dev1.dist-info/RECORD +27 -0
- pfeed-0.0.1.dev1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
'''ETL = Extract, Transform, Load data'''
|
|
2
|
+
import os
|
|
3
|
+
import io
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from pfeed.const.paths import DATA_PATH
|
|
12
|
+
from pfeed.sources.bybit.const import DATA_SOURCE, SELECTED_RAW_COLS, RENAMING_COLS, RAW_DATA_TIMESTAMP_UNITS
|
|
13
|
+
from pfeed.datastore import Datastore
|
|
14
|
+
from pfeed.filepath import FilePath
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(DATA_SOURCE.lower())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def extract_data(
|
|
21
|
+
pdt: str,
|
|
22
|
+
date: str,
|
|
23
|
+
dtype: Literal['raw', 'tick', 'second', 'minute', 'hour', 'daily'],
|
|
24
|
+
env: Literal['PAPER', 'LIVE']='LIVE',
|
|
25
|
+
mode: Literal['historical', 'streaming']='historical',
|
|
26
|
+
data_path: str=str(DATA_PATH),
|
|
27
|
+
) -> bytes:
|
|
28
|
+
file_extension = '.csv.gz' if dtype == 'raw' else '.parquet.gz'
|
|
29
|
+
fp = FilePath(data_path, env, DATA_SOURCE, dtype, mode, pdt, date, file_extension)
|
|
30
|
+
if os.path.exists(fp.file_path):
|
|
31
|
+
with open(fp.file_path, 'rb') as f:
|
|
32
|
+
data: bytes = f.read()
|
|
33
|
+
logger.debug(f'read data from {fp.file_path}')
|
|
34
|
+
return data
|
|
35
|
+
else:
|
|
36
|
+
datastore = Datastore()
|
|
37
|
+
object_name = fp.storage_path
|
|
38
|
+
data: bytes | None = datastore.get_object(object_name)
|
|
39
|
+
if data:
|
|
40
|
+
logger.debug(f'extracted data from MinIO object {object_name}')
|
|
41
|
+
else:
|
|
42
|
+
logger.error(f'failed to extract data from MinIO object {object_name}')
|
|
43
|
+
return data
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_data(
|
|
47
|
+
pdt: str,
|
|
48
|
+
date: str,
|
|
49
|
+
dtype: Literal['raw', 'tick', 'second', 'minute', 'hour', 'daily'],
|
|
50
|
+
data: bytes,
|
|
51
|
+
env: Literal['PAPER', 'LIVE']='LIVE',
|
|
52
|
+
mode: Literal['historical', 'streaming']='historical',
|
|
53
|
+
data_path: str=str(DATA_PATH),
|
|
54
|
+
use_minio=True,
|
|
55
|
+
**kwargs
|
|
56
|
+
):
|
|
57
|
+
if not os.path.exists(data_path):
|
|
58
|
+
os.makedirs(data_path)
|
|
59
|
+
print(f'created {data_path=}')
|
|
60
|
+
file_extension = '.csv.gz' if dtype == 'raw' else '.parquet.gz'
|
|
61
|
+
fp = FilePath(data_path, env, DATA_SOURCE, dtype, mode, pdt, date, file_extension)
|
|
62
|
+
if use_minio:
|
|
63
|
+
datastore = Datastore()
|
|
64
|
+
object_name = fp.storage_path
|
|
65
|
+
datastore.put_object(object_name, data, **kwargs)
|
|
66
|
+
logger.debug(f'loaded data to object {object_name} {kwargs=}')
|
|
67
|
+
else:
|
|
68
|
+
directory = os.path.dirname(fp.file_path)
|
|
69
|
+
if not os.path.exists(directory):
|
|
70
|
+
os.makedirs(directory)
|
|
71
|
+
with open(fp.file_path, 'wb') as f:
|
|
72
|
+
f.write(data)
|
|
73
|
+
logger.debug(f'loaded data to {fp.file_path}')
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def clean_data(category: str, data: bytes) -> bytes:
|
|
77
|
+
df = pd.read_csv(io.BytesIO(data), compression='gzip')
|
|
78
|
+
df = df.loc[:, SELECTED_RAW_COLS[category]]
|
|
79
|
+
df['side'] = df['side'].map({'Buy': 1, 'Sell': -1})
|
|
80
|
+
df = df.rename(columns=RENAMING_COLS[category])
|
|
81
|
+
return df.to_parquet()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def resample_data(data: bytes, resolution: str, is_tick=False, category='') -> bytes:
|
|
85
|
+
'''
|
|
86
|
+
Args:
|
|
87
|
+
is_tick: if True, use tick data to resample data
|
|
88
|
+
resolution: # + unit (s/m/h/d), e.g. 1s
|
|
89
|
+
'''
|
|
90
|
+
def find_high_or_low_first(series: pd.Series):
|
|
91
|
+
if not series.empty:
|
|
92
|
+
argmax, argmin = series.argmax(), series.argmin()
|
|
93
|
+
if argmax < argmin:
|
|
94
|
+
return 'H'
|
|
95
|
+
elif argmax > argmin:
|
|
96
|
+
return 'L'
|
|
97
|
+
else:
|
|
98
|
+
return 'N'
|
|
99
|
+
# T means minute, refer to https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects
|
|
100
|
+
resolution = resolution.upper().replace('M', 'T')
|
|
101
|
+
df = pd.read_parquet(io.BytesIO(data))
|
|
102
|
+
if 'ts' in df.columns:
|
|
103
|
+
assert category, 'category must be provided'
|
|
104
|
+
df.set_index('ts', inplace=True)
|
|
105
|
+
# NOTE: this may make the `ts` value inaccurate,
|
|
106
|
+
# e.g. 1671580800.9906 -> 1671580800.990600192
|
|
107
|
+
df.index = pd.to_datetime(df.index, unit=RAW_DATA_TIMESTAMP_UNITS[category])
|
|
108
|
+
if is_tick:
|
|
109
|
+
df['num_buys'] = df['side'].map({1: 1, -1: np.nan})
|
|
110
|
+
df['num_sells'] = df['side'].map({1: np.nan, -1: 1})
|
|
111
|
+
df['buy_volume'] = np.where(df['side'] == 1, df['volume'], np.nan)
|
|
112
|
+
df['sell_volume'] = np.where(df['side'] == -1, df['volume'], np.nan)
|
|
113
|
+
df['first'] = df['price']
|
|
114
|
+
resample_logic = {
|
|
115
|
+
'num_buys': 'sum',
|
|
116
|
+
'num_sells': 'sum',
|
|
117
|
+
'volume': 'sum',
|
|
118
|
+
'buy_volume': 'sum',
|
|
119
|
+
'sell_volume': 'sum',
|
|
120
|
+
'price': 'ohlc',
|
|
121
|
+
'first': find_high_or_low_first
|
|
122
|
+
}
|
|
123
|
+
else:
|
|
124
|
+
df['arg_high'] = df['high']
|
|
125
|
+
df['arg_low'] = df['low']
|
|
126
|
+
resample_logic = {
|
|
127
|
+
'num_buys': 'sum',
|
|
128
|
+
'num_sells': 'sum',
|
|
129
|
+
'buy_volume': 'sum',
|
|
130
|
+
'sell_volume': 'sum',
|
|
131
|
+
'volume': 'sum',
|
|
132
|
+
'open': 'first',
|
|
133
|
+
'high': 'max',
|
|
134
|
+
'low': 'min',
|
|
135
|
+
'close': 'last',
|
|
136
|
+
'arg_high': lambda series: series.argmax() if not series.empty else None,
|
|
137
|
+
'arg_low': lambda series: series.argmin() if not series.empty else None,
|
|
138
|
+
}
|
|
139
|
+
resampled_df = (
|
|
140
|
+
df
|
|
141
|
+
.resample(resolution)
|
|
142
|
+
.apply(resample_logic)
|
|
143
|
+
.dropna()
|
|
144
|
+
)
|
|
145
|
+
if is_tick:
|
|
146
|
+
resampled_df = resampled_df.droplevel(0, axis=1)
|
|
147
|
+
# convert float to int
|
|
148
|
+
resampled_df['num_buys'] = resampled_df['num_buys'].astype(int)
|
|
149
|
+
resampled_df['num_sells'] = resampled_df['num_sells'].astype(int)
|
|
150
|
+
else:
|
|
151
|
+
resampled_df['first'] = (resampled_df['arg_high'] < resampled_df['arg_low']).map({True: 'H', False: 'L'})
|
|
152
|
+
resampled_df['first'].where(resampled_df['arg_high'] != resampled_df['arg_low'], other='N', inplace=True)
|
|
153
|
+
resampled_df.drop(columns=['arg_high', 'arg_low'], inplace=True)
|
|
154
|
+
return resampled_df.to_parquet()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == '__main__':
|
|
158
|
+
pdt = 'BTC_USDT_PERP'
|
|
159
|
+
date = '2023-11-02'
|
|
160
|
+
dtype = 'raw'
|
|
161
|
+
data: bytes = extract_data(pdt, date, dtype)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import logging
|
|
3
|
+
import datetime
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from logging.handlers import QueueHandler, QueueListener
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
from tqdm import tqdm
|
|
9
|
+
|
|
10
|
+
from pfeed.utils.utils import get_dates_in_between
|
|
11
|
+
from pfeed.const.commons import SUPPORTED_DATA_TYPES
|
|
12
|
+
from pfeed.const.paths import PROJ_PATH, DATA_PATH, LOG_PATH, CONFIG_PATH
|
|
13
|
+
from pfeed.sources.bybit.const import DATA_START_DATE, DATA_SOURCE, SUPPORTED_CRYPTO_PRODUCT_TYPES, create_efilename
|
|
14
|
+
from pfeed.sources.bybit import api
|
|
15
|
+
from pfeed.sources.bybit import etl
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(DATA_SOURCE.lower())
|
|
19
|
+
__all__ = ['run']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _load_config():
|
|
23
|
+
file_path = f'{PROJ_PATH}/sources/{DATA_SOURCE.lower()}/config.yml'
|
|
24
|
+
short_file_path = '/'.join(file_path.split("/")[-4:])
|
|
25
|
+
if os.path.exists(file_path):
|
|
26
|
+
with open(file_path, 'r') as f:
|
|
27
|
+
print(f'loaded config {short_file_path}')
|
|
28
|
+
return yaml.safe_load(f.read())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_pdts(exchange, pdts, ptypes) -> list[str]:
|
|
32
|
+
if not pdts:
|
|
33
|
+
adapter = exchange.adapter
|
|
34
|
+
pdts = []
|
|
35
|
+
if not ptypes:
|
|
36
|
+
ptypes = SUPPORTED_CRYPTO_PRODUCT_TYPES
|
|
37
|
+
for ptype in ptypes:
|
|
38
|
+
assert ptype in SUPPORTED_CRYPTO_PRODUCT_TYPES, f'{ptype} is not supported, {SUPPORTED_CRYPTO_PRODUCT_TYPES=}'
|
|
39
|
+
category = exchange.categorize_product(ptype)
|
|
40
|
+
epdts = api.get_epdts(category, ptype)
|
|
41
|
+
# NOTE: if adapter(epdt, ref_key=category) == epdt, i.e. key is not found in pdt matching, meaning the product has been delisted
|
|
42
|
+
pdts.extend([adapter(epdt, ref_key=category) for epdt in epdts if adapter(epdt, ref_key=category) != epdt])
|
|
43
|
+
return pdts
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def resample_raw_data(category: str, pdt: str, date: str, raw_data: bytes) -> dict[str, bytes]:
|
|
47
|
+
tick_data = etl.clean_data(category, raw_data)
|
|
48
|
+
second_data = etl.resample_data(tick_data, resolution='1s', is_tick=True, category=category)
|
|
49
|
+
minute_data = etl.resample_data(second_data, resolution='1m')
|
|
50
|
+
hour_data = etl.resample_data(minute_data, resolution='1h')
|
|
51
|
+
daily_data = etl.resample_data(hour_data, resolution='1d')
|
|
52
|
+
logger.debug(f'resampled {DATA_SOURCE} {pdt} {date} data')
|
|
53
|
+
return {
|
|
54
|
+
'raw': raw_data,
|
|
55
|
+
'tick': tick_data,
|
|
56
|
+
'second': second_data,
|
|
57
|
+
'minute': minute_data,
|
|
58
|
+
'hour': hour_data,
|
|
59
|
+
'daily': daily_data,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def run(
|
|
64
|
+
dtypes: list[str] | None=None,
|
|
65
|
+
ptypes: list[str] | None=None,
|
|
66
|
+
pdts: list[str] | None=None,
|
|
67
|
+
start_date: str | None=None,
|
|
68
|
+
end_date: str | None=None,
|
|
69
|
+
log_path: str=str(LOG_PATH),
|
|
70
|
+
data_path: str=str(DATA_PATH),
|
|
71
|
+
batch_size: int=8,
|
|
72
|
+
use_ray: bool=True,
|
|
73
|
+
use_minio: bool=True
|
|
74
|
+
):
|
|
75
|
+
from pfund.exchanges.bybit.exchange import Exchange
|
|
76
|
+
from pfund.logging import set_up_loggers
|
|
77
|
+
from pfeed import cprint
|
|
78
|
+
|
|
79
|
+
env = 'LIVE' # historical data is from LIVE env
|
|
80
|
+
mode = 'historical'
|
|
81
|
+
dtypes = [dtype.lower() for dtype in dtypes] if dtypes else SUPPORTED_DATA_TYPES[:]
|
|
82
|
+
assert all(dtype in SUPPORTED_DATA_TYPES for dtype in dtypes), f'{dtypes=} but {SUPPORTED_DATA_TYPES=}'
|
|
83
|
+
ptypes = [ptype.upper() for ptype in ptypes] if ptypes else []
|
|
84
|
+
pdts = [pdt.upper() for pdt in pdts] if pdts else []
|
|
85
|
+
set_up_loggers(log_path=f'{log_path}/{env}', config_path=CONFIG_PATH)
|
|
86
|
+
|
|
87
|
+
cprint(f'PFeed ({DATA_SOURCE} {env} server): getting {mode.upper()} data', style='bold yellow')
|
|
88
|
+
|
|
89
|
+
# load config if any
|
|
90
|
+
if config := _load_config():
|
|
91
|
+
ptypes = ptypes or config.get('ptypes', None)
|
|
92
|
+
pdts = pdts or config.get('pdts', None)
|
|
93
|
+
start_date = start_date or config.get('start_date', None)
|
|
94
|
+
end_date = end_date or config.get('end_date', None)
|
|
95
|
+
|
|
96
|
+
exchange = Exchange(env)
|
|
97
|
+
adapter = exchange.adapter
|
|
98
|
+
pdts = get_pdts(exchange, pdts, ptypes)
|
|
99
|
+
start_date: str = start_date or DATA_START_DATE
|
|
100
|
+
end_date: str = end_date or datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y-%m-%d')
|
|
101
|
+
dates: list[str] = get_dates_in_between(start_date, end_date)
|
|
102
|
+
ray_tasks = defaultdict(list)
|
|
103
|
+
|
|
104
|
+
for pdt in pdts if use_ray else tqdm(pdts, desc=f'Downloading {DATA_SOURCE} historical data by product', colour='green'):
|
|
105
|
+
ptype = pdt.split('_')[-1]
|
|
106
|
+
is_spot = (ptype.upper() == 'SPOT')
|
|
107
|
+
category = exchange.categorize_product(ptype)
|
|
108
|
+
epdt = adapter(pdt, ref_key=category)
|
|
109
|
+
efilenames = api.get_efilenames(category, epdt)
|
|
110
|
+
for date in dates if use_ray else tqdm(dates, desc=f'Downloading {DATA_SOURCE} {pdt} historical data by date', colour='yellow'):
|
|
111
|
+
efilename = create_efilename(epdt, date, is_spot=is_spot)
|
|
112
|
+
if efilename not in efilenames:
|
|
113
|
+
# logger.debug(f'{efilename} does not exist in {DATA_SOURCE}')
|
|
114
|
+
continue
|
|
115
|
+
if use_ray:
|
|
116
|
+
ray_tasks[pdt].append((category, pdt, date))
|
|
117
|
+
else:
|
|
118
|
+
# run ETL = Extract, Transform, Load data
|
|
119
|
+
if raw_data := api.get_data(category, epdt, date):
|
|
120
|
+
resampled_datas = resample_raw_data(category, pdt, date, raw_data)
|
|
121
|
+
for dtype in dtypes:
|
|
122
|
+
etl.load_data(pdt, date, dtype, resampled_datas[dtype], data_path=data_path, use_minio=use_minio)
|
|
123
|
+
else:
|
|
124
|
+
raise Exception(f'failed to download {DATA_SOURCE} {pdt} {date} historical data')
|
|
125
|
+
|
|
126
|
+
if use_ray:
|
|
127
|
+
import ray
|
|
128
|
+
from ray.util.queue import Queue
|
|
129
|
+
|
|
130
|
+
@ray.remote
|
|
131
|
+
def _run_task(log_queue: Queue, category: str, pdt: str, date: str):
|
|
132
|
+
if not logger.handlers:
|
|
133
|
+
logger.addHandler(QueueHandler(log_queue))
|
|
134
|
+
logger.setLevel(logging.DEBUG)
|
|
135
|
+
epdt = adapter(pdt, ref_key=category)
|
|
136
|
+
if raw_data := api.get_data(category, epdt, date):
|
|
137
|
+
resampled_datas = resample_raw_data(category, pdt, date, raw_data)
|
|
138
|
+
for dtype in dtypes:
|
|
139
|
+
etl.load_data(pdt, date, dtype, resampled_datas[dtype], data_path=data_path, use_minio=use_minio)
|
|
140
|
+
else:
|
|
141
|
+
raise Exception(f'failed to download {DATA_SOURCE} {pdt} {date} historical data')
|
|
142
|
+
|
|
143
|
+
log_queue = Queue()
|
|
144
|
+
QueueListener(log_queue, *logger.handlers, respect_handler_level=True).start()
|
|
145
|
+
for pdt in tqdm(ray_tasks, desc=f'Downloading {DATA_SOURCE} historical data by product', colour='green'):
|
|
146
|
+
batches = [ray_tasks[pdt][i: i + batch_size] for i in range(0, len(ray_tasks[pdt]), batch_size)]
|
|
147
|
+
for batch in tqdm(batches, desc=f'Downloading {DATA_SOURCE} {pdt} historical data by batch ({batch_size=})', colour='yellow'):
|
|
148
|
+
futures = [_run_task.remote(log_queue, *task) for task in batch]
|
|
149
|
+
ray.get(futures)
|
|
150
|
+
|
|
151
|
+
logger.warning(f'finished downloading historical data from {DATA_SOURCE} to {data_path} or MinIO if enabled')
|
pfeed/utils/utils.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import datetime
|
|
3
|
+
import calendar
|
|
4
|
+
import pytz
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_TZ_abbrev_and_UTC_offset(date: str, tz_identifier='US/Eastern'):
|
|
8
|
+
'''Returns timezone abbreviation (e.g. EST, EDT) based on the timezone identifier.
|
|
9
|
+
Useful when you want to determine if e.g. New York is in EST or EDT now.
|
|
10
|
+
Args:
|
|
11
|
+
date: e.g. 2023-11-11
|
|
12
|
+
timezone: TZ identifier from IANA timezone database
|
|
13
|
+
'''
|
|
14
|
+
date = datetime.datetime.strptime(date, '%Y-%m-%d')
|
|
15
|
+
timezone = pytz.timezone(tz_identifier)
|
|
16
|
+
local_date = timezone.localize(date) # attach timezone to the datetime object
|
|
17
|
+
return local_date.strftime('%Z%z')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_x_days_before_in_UTC(x=0) -> str:
|
|
21
|
+
return (datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(days=x)).strftime('%Y-%m-%d')
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_dates_in_between(start_date: str, end_date: str) -> list[str]:
|
|
25
|
+
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d').date()
|
|
26
|
+
end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').date()
|
|
27
|
+
date_delta = end_date - start_date
|
|
28
|
+
return [str(start_date + datetime.timedelta(i)) for i in range(date_delta.days + 1)]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_filename(pdt: str, date: str, file_extension: str) -> str:
|
|
32
|
+
return pdt + '_' + date + file_extension
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def extract_date_from_filename(filename: str) -> str | None:
|
|
36
|
+
date_pattern = r'\d{4}-\d{2}-\d{2}'
|
|
37
|
+
match = re.search(date_pattern, filename)
|
|
38
|
+
if match:
|
|
39
|
+
date = match.group(0)
|
|
40
|
+
return date
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def rollback_date_range(rollback_period: str) -> tuple[str, str]:
|
|
44
|
+
'''Returns start_date and end_date based on the rollback_period (e.g. '1w', '1M').'''
|
|
45
|
+
def _nextmonth(year, month):
|
|
46
|
+
if month == 12:
|
|
47
|
+
return year+1, 1
|
|
48
|
+
else:
|
|
49
|
+
return year, month+1
|
|
50
|
+
utcnow = datetime.datetime.now(tz=datetime.timezone.utc)
|
|
51
|
+
period = int(rollback_period[:-1])
|
|
52
|
+
if rollback_period.endswith('d'):
|
|
53
|
+
timedelta = datetime.timedelta(days=period)
|
|
54
|
+
elif rollback_period.endswith('w'):
|
|
55
|
+
timedelta = datetime.timedelta(weeks=period)
|
|
56
|
+
elif rollback_period.endswith('M'):
|
|
57
|
+
year, month = utcnow.year, utcnow.month - period
|
|
58
|
+
while month <= 0:
|
|
59
|
+
month += 12 # Rollback to the previous year
|
|
60
|
+
year -= 1
|
|
61
|
+
total_days_in_month = 0
|
|
62
|
+
while not (year == utcnow.year and month == utcnow.month):
|
|
63
|
+
year, month = _nextmonth(year, month)
|
|
64
|
+
_, days_in_month = calendar.monthrange(year, month)
|
|
65
|
+
total_days_in_month += days_in_month
|
|
66
|
+
timedelta = datetime.timedelta(days=total_days_in_month)
|
|
67
|
+
elif rollback_period.endswith('y'):
|
|
68
|
+
year = utcnow.year - period
|
|
69
|
+
total_days_in_year = 0
|
|
70
|
+
for yr in range(year, utcnow.year):
|
|
71
|
+
total_days_in_year += 366 if calendar.isleap(yr) else 365
|
|
72
|
+
timedelta = datetime.timedelta(days=total_days_in_year)
|
|
73
|
+
else:
|
|
74
|
+
raise ValueError(f"Unsupported {rollback_period=}")
|
|
75
|
+
end_date = utcnow - datetime.timedelta(days=1) # Previous day
|
|
76
|
+
start_date = end_date - timedelta + datetime.timedelta(days=1)
|
|
77
|
+
return start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d')
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: pfeed
|
|
3
|
+
Version: 0.0.1.dev1
|
|
4
|
+
Summary: A Modern Data Pipeline for Algo-Trading, supporting getting both Real-Time and Historical Data.
|
|
5
|
+
Author: Stephen Yau
|
|
6
|
+
Author-email: softwareentrepreneer+pfeed@gmail.com
|
|
7
|
+
Requires-Python: >=3.10,<3.12
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Requires-Dist: beautifulsoup4 (>=4.12.3,<5.0.0)
|
|
12
|
+
Requires-Dist: minio (>=7.2.3,<8.0.0)
|
|
13
|
+
Requires-Dist: orjson (>=3.9.12,<4.0.0)
|
|
14
|
+
Requires-Dist: pandas (>=2.2.0,<3.0.0)
|
|
15
|
+
Requires-Dist: pyarrow (>=15.0.0,<16.0.0)
|
|
16
|
+
Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
|
|
17
|
+
Requires-Dist: pyyaml (>=6.0.1,<7.0.0)
|
|
18
|
+
Requires-Dist: ray (>=2.9.1,<3.0.0)
|
|
19
|
+
Requires-Dist: requests (>=2.31.0,<3.0.0)
|
|
20
|
+
Requires-Dist: rich (>=13.7.0,<14.0.0)
|
|
21
|
+
Requires-Dist: tqdm (>=4.66.1,<5.0.0)
|
|
22
|
+
Requires-Dist: yfinance (>=0.2.36,<0.3.0)
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
## Setup
|
|
26
|
+
```bash
|
|
27
|
+
poetry install
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Start Processing Historical Data
|
|
31
|
+
```
|
|
32
|
+
python main.py -m historical -p BTC_USDT_PERP -s bybit --no-minio
|
|
33
|
+
# or
|
|
34
|
+
from pfeed import bybit
|
|
35
|
+
bybit.run_historical(...)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Start Streaming Live Data (supports PAPER trading)
|
|
39
|
+
```python
|
|
40
|
+
python main.py -e live -s bybit -m streaming
|
|
41
|
+
```
|
|
42
|
+
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
pfeed/.DS_Store,sha256=VopWakmBjGn9kpV7l3WwYvr4ZpufKwmHA97oYMaAwn8,6148
|
|
2
|
+
pfeed/__init__.py,sha256=4qzQygCmy0QyU8lJuaKbs0bCnZVvQf1UiYIYCSuf62U,376
|
|
3
|
+
pfeed/config/logging.yml,sha256=9pOePCcMAQsK2urN_Km73wzH4xdtnBobntXlJa5olY0,1591
|
|
4
|
+
pfeed/const/commons.py,sha256=Mh-hYF_RRpbSB-WbAE_7e3WnVWxGkOXm-cTQ9wNir9o,125
|
|
5
|
+
pfeed/const/paths.py,sha256=IZyl4SK_RQ2KgwqctZury4BvBjpSv_GVffDbMZJLAgQ,293
|
|
6
|
+
pfeed/datastore.py,sha256=Uku0v061Os05J2fqFVt0__JzK4V4Dh5C_eR-Lz8ABZM,3469
|
|
7
|
+
pfeed/feeds/__init__.py,sha256=LgBB4xo_6TC630RLT1gmrVLbbL6jezqXgaiB9JGAbjE,104
|
|
8
|
+
pfeed/feeds/base_feed.py,sha256=UNlhS3grajkuyZWrsknLxHbgHq2hl74A41CJg4dH2EE,79
|
|
9
|
+
pfeed/feeds/bybit_feed.py,sha256=2MsrrEDVxbIbRZCTJLBtJ1wTYsF9gw3j90YCbulaSsM,3815
|
|
10
|
+
pfeed/feeds/custom_csv_feed.py,sha256=qTkanCebga7Vcrz9Gus0YXX6ZZkhxwiXw02ID9zmZ5M,281
|
|
11
|
+
pfeed/feeds/yahoo_finance_feed.py,sha256=yCNopqZ9lBdl_gVDnvglB1l8ReO74Hy9c5gINNNSeZ4,3326
|
|
12
|
+
pfeed/filepath.py,sha256=eCsz7VcgUr01r0pU-SI41SNh2OVxFT0lakXIGSsLqvg,1324
|
|
13
|
+
pfeed/main.py,sha256=NKYiad7zcHUbJAg1IAwZd3WL6arRvQe9Z4VxBt8pzjs,3168
|
|
14
|
+
pfeed/sources/.DS_Store,sha256=bprxU9J9w5pEM8T_WyRU2_WKbdzscUWgfmLwHfkMw90,6148
|
|
15
|
+
pfeed/sources/__init__.py,sha256=jzafyaYJFj8G2NTuJNqKShqpYjS8NGgb4BskvEH6r6Q,32
|
|
16
|
+
pfeed/sources/bybit/__init__.py,sha256=4LT5I1gsoAD0oJWEbTGq2_ZSakgv0RxcVAVDsfpD5XY,111
|
|
17
|
+
pfeed/sources/bybit/api.py,sha256=hE67WGRG9GbqXbwngazyQlsbYXijh93nTbiNX-PUrq8,2111
|
|
18
|
+
pfeed/sources/bybit/config.yml,sha256=WI2F5Eh96PU_m-mW5pj7g9rkb-nSs-xgug8IxX0-WIA,47
|
|
19
|
+
pfeed/sources/bybit/const.py,sha256=dyhtcOnVsO2iJSqOBn2G6s2xhWATr-ZOcgj1aSimQOE,1398
|
|
20
|
+
pfeed/sources/bybit/eda.ipynb,sha256=4CTHgT1VjGHdQOyDBUSd63Uq0mxxyCARTTLdmwC0wys,4405251
|
|
21
|
+
pfeed/sources/bybit/etl.py,sha256=YVNkxGidNpTKQJ5FMTSO3tCeDSkkS8LALmSi9Nwpq3M,5823
|
|
22
|
+
pfeed/sources/bybit/historical.py,sha256=dP8LBsdTDbw9eX-_vMO15g_bbLfY765wX2fXMgOLjPQ,6879
|
|
23
|
+
pfeed/utils/utils.py,sha256=B0JjbPxJNbMEjv5lGhwOlpEEUT9eV3p28CpTt4TjiVY,3122
|
|
24
|
+
pfeed-0.0.1.dev1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
25
|
+
pfeed-0.0.1.dev1.dist-info/METADATA,sha256=P3lwrBdScqxszoZNqUcZiUsdytjPK1B_2xQmJ5xdTEA,1257
|
|
26
|
+
pfeed-0.0.1.dev1.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
27
|
+
pfeed-0.0.1.dev1.dist-info/RECORD,,
|