hyperdrive 1.13.2__tar.gz → 1.15.2__tar.gz
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.
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/PKG-INFO +4 -8
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/README.md +3 -3
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Algotrader.py +1 -1
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Broker.py +1 -1
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Calculus.py +5 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Constants.py +7 -1
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/DataSource.py +13 -6
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Exchange.py +53 -13
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/History.py +70 -2
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Precognition.py +20 -4
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Storage.py +16 -10
- hyperdrive-1.15.2/hyperdrive/TimeMachine.py +236 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive.egg-info/PKG-INFO +4 -8
- hyperdrive-1.15.2/hyperdrive.egg-info/requires.txt +19 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_DataSource.py +2 -1
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Exchange.py +23 -11
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_History.py +26 -4
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Precognition.py +6 -2
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Storage.py +2 -2
- hyperdrive-1.13.2/hyperdrive/TimeMachine.py +0 -89
- hyperdrive-1.13.2/hyperdrive.egg-info/requires.txt +0 -20
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/LICENSE +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Crypt.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/FileOps.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Transformer.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Utils.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/Workflow.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive/__init__.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive.egg-info/SOURCES.txt +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive.egg-info/dependency_links.txt +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/hyperdrive.egg-info/top_level.txt +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/setup.cfg +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/setup.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Algotrader.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Broker.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Calculus.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Constants.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_FileOps.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_TimeMachine.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Transformer.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Utils.py +0 -0
- {hyperdrive-1.13.2 → hyperdrive-1.15.2}/test/test_Workflow.py +0 -0
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: hyperdrive
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.15.2
|
|
4
4
|
Summary: An algorithmic trading platform
|
|
5
5
|
Home-page: https://github.com/suchak1/hyperdrive
|
|
6
6
|
Author: Krish Suchak
|
|
7
7
|
Author-email: suchak.krish@gmail.com
|
|
8
|
-
License: UNKNOWN
|
|
9
8
|
Project-URL: Bug Reports, https://github.com/suchak1/hyperdrive/issues
|
|
10
9
|
Project-URL: Source, https://github.com/suchak1/hyperdrive
|
|
11
|
-
Platform: UNKNOWN
|
|
12
10
|
Requires-Python: >=3.7
|
|
13
11
|
Description-Content-Type: text/markdown
|
|
14
12
|
License-File: LICENSE
|
|
@@ -26,7 +24,7 @@ License-File: LICENSE
|
|
|
26
24
|
<!-- green left, gray right https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=brightgreen&right_color=gray&left_text=Downloads-->
|
|
27
25
|
<!-- black and indigo https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=black&right_color=indigo&left_text=Downloads -->
|
|
28
26
|
|
|
29
|
-
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/
|
|
27
|
+
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/logo.png" width="16" /> **Algotrade.io**](https://algotrade.io).
|
|
30
28
|
|
|
31
29
|
Unlike other backtesting libraries, _`hyperdrive`_ specializes in data collection and quantitative research.
|
|
32
30
|
|
|
@@ -159,9 +157,9 @@ timeframe = '1y'
|
|
|
159
157
|
|
|
160
158
|
df = md.get_ohlc(symbol=symbol, timeframe=timeframe)
|
|
161
159
|
|
|
162
|
-
holding = hist.
|
|
160
|
+
holding = hist.from_holding(df[C.CLOSE])
|
|
163
161
|
signals = hist.get_optimal_signals(df[C.CLOSE])
|
|
164
|
-
my_strat = hist.
|
|
162
|
+
my_strat = hist.from_signals(df[C.CLOSE], signals)
|
|
165
163
|
|
|
166
164
|
metrics = [
|
|
167
165
|
'Total Return [%]', 'Benchmark Return [%]',
|
|
@@ -300,5 +298,3 @@ Available data collection functions:
|
|
|
300
298
|
```
|
|
301
299
|
|
|
302
300
|
```
|
|
303
|
-
|
|
304
|
-
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
<!-- green left, gray right https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=brightgreen&right_color=gray&left_text=Downloads-->
|
|
12
12
|
<!-- black and indigo https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=black&right_color=indigo&left_text=Downloads -->
|
|
13
13
|
|
|
14
|
-
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/
|
|
14
|
+
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/logo.png" width="16" /> **Algotrade.io**](https://algotrade.io).
|
|
15
15
|
|
|
16
16
|
Unlike other backtesting libraries, _`hyperdrive`_ specializes in data collection and quantitative research.
|
|
17
17
|
|
|
@@ -144,9 +144,9 @@ timeframe = '1y'
|
|
|
144
144
|
|
|
145
145
|
df = md.get_ohlc(symbol=symbol, timeframe=timeframe)
|
|
146
146
|
|
|
147
|
-
holding = hist.
|
|
147
|
+
holding = hist.from_holding(df[C.CLOSE])
|
|
148
148
|
signals = hist.get_optimal_signals(df[C.CLOSE])
|
|
149
|
-
my_strat = hist.
|
|
149
|
+
my_strat = hist.from_signals(df[C.CLOSE], signals)
|
|
150
150
|
|
|
151
151
|
metrics = [
|
|
152
152
|
'Total Return [%]', 'Benchmark Return [%]',
|
|
@@ -37,6 +37,11 @@ class Calculator:
|
|
|
37
37
|
order
|
|
38
38
|
)
|
|
39
39
|
|
|
40
|
+
def get_difference(self, old: set, new: set) -> tuple[set, set]:
|
|
41
|
+
minus = old.difference(new)
|
|
42
|
+
plus = new.difference(old)
|
|
43
|
+
return minus, plus
|
|
44
|
+
|
|
40
45
|
def derive(self, y, x=np.array([0, 1])):
|
|
41
46
|
if isinstance(x, pd.Series):
|
|
42
47
|
x = x.to_numpy()
|
|
@@ -8,7 +8,12 @@ load_dotenv(find_dotenv('config.env'))
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def get_env_int(var_name, default=None):
|
|
11
|
-
return
|
|
11
|
+
return (
|
|
12
|
+
int(os.environ[var_name])
|
|
13
|
+
if os.environ.get(var_name)
|
|
14
|
+
and os.environ[var_name].isnumeric()
|
|
15
|
+
else default
|
|
16
|
+
)
|
|
12
17
|
|
|
13
18
|
|
|
14
19
|
def get_env_bool(var_name):
|
|
@@ -237,6 +242,7 @@ class PathFinder:
|
|
|
237
242
|
def get_new_orders_path(self, provider):
|
|
238
243
|
return os.path.join(
|
|
239
244
|
DATA_DIR,
|
|
245
|
+
'orders',
|
|
240
246
|
f'{provider}.csv'
|
|
241
247
|
)
|
|
242
248
|
|
|
@@ -8,6 +8,7 @@ from random import random
|
|
|
8
8
|
from polygon import RESTClient, exceptions
|
|
9
9
|
from dotenv import load_dotenv, find_dotenv
|
|
10
10
|
from FileOps import FileReader, FileWriter
|
|
11
|
+
from Calculus import Calculator
|
|
11
12
|
from TimeMachine import TimeTraveller
|
|
12
13
|
from Constants import PathFinder
|
|
13
14
|
import Constants as C
|
|
@@ -27,6 +28,7 @@ class MarketData:
|
|
|
27
28
|
self.reader = FileReader()
|
|
28
29
|
self.finder = PathFinder()
|
|
29
30
|
self.traveller = TimeTraveller()
|
|
31
|
+
self.calculator = Calculator()
|
|
30
32
|
self.provider = 'polygon'
|
|
31
33
|
|
|
32
34
|
def get_indexer(self, s1, s2):
|
|
@@ -375,7 +377,7 @@ class MarketData:
|
|
|
375
377
|
df = pd.DataFrame(columns=[C.TIME, C.SYMBOL, C.DELTA])
|
|
376
378
|
df = df.sort_values(
|
|
377
379
|
by=[C.TIME, C.SYMBOL]
|
|
378
|
-
).drop_duplicates(C.SYMBOL, 'last')
|
|
380
|
+
).drop_duplicates(C.SYMBOL, keep='last')
|
|
379
381
|
df = df[df[C.DELTA] == '+'].reset_index(drop=True)
|
|
380
382
|
return df
|
|
381
383
|
|
|
@@ -399,7 +401,7 @@ class MarketData:
|
|
|
399
401
|
soup = BeautifulSoup(res.text, 'html.parser')
|
|
400
402
|
html = soup.select("table#constituents")[0]
|
|
401
403
|
df = pd.read_html(str(html))[0]
|
|
402
|
-
symbols = df[
|
|
404
|
+
symbols = df['Ticker']
|
|
403
405
|
today = datetime.today().strftime(C.DATE_FMT)
|
|
404
406
|
df = pd.DataFrame({
|
|
405
407
|
C.TIME: len(symbols) * [today],
|
|
@@ -419,8 +421,7 @@ class MarketData:
|
|
|
419
421
|
before = set(self.standardize_ndx(saved)[C.SYMBOL])
|
|
420
422
|
after = set(self.get_latest_ndx(**kwargs)[C.SYMBOL])
|
|
421
423
|
today = datetime.now().strftime(C.DATE_FMT)
|
|
422
|
-
minus =
|
|
423
|
-
plus = after.difference(before)
|
|
424
|
+
minus, plus = self.calculator.get_difference(before, after)
|
|
424
425
|
union = list(minus.union(plus))
|
|
425
426
|
to_append = pd.DataFrame({
|
|
426
427
|
C.TIME: [today] * len(union),
|
|
@@ -633,7 +634,10 @@ class Polygon(MarketData):
|
|
|
633
634
|
try:
|
|
634
635
|
response = self.client.get_aggs(
|
|
635
636
|
symbol, 1, 'day',
|
|
636
|
-
from_=formatted_start,
|
|
637
|
+
from_=formatted_start,
|
|
638
|
+
to=formatted_end,
|
|
639
|
+
adjusted=True,
|
|
640
|
+
limit=C.POLY_MAX_AGGS_LIMIT
|
|
637
641
|
)
|
|
638
642
|
finally:
|
|
639
643
|
self.log_api_call_time()
|
|
@@ -790,7 +794,10 @@ class Glassnode(MarketData):
|
|
|
790
794
|
sleep(15)
|
|
791
795
|
driver.get('https://studio.glassnode.com/metrics')
|
|
792
796
|
sleep(5)
|
|
793
|
-
url =
|
|
797
|
+
url = (
|
|
798
|
+
"https://api.glassnode.com/v1/metrics/market/price_usd_close"
|
|
799
|
+
"?a=BTC&i=24h&referer=charts"
|
|
800
|
+
)
|
|
794
801
|
driver.get(url)
|
|
795
802
|
sleep(5) # wait for the requests to take place
|
|
796
803
|
|
|
@@ -5,7 +5,9 @@ import base64
|
|
|
5
5
|
import hashlib
|
|
6
6
|
import requests
|
|
7
7
|
import urllib.parse
|
|
8
|
+
from time import sleep
|
|
8
9
|
from binance import Client
|
|
10
|
+
from typing import Iterable, Union, Optional
|
|
9
11
|
from binance.helpers import round_step_size
|
|
10
12
|
from dotenv import load_dotenv, find_dotenv
|
|
11
13
|
import Constants as C
|
|
@@ -13,17 +15,17 @@ load_dotenv(find_dotenv('config.env'))
|
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
class CEX:
|
|
16
|
-
def create_pair(self, base, quote):
|
|
18
|
+
def create_pair(self, base: str, quote: str) -> str:
|
|
17
19
|
return f'{base}{quote}'
|
|
18
20
|
|
|
19
21
|
|
|
20
22
|
class AlpacaEx(CEX):
|
|
21
23
|
def __init__(
|
|
22
24
|
self,
|
|
23
|
-
token=os.environ.get('ALPACA'),
|
|
24
|
-
secret=os.environ.get('ALPACA_SECRET'),
|
|
25
|
-
paper=False
|
|
26
|
-
):
|
|
25
|
+
token: Optional[str] = os.environ.get('ALPACA'),
|
|
26
|
+
secret: Optional[str] = os.environ.get('ALPACA_SECRET'),
|
|
27
|
+
paper: bool = False
|
|
28
|
+
) -> None:
|
|
27
29
|
super().__init__()
|
|
28
30
|
self.base = (f'https://{"paper-" if paper or C.TEST else ""}'
|
|
29
31
|
'api.alpaca.markets')
|
|
@@ -35,7 +37,35 @@ class AlpacaEx(CEX):
|
|
|
35
37
|
if not (self.token and self.secret):
|
|
36
38
|
raise Exception('missing Alpaca credentials')
|
|
37
39
|
|
|
38
|
-
def
|
|
40
|
+
def fill_orders(
|
|
41
|
+
self,
|
|
42
|
+
symbols: Iterable[str],
|
|
43
|
+
func: callable,
|
|
44
|
+
**kwargs: dict[str, any]
|
|
45
|
+
) -> list[dict[str, any]]:
|
|
46
|
+
pending_orders = set()
|
|
47
|
+
completed_orders = []
|
|
48
|
+
for symbol in symbols:
|
|
49
|
+
order = func(symbol, **kwargs)
|
|
50
|
+
if order['status'] == 'filled':
|
|
51
|
+
completed_orders.append(order)
|
|
52
|
+
else:
|
|
53
|
+
pending_orders.add(order['id'])
|
|
54
|
+
while pending_orders:
|
|
55
|
+
for id in list(pending_orders):
|
|
56
|
+
order = self.get_order(id)
|
|
57
|
+
if order['status'] == 'filled':
|
|
58
|
+
completed_orders.append(order)
|
|
59
|
+
pending_orders.discard(id)
|
|
60
|
+
sleep(1)
|
|
61
|
+
return completed_orders
|
|
62
|
+
|
|
63
|
+
def make_request(
|
|
64
|
+
self,
|
|
65
|
+
method: str,
|
|
66
|
+
route: str,
|
|
67
|
+
payload: Optional[dict[str, any]] = {}
|
|
68
|
+
) -> any:
|
|
39
69
|
parts = [self.base, self.version, route]
|
|
40
70
|
url = '/'.join(parts)
|
|
41
71
|
headers = {
|
|
@@ -49,25 +79,32 @@ class AlpacaEx(CEX):
|
|
|
49
79
|
else:
|
|
50
80
|
raise Exception(response.text)
|
|
51
81
|
|
|
52
|
-
def get_positions(self):
|
|
82
|
+
def get_positions(self) -> any:
|
|
53
83
|
return self.make_request('GET', 'positions')
|
|
54
84
|
|
|
55
|
-
def close_position(self, symbol):
|
|
85
|
+
def close_position(self, symbol: str) -> any:
|
|
56
86
|
return self.make_request('DELETE', f'positions/{symbol}')
|
|
57
87
|
|
|
58
|
-
def get_order(self, id):
|
|
88
|
+
def get_order(self, id: str) -> any:
|
|
59
89
|
return self.make_request('GET', f'orders/{id}')
|
|
60
90
|
|
|
61
|
-
def get_account(self):
|
|
91
|
+
def get_account(self) -> any:
|
|
62
92
|
return self.make_request('GET', 'account')
|
|
63
93
|
|
|
64
|
-
def create_order(
|
|
94
|
+
def create_order(
|
|
95
|
+
self,
|
|
96
|
+
symbol: str,
|
|
97
|
+
side: str,
|
|
98
|
+
notional: Union[int, float, str]
|
|
99
|
+
) -> any:
|
|
65
100
|
payload = {
|
|
66
101
|
'symbol': symbol,
|
|
67
102
|
'side': side.lower(),
|
|
68
103
|
'type': 'market',
|
|
69
104
|
'notional': str(notional),
|
|
70
|
-
'time_in_force':
|
|
105
|
+
'time_in_force': (
|
|
106
|
+
'gtc' if symbol in C.ALPC_CRYPTO_SYMBOLS else 'day'
|
|
107
|
+
)
|
|
71
108
|
}
|
|
72
109
|
return self.make_request('POST', 'orders', payload)
|
|
73
110
|
|
|
@@ -368,7 +405,10 @@ class Binance(CEX):
|
|
|
368
405
|
params[quantity_label] = quantity
|
|
369
406
|
|
|
370
407
|
params['side'] = side
|
|
371
|
-
fx =
|
|
408
|
+
fx = (
|
|
409
|
+
self.client.create_test_order
|
|
410
|
+
if test else self.client.create_order
|
|
411
|
+
)
|
|
372
412
|
|
|
373
413
|
order = fx(**params)
|
|
374
414
|
return order
|
|
@@ -17,6 +17,7 @@ from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
|
|
|
17
17
|
from sklearn.metrics import classification_report
|
|
18
18
|
from imblearn.over_sampling import SMOTE
|
|
19
19
|
from Calculus import Calculator
|
|
20
|
+
import Constants as C
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class Historian:
|
|
@@ -26,19 +27,86 @@ class Historian:
|
|
|
26
27
|
# add fx to perform calculations on columns
|
|
27
28
|
# takes calc.fx, df, and column names as args, fx args
|
|
28
29
|
|
|
29
|
-
def
|
|
30
|
+
def from_holding(self, close, init_cash=1000):
|
|
30
31
|
# returns a portfolio based on buy and hold strategy
|
|
31
32
|
portfolio = vbt.Portfolio.from_holding(
|
|
32
33
|
close, init_cash=init_cash, freq='D')
|
|
33
34
|
return portfolio
|
|
34
35
|
|
|
35
|
-
def
|
|
36
|
+
def from_signals(self, close, signals, init_cash=1000, fee=0):
|
|
36
37
|
# returns a portfolio based on signals
|
|
37
38
|
portfolio = vbt.Portfolio.from_signals(
|
|
38
39
|
close, signals, ~signals, init_cash=init_cash, freq='D', fees=fee
|
|
39
40
|
)
|
|
40
41
|
return portfolio
|
|
41
42
|
|
|
43
|
+
def optimize_portfolio(
|
|
44
|
+
self,
|
|
45
|
+
close: pd.DataFrame,
|
|
46
|
+
indicator: callable,
|
|
47
|
+
top_n: int,
|
|
48
|
+
period: str,
|
|
49
|
+
init_cash: float,
|
|
50
|
+
**kwargs: dict[str, any]
|
|
51
|
+
) -> vbt.Portfolio:
|
|
52
|
+
if C.CLOSE in close.columns:
|
|
53
|
+
close = close.set_index(C.CLOSE)
|
|
54
|
+
signals = close.apply(indicator, **kwargs)
|
|
55
|
+
close = close.dropna()
|
|
56
|
+
positions = pd.DataFrame(
|
|
57
|
+
0, index=close.index, columns=close.columns)
|
|
58
|
+
holdings = {"cash": init_cash}
|
|
59
|
+
prev_period = None
|
|
60
|
+
prev_symbols = set()
|
|
61
|
+
for day in close.index:
|
|
62
|
+
curr_period = getattr(day, period)
|
|
63
|
+
# if is first of the period
|
|
64
|
+
if prev_period != curr_period:
|
|
65
|
+
# Rank symbols by indicator and select top_n
|
|
66
|
+
top_symbols = set(signals.loc[day].nlargest(top_n).index)
|
|
67
|
+
minus, plus = self.calc.get_difference(
|
|
68
|
+
prev_symbols, top_symbols)
|
|
69
|
+
# Sell old positions for the top symbols
|
|
70
|
+
for symbol in minus:
|
|
71
|
+
size = holdings[symbol]
|
|
72
|
+
positions.loc[day, symbol] = - size
|
|
73
|
+
holdings["cash"] += close.loc[day][symbol] * size
|
|
74
|
+
del holdings[symbol]
|
|
75
|
+
# Buy new positions for the top symbols
|
|
76
|
+
notional = holdings["cash"] / len(plus)
|
|
77
|
+
for symbol in plus:
|
|
78
|
+
size = notional / close.loc[day][symbol]
|
|
79
|
+
positions.loc[day, symbol] = size
|
|
80
|
+
holdings[symbol] = size
|
|
81
|
+
holdings["cash"] -= notional
|
|
82
|
+
# Update prev values
|
|
83
|
+
prev_period = curr_period
|
|
84
|
+
prev_symbols = top_symbols
|
|
85
|
+
|
|
86
|
+
# Forward fill positions to maintain holdings
|
|
87
|
+
positions = positions.ffill().fillna(0)
|
|
88
|
+
|
|
89
|
+
# Convert to orders format
|
|
90
|
+
portfolio = vbt.Portfolio.from_orders(
|
|
91
|
+
close=close,
|
|
92
|
+
size=positions,
|
|
93
|
+
freq='D',
|
|
94
|
+
init_cash=0,
|
|
95
|
+
group_by=True
|
|
96
|
+
)
|
|
97
|
+
return portfolio
|
|
98
|
+
|
|
99
|
+
def from_orders(
|
|
100
|
+
self,
|
|
101
|
+
close: pd.DataFrame,
|
|
102
|
+
size: pd.DataFrame,
|
|
103
|
+
fee: float = 0
|
|
104
|
+
) -> vbt.Portfolio:
|
|
105
|
+
portfolio = vbt.Portfolio.from_orders(
|
|
106
|
+
close, size, freq='D', fees=fee, init_cash=0, group_by=True
|
|
107
|
+
)
|
|
108
|
+
return portfolio
|
|
109
|
+
|
|
42
110
|
def fill(self, arr, method='ffill', type='bool'):
|
|
43
111
|
# forward fills or nearest fills an array
|
|
44
112
|
df = pd.DataFrame(arr)
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
from sklearn.decomposition import PCA
|
|
3
|
+
from autogluon.tabular import TabularDataset, TabularPredictor
|
|
4
|
+
import pandas as pd
|
|
3
5
|
from FileOps import FileReader, FileWriter
|
|
4
6
|
from Calculus import Calculator
|
|
5
7
|
import Constants as C
|
|
@@ -11,8 +13,12 @@ class Oracle:
|
|
|
11
13
|
self.writer = FileWriter()
|
|
12
14
|
self.calc = Calculator()
|
|
13
15
|
|
|
14
|
-
def get_filename(self, name):
|
|
15
|
-
return f'models/latest/{name}.
|
|
16
|
+
def get_filename(self, name, ext='pkl'):
|
|
17
|
+
return f'models/latest/{name}.{ext}'
|
|
18
|
+
|
|
19
|
+
def load_metadata(self):
|
|
20
|
+
filename = self.get_filename('metadata', 'json')
|
|
21
|
+
return self.reader.load_json(filename)
|
|
16
22
|
|
|
17
23
|
def load_model_pickle(self, name):
|
|
18
24
|
filename = self.get_filename(name)
|
|
@@ -23,7 +29,14 @@ class Oracle:
|
|
|
23
29
|
return self.writer.save_pickle(filename, data)
|
|
24
30
|
|
|
25
31
|
def predict(self, data):
|
|
26
|
-
|
|
32
|
+
model_path = 'models/latest/autogluon'
|
|
33
|
+
self.reader.store.download_dir(model_path)
|
|
34
|
+
model = TabularPredictor.load(model_path)
|
|
35
|
+
if (
|
|
36
|
+
isinstance(model, TabularPredictor) and not
|
|
37
|
+
isinstance(data, TabularDataset)
|
|
38
|
+
):
|
|
39
|
+
data = TabularDataset(data)
|
|
27
40
|
return model.predict(data)
|
|
28
41
|
|
|
29
42
|
def visualize(self, X, y, dimensions, refinement, increase_percent=0):
|
|
@@ -49,7 +62,10 @@ class Oracle:
|
|
|
49
62
|
flattened = [arr.flatten() for arr in unflattened]
|
|
50
63
|
reduced = np.array(flattened).T
|
|
51
64
|
unreduced = reducer.inverse_transform(reduced)
|
|
52
|
-
|
|
65
|
+
metadata = self.load_metadata()
|
|
66
|
+
features = metadata['features']
|
|
67
|
+
data = pd.DataFrame(unreduced, columns=features[:unreduced.shape[1]])
|
|
68
|
+
preds = self.predict(data).astype(int).to_numpy()
|
|
53
69
|
actual = [
|
|
54
70
|
{
|
|
55
71
|
C.BUY: [
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import os
|
|
2
|
-
from datetime import datetime
|
|
2
|
+
from datetime import datetime, timedelta
|
|
3
3
|
import boto3
|
|
4
4
|
from botocore.exceptions import ClientError
|
|
5
5
|
from dotenv import load_dotenv, find_dotenv
|
|
6
6
|
from multiprocessing import Pool
|
|
7
7
|
from Constants import PathFinder
|
|
8
8
|
import Constants as C
|
|
9
|
+
# from typing import Optional
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
class Store:
|
|
@@ -33,18 +34,18 @@ class Store:
|
|
|
33
34
|
with Pool() as p:
|
|
34
35
|
p.map(self.upload_file, paths)
|
|
35
36
|
|
|
36
|
-
def delete_objects(self, keys):
|
|
37
|
+
def delete_objects(self, keys: list[str]) -> None:
|
|
37
38
|
if keys:
|
|
38
39
|
objects = [{'Key': key.replace('\\', '/')} for key in keys]
|
|
39
40
|
bucket = self.get_bucket()
|
|
40
41
|
bucket.delete_objects(Delete={'Objects': objects})
|
|
41
42
|
|
|
42
|
-
def
|
|
43
|
+
def get_keys(self, filter: str = '') -> list[str]:
|
|
43
44
|
bucket = self.get_bucket()
|
|
44
|
-
keys = [obj.key for obj in bucket.objects.filter()]
|
|
45
|
+
keys = [obj.key for obj in bucket.objects.filter(Prefix=filter)]
|
|
45
46
|
return keys
|
|
46
47
|
|
|
47
|
-
def key_exists(self, key, download=False):
|
|
48
|
+
def key_exists(self, key: str, download=False) -> bool:
|
|
48
49
|
key = key.replace('\\', '/')
|
|
49
50
|
try:
|
|
50
51
|
if download:
|
|
@@ -57,7 +58,7 @@ class Store:
|
|
|
57
58
|
else:
|
|
58
59
|
return True
|
|
59
60
|
|
|
60
|
-
def download_file(self, key):
|
|
61
|
+
def download_file(self, key: str) -> None:
|
|
61
62
|
try:
|
|
62
63
|
self.finder.make_path(key)
|
|
63
64
|
with open(key, 'wb') as file:
|
|
@@ -69,7 +70,12 @@ class Store:
|
|
|
69
70
|
os.remove(key)
|
|
70
71
|
raise e
|
|
71
72
|
|
|
72
|
-
def
|
|
73
|
+
def download_dir(self, path: str) -> None:
|
|
74
|
+
keys = self.get_keys(path)
|
|
75
|
+
with Pool() as p:
|
|
76
|
+
p.starmap(self.key_exists, zip(keys, [True] * len(keys)))
|
|
77
|
+
|
|
78
|
+
def copy_object(self, src: str, dst: str) -> None:
|
|
73
79
|
src = src.replace('\\', '/')
|
|
74
80
|
dst = dst.replace('\\', '/')
|
|
75
81
|
bucket = self.get_bucket()
|
|
@@ -79,20 +85,20 @@ class Store:
|
|
|
79
85
|
}
|
|
80
86
|
bucket.copy(copy_source, dst)
|
|
81
87
|
|
|
82
|
-
def rename_key(self, old_key, new_key):
|
|
88
|
+
def rename_key(self, old_key: str, new_key: str) -> None:
|
|
83
89
|
old_key = old_key.replace('\\', '/')
|
|
84
90
|
new_key = new_key.replace('\\', '/')
|
|
85
91
|
self.copy_object(old_key, new_key)
|
|
86
92
|
self.delete_objects([old_key])
|
|
87
93
|
|
|
88
|
-
def last_modified(self, key):
|
|
94
|
+
def last_modified(self, key: str) -> datetime:
|
|
89
95
|
key = key.replace('\\', '/')
|
|
90
96
|
bucket = self.get_bucket()
|
|
91
97
|
obj = bucket.Object(key)
|
|
92
98
|
then = obj.last_modified.replace(tzinfo=None)
|
|
93
99
|
return then
|
|
94
100
|
|
|
95
|
-
def modified_delta(self, key):
|
|
101
|
+
def modified_delta(self, key: str) -> timedelta:
|
|
96
102
|
key = key.replace('\\', '/')
|
|
97
103
|
then = self.last_modified(key)
|
|
98
104
|
now = datetime.utcnow()
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from time import sleep
|
|
2
|
+
from typing import Union
|
|
3
|
+
from datetime import datetime, timedelta, tzinfo
|
|
4
|
+
from Constants import TZ, UTC, DATE_FMT, TIME_FMT, PRECISE_TIME_FMT
|
|
5
|
+
|
|
6
|
+
FlexibleDate = Union[datetime, str]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TimeTraveller:
|
|
10
|
+
"""
|
|
11
|
+
A class to handle time-related operations, such as calculating deltas,
|
|
12
|
+
converting timeframes, and managing sleep intervals.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def get_delta(
|
|
16
|
+
self,
|
|
17
|
+
d1: FlexibleDate,
|
|
18
|
+
d2: FlexibleDate = datetime.now(),
|
|
19
|
+
format: str = DATE_FMT
|
|
20
|
+
) -> timedelta:
|
|
21
|
+
"""
|
|
22
|
+
Calculate the difference between two dates.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
d1 (FlexibleDate):
|
|
26
|
+
The first date, can be a datetime object or a string.
|
|
27
|
+
d2 (FlexibleDate):
|
|
28
|
+
The second date, defaults to the current time.
|
|
29
|
+
format (str):
|
|
30
|
+
The format to parse the date strings, defaults to DATE_FMT.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
timedelta: The absolute difference between the two dates.
|
|
34
|
+
"""
|
|
35
|
+
if isinstance(d1, str):
|
|
36
|
+
d1 = datetime.strptime(d1, format)
|
|
37
|
+
if isinstance(d2, str):
|
|
38
|
+
d2 = datetime.strptime(d2, format)
|
|
39
|
+
|
|
40
|
+
return abs(d2 - d1)
|
|
41
|
+
|
|
42
|
+
def convert_timeframe(self, d1: FlexibleDate, d2: FlexibleDate) -> str:
|
|
43
|
+
"""
|
|
44
|
+
Convert two datetime objects
|
|
45
|
+
to a string representation of the timeframe.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
d1 (FlexibleDate):
|
|
49
|
+
The first date, can be a datetime object or a string.
|
|
50
|
+
d2 (FlexibleDate):
|
|
51
|
+
The second date, can be a datetime object or a string.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
str: A string representation of the timeframe in days.
|
|
55
|
+
"""
|
|
56
|
+
delta = self.get_delta(d1, d2)
|
|
57
|
+
days = delta.days
|
|
58
|
+
return f'{days}d'
|
|
59
|
+
|
|
60
|
+
def convert_delta(self, timeframe: str) -> timedelta:
|
|
61
|
+
"""
|
|
62
|
+
Convert a timeframe string to a timedelta object.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
timeframe (str):
|
|
66
|
+
A string representing the timeframe,
|
|
67
|
+
e.g., '1d', '2w', '3m', '1y'.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
timedelta: A timedelta object representing the specified timeframe.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
ValueError: If the timeframe string is not in a supported format.
|
|
74
|
+
"""
|
|
75
|
+
if timeframe == 'max':
|
|
76
|
+
return timedelta(days=36500)
|
|
77
|
+
|
|
78
|
+
periods = {'y': 365, 'm': 30, 'w': 7, 'd': 1}
|
|
79
|
+
period = 'y'
|
|
80
|
+
idx = -1
|
|
81
|
+
|
|
82
|
+
for curr_period in periods:
|
|
83
|
+
idx = timeframe.find(curr_period)
|
|
84
|
+
if idx != -1:
|
|
85
|
+
period = curr_period
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
if idx == -1:
|
|
89
|
+
supported = ', '.join(list(periods))
|
|
90
|
+
error_msg = f'Only certain suffixes ({supported}) are supported.'
|
|
91
|
+
raise ValueError(error_msg)
|
|
92
|
+
|
|
93
|
+
num = int(timeframe[:idx])
|
|
94
|
+
days = periods[period] * num
|
|
95
|
+
delta = timedelta(days=days)
|
|
96
|
+
|
|
97
|
+
return delta
|
|
98
|
+
|
|
99
|
+
def convert_dates(
|
|
100
|
+
self,
|
|
101
|
+
timeframe: str,
|
|
102
|
+
format: str = DATE_FMT
|
|
103
|
+
) -> tuple[FlexibleDate, FlexibleDate]:
|
|
104
|
+
"""
|
|
105
|
+
Convert a timeframe to a start and end date.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
timeframe (str):
|
|
109
|
+
A string representing the timeframe,
|
|
110
|
+
e.g., '1d', '2w', '3m', '1y'.
|
|
111
|
+
format (str):
|
|
112
|
+
The format to return the dates in, defaults to DATE_FMT.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
tuple[FlexibleDate, FlexibleDate]:
|
|
116
|
+
A tuple containing the start and end dates as strings.
|
|
117
|
+
"""
|
|
118
|
+
# if timeframe='max': timeframe = '25y'
|
|
119
|
+
end = datetime.now(TZ) - self.convert_delta('1d')
|
|
120
|
+
delta = self.convert_delta(timeframe) - self.convert_delta('1d')
|
|
121
|
+
start = end - delta
|
|
122
|
+
if format:
|
|
123
|
+
start = start.strftime(format)
|
|
124
|
+
end = end.strftime(format)
|
|
125
|
+
return start, end
|
|
126
|
+
|
|
127
|
+
def dates_in_range(self, timeframe: str, format: str = DATE_FMT
|
|
128
|
+
) -> list[FlexibleDate]:
|
|
129
|
+
"""
|
|
130
|
+
Get a list of dates in the specified timeframe.
|
|
131
|
+
Args:
|
|
132
|
+
timeframe (str):
|
|
133
|
+
A string representing the timeframe,
|
|
134
|
+
e.g., '1d', '2w', '3m', '1y'.
|
|
135
|
+
format (str):
|
|
136
|
+
The format to return the dates in, defaults to DATE_FMT.
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
list[FlexibleDate]: A list of dates in the specified timeframe.
|
|
140
|
+
"""
|
|
141
|
+
start, end = self.convert_dates(timeframe, None)
|
|
142
|
+
dates = [start + timedelta(days=x)
|
|
143
|
+
for x in range(0, (end - start).days + 1)]
|
|
144
|
+
if format:
|
|
145
|
+
dates = [date.strftime(format) for date in dates]
|
|
146
|
+
return dates
|
|
147
|
+
|
|
148
|
+
def get_time(self, time: str) -> datetime.time:
|
|
149
|
+
"""
|
|
150
|
+
Converts time string to a time object.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
time (str):
|
|
154
|
+
A string representing the time, e.g., '14:30', '14:30:00'.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
datetime.time: A time object representing the specified time.
|
|
158
|
+
"""
|
|
159
|
+
return datetime.strptime(
|
|
160
|
+
time, TIME_FMT if len(time.split(':')) == 2 else PRECISE_TIME_FMT
|
|
161
|
+
).time()
|
|
162
|
+
|
|
163
|
+
def combine_date_time(self, date: str, time: str) -> datetime:
|
|
164
|
+
"""
|
|
165
|
+
Combines date and time into a datetime object.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
date (str):
|
|
169
|
+
A string representing the date, e.g., '2025-01-01'.
|
|
170
|
+
time (str):
|
|
171
|
+
A string representing the time, e.g., '14:30', '14:30:00'.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
datetime: A datetime object combining the specified date and time.
|
|
175
|
+
"""
|
|
176
|
+
date = datetime.strptime(date, DATE_FMT)
|
|
177
|
+
time = self.get_time(time)
|
|
178
|
+
return date.combine(date, time)
|
|
179
|
+
|
|
180
|
+
def get_diff(self, t1: datetime, t2: datetime) -> float:
|
|
181
|
+
"""
|
|
182
|
+
Get the difference in seconds between two datetime objects.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
t1 (datetime):
|
|
186
|
+
The first datetime object.
|
|
187
|
+
t2 (datetime):
|
|
188
|
+
The second datetime object.
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
float: The absolute difference in seconds
|
|
192
|
+
between the two datetimes.
|
|
193
|
+
"""
|
|
194
|
+
return abs((t1 - t2).total_seconds())
|
|
195
|
+
|
|
196
|
+
def sleep_until(self, time: str, tz: tzinfo = UTC) -> None:
|
|
197
|
+
"""
|
|
198
|
+
Sleep until the specified time in the given timezone.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
time (str):
|
|
202
|
+
A string representing the time to sleep until, e.g., '14:30'.
|
|
203
|
+
tz (tzinfo):
|
|
204
|
+
The timezone to use for the time, defaults to UTC.
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
None: This function does not return anything.
|
|
208
|
+
"""
|
|
209
|
+
# time could be "00:00"
|
|
210
|
+
curr = datetime.now(tz)
|
|
211
|
+
prev_sched = datetime.combine(curr.date(), self.get_time(time), tz)
|
|
212
|
+
next_sched = prev_sched + timedelta(days=1)
|
|
213
|
+
|
|
214
|
+
prev_diff = self.get_diff(curr, prev_sched)
|
|
215
|
+
next_diff = self.get_diff(curr, next_sched)
|
|
216
|
+
|
|
217
|
+
sched = next_sched if next_diff < prev_diff else prev_sched
|
|
218
|
+
diff = self.get_diff(curr, sched) if sched > curr else 0
|
|
219
|
+
|
|
220
|
+
while diff > 0:
|
|
221
|
+
curr = datetime.now(tz)
|
|
222
|
+
diff = self.get_diff(curr, sched) if sched > curr else 0
|
|
223
|
+
sleep(diff)
|
|
224
|
+
|
|
225
|
+
def convert_date(self, date: FlexibleDate) -> str:
|
|
226
|
+
"""
|
|
227
|
+
Convert a date to a string in the specified format.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
date (FlexibleDate):
|
|
231
|
+
A date that can be a datetime object or a string.
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
str: A string representation of the date in the specified format.
|
|
235
|
+
"""
|
|
236
|
+
return date if isinstance(date, str) else date.strftime(DATE_FMT)
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: hyperdrive
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.15.2
|
|
4
4
|
Summary: An algorithmic trading platform
|
|
5
5
|
Home-page: https://github.com/suchak1/hyperdrive
|
|
6
6
|
Author: Krish Suchak
|
|
7
7
|
Author-email: suchak.krish@gmail.com
|
|
8
|
-
License: UNKNOWN
|
|
9
8
|
Project-URL: Bug Reports, https://github.com/suchak1/hyperdrive/issues
|
|
10
9
|
Project-URL: Source, https://github.com/suchak1/hyperdrive
|
|
11
|
-
Platform: UNKNOWN
|
|
12
10
|
Requires-Python: >=3.7
|
|
13
11
|
Description-Content-Type: text/markdown
|
|
14
12
|
License-File: LICENSE
|
|
@@ -26,7 +24,7 @@ License-File: LICENSE
|
|
|
26
24
|
<!-- green left, gray right https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=brightgreen&right_color=gray&left_text=Downloads-->
|
|
27
25
|
<!-- black and indigo https://static.pepy.tech/personalized-badge/hyperdrive?period=total&units=international_system&left_color=black&right_color=indigo&left_text=Downloads -->
|
|
28
26
|
|
|
29
|
-
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/
|
|
27
|
+
**_hyperdrive_** is an algorithmic trading library that powers quant research firm [<img src="https://raw.githubusercontent.com/suchak1/hyperdrive/master/img/logo.png" width="16" /> **Algotrade.io**](https://algotrade.io).
|
|
30
28
|
|
|
31
29
|
Unlike other backtesting libraries, _`hyperdrive`_ specializes in data collection and quantitative research.
|
|
32
30
|
|
|
@@ -159,9 +157,9 @@ timeframe = '1y'
|
|
|
159
157
|
|
|
160
158
|
df = md.get_ohlc(symbol=symbol, timeframe=timeframe)
|
|
161
159
|
|
|
162
|
-
holding = hist.
|
|
160
|
+
holding = hist.from_holding(df[C.CLOSE])
|
|
163
161
|
signals = hist.get_optimal_signals(df[C.CLOSE])
|
|
164
|
-
my_strat = hist.
|
|
162
|
+
my_strat = hist.from_signals(df[C.CLOSE], signals)
|
|
165
163
|
|
|
166
164
|
metrics = [
|
|
167
165
|
'Total Return [%]', 'Benchmark Return [%]',
|
|
@@ -300,5 +298,3 @@ Available data collection functions:
|
|
|
300
298
|
```
|
|
301
299
|
|
|
302
300
|
```
|
|
303
|
-
|
|
304
|
-
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
python-dotenv==1.1.0
|
|
2
|
+
pandas==2.2.3
|
|
3
|
+
robin-stocks==3.4.0
|
|
4
|
+
boto3==1.38.13
|
|
5
|
+
polygon-api-client==1.11.0
|
|
6
|
+
pytz==2025.2
|
|
7
|
+
vectorbt==0.27.3
|
|
8
|
+
scipy==1.15.3
|
|
9
|
+
scikit-learn==1.6.1
|
|
10
|
+
cryptography==44.0.3
|
|
11
|
+
ta==0.11.0
|
|
12
|
+
python-binance==1.0.28
|
|
13
|
+
imbalanced-learn==0.13.0
|
|
14
|
+
icosphere==0.1.3
|
|
15
|
+
numpy==1.26.4
|
|
16
|
+
beautifulsoup4==4.13.4
|
|
17
|
+
lxml==5.4.0
|
|
18
|
+
autogluon==1.3.0
|
|
19
|
+
selenium
|
|
@@ -120,7 +120,7 @@ class TestMarketData:
|
|
|
120
120
|
os.rename(splt_path, temp_path)
|
|
121
121
|
|
|
122
122
|
for _ in range(retries):
|
|
123
|
-
poly.save_splits(symbol=symbol, timeframe='
|
|
123
|
+
poly.save_splits(symbol=symbol, timeframe='2y', retries=1, delay=0)
|
|
124
124
|
if not md.reader.check_file_exists(splt_path):
|
|
125
125
|
delay = choice(range(5, 10))
|
|
126
126
|
sleep(delay)
|
|
@@ -179,6 +179,7 @@ class TestMarketData:
|
|
|
179
179
|
os.rename(temp_path, ohlc_path)
|
|
180
180
|
|
|
181
181
|
def test_save_intraday(self):
|
|
182
|
+
sleep(C.POLY_FREE_DELAY)
|
|
182
183
|
symbol = 'NFLX'
|
|
183
184
|
timeframe = '4d'
|
|
184
185
|
dates = md.traveller.dates_in_range(timeframe)
|
|
@@ -20,6 +20,17 @@ class TestAlpacaEx:
|
|
|
20
20
|
assert hasattr(alpc, 'token')
|
|
21
21
|
assert hasattr(alpc, 'secret')
|
|
22
22
|
|
|
23
|
+
def test_fill_orders(self):
|
|
24
|
+
positions = alpc.get_positions()
|
|
25
|
+
if any([position['symbol'] == 'LTC/USD' for position in positions]):
|
|
26
|
+
orders = alpc.fill_orders(['LTC/USD'], alpc.close_position)
|
|
27
|
+
else:
|
|
28
|
+
orders = alpc.fill_orders(
|
|
29
|
+
['LTC/USD'], alpc.create_order, side='buy', notional=10)
|
|
30
|
+
|
|
31
|
+
for order in orders:
|
|
32
|
+
assert 'id' in order
|
|
33
|
+
|
|
23
34
|
def test_make_request(self):
|
|
24
35
|
acct = alpc.make_request('GET', 'account')
|
|
25
36
|
assert acct['status'] == 'ACTIVE'
|
|
@@ -33,8 +44,8 @@ class TestAlpacaEx:
|
|
|
33
44
|
|
|
34
45
|
def test_close_position(self):
|
|
35
46
|
positions = alpc.get_positions()
|
|
36
|
-
if any([position['symbol'] == '
|
|
37
|
-
order = alpc.close_position('
|
|
47
|
+
if any([position['symbol'] == 'LTC/USD' for position in positions]):
|
|
48
|
+
order = alpc.close_position('LTC/USD')
|
|
38
49
|
assert 'id' in order
|
|
39
50
|
|
|
40
51
|
def test_get_order(self):
|
|
@@ -48,9 +59,9 @@ class TestAlpacaEx:
|
|
|
48
59
|
def test_create_order(self):
|
|
49
60
|
positions = alpc.get_positions()
|
|
50
61
|
side = 'buy'
|
|
51
|
-
if '
|
|
62
|
+
if 'LTC/USD' in [position['symbol'] for position in positions]:
|
|
52
63
|
side = 'sell'
|
|
53
|
-
order = alpc.create_order('
|
|
64
|
+
order = alpc.create_order('LTC/USD', side, 10)
|
|
54
65
|
assert 'id' in order
|
|
55
66
|
|
|
56
67
|
|
|
@@ -150,9 +161,8 @@ class TestKraken:
|
|
|
150
161
|
except Exception as e:
|
|
151
162
|
# if Kraken balance is low/zero, then tests may fail
|
|
152
163
|
exception_name = e.__str__()
|
|
153
|
-
vol_error = "['EGeneral:Invalid arguments:volume']"
|
|
154
|
-
|
|
155
|
-
if not (exception_name == vol_error and binance_preferred):
|
|
164
|
+
vol_error = "['EGeneral:Invalid arguments:volume minimum not met']"
|
|
165
|
+
if not (exception_name == vol_error):
|
|
156
166
|
raise e
|
|
157
167
|
|
|
158
168
|
def test_standardize_order(self):
|
|
@@ -170,10 +180,12 @@ class TestKraken:
|
|
|
170
180
|
('type', 'MARKET'),
|
|
171
181
|
('side', 'SELL'),
|
|
172
182
|
('fills',
|
|
173
|
-
[OrderedDict(
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
183
|
+
[OrderedDict(
|
|
184
|
+
[('price', '0.9999'),
|
|
185
|
+
('qty', '5.41394641'),
|
|
186
|
+
('commission', '0.01082681'),
|
|
187
|
+
('tradeId', 'TZX2YO-WCZN5-6GIH3E')]
|
|
188
|
+
)])])
|
|
177
189
|
assert std_order == expected
|
|
178
190
|
|
|
179
191
|
|
|
@@ -3,6 +3,7 @@ import numpy as np
|
|
|
3
3
|
import pandas as pd
|
|
4
4
|
sys.path.append('hyperdrive')
|
|
5
5
|
from History import Historian # noqa autopep8
|
|
6
|
+
import Constants as C # noqa autopep8
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
hist = Historian()
|
|
@@ -27,14 +28,35 @@ data = np.arange(total)
|
|
|
27
28
|
X = pd.DataFrame({'i': data, 'j': data})
|
|
28
29
|
y = np.array([True] * majority + [False] * minority)
|
|
29
30
|
|
|
31
|
+
orders_index = pd.to_datetime(
|
|
32
|
+
pd.Series(['2025-01-01', '2025-01-02'], name=C.TIME))
|
|
33
|
+
orders_close = pd.DataFrame({
|
|
34
|
+
'AAPL': [200, 100],
|
|
35
|
+
'META': [25, 50]
|
|
36
|
+
}, index=orders_index)
|
|
37
|
+
|
|
30
38
|
|
|
31
39
|
class TestHistorian:
|
|
32
|
-
def
|
|
33
|
-
stats = hist.
|
|
40
|
+
def test_from_holding(self):
|
|
41
|
+
stats = hist.from_holding(close).stats()
|
|
42
|
+
assert 'Sortino Ratio' in stats
|
|
43
|
+
|
|
44
|
+
def test_from_signals(self):
|
|
45
|
+
stats = hist.from_signals(close, test_ffill).stats()
|
|
46
|
+
assert 'Sortino Ratio' in stats
|
|
47
|
+
|
|
48
|
+
def test_from_orders(self):
|
|
49
|
+
size = pd.DataFrame({
|
|
50
|
+
'AAPL': [1, 0],
|
|
51
|
+
'META': [0, 1]
|
|
52
|
+
}, index=orders_index)
|
|
53
|
+
stats = hist.from_orders(orders_close, size).stats()
|
|
34
54
|
assert 'Sortino Ratio' in stats
|
|
35
55
|
|
|
36
|
-
def
|
|
37
|
-
|
|
56
|
+
def test_optimize_portfolio(self):
|
|
57
|
+
indicator = pd.Series.diff
|
|
58
|
+
stats = hist.optimize_portfolio(
|
|
59
|
+
orders_close, indicator, 1, 'day', 225).stats()
|
|
38
60
|
assert 'Sortino Ratio' in stats
|
|
39
61
|
|
|
40
62
|
def test_fill(self):
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
3
4
|
sys.path.append('hyperdrive')
|
|
4
5
|
from Precognition import Oracle # noqa autopep8
|
|
5
6
|
from Utils import SwissArmyKnife # noqa autopep8
|
|
@@ -33,9 +34,12 @@ class TestOracle:
|
|
|
33
34
|
|
|
34
35
|
def test_predict(self):
|
|
35
36
|
metadata = oracle.reader.load_json('models/latest/metadata.json')
|
|
36
|
-
|
|
37
|
+
features = metadata['features']
|
|
38
|
+
num_features = metadata['num_pca'] or len(features)
|
|
37
39
|
data = np.full((1, num_features), 1)
|
|
38
|
-
|
|
40
|
+
features = metadata['features']
|
|
41
|
+
ds = pd.DataFrame(data, columns=features[:num_features])
|
|
42
|
+
pred = oracle.predict(ds)
|
|
39
43
|
assert pred.dtype == np.dtype(bool)
|
|
40
44
|
|
|
41
45
|
def test_visualize(self):
|
|
@@ -48,8 +48,8 @@ class TestStore:
|
|
|
48
48
|
store.delete_objects([test_file1, test_file2])
|
|
49
49
|
assert not store.key_exists(test_file2)
|
|
50
50
|
|
|
51
|
-
def
|
|
52
|
-
keys = set(store.
|
|
51
|
+
def test_get_keys(self):
|
|
52
|
+
keys = set(store.get_keys())
|
|
53
53
|
|
|
54
54
|
assert symbols_path in keys
|
|
55
55
|
assert 'README.md' in keys
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
from time import sleep
|
|
2
|
-
from datetime import datetime, timedelta
|
|
3
|
-
from Constants import TZ, UTC, DATE_FMT, TIME_FMT, PRECISE_TIME_FMT
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class TimeTraveller:
|
|
7
|
-
def get_delta(self, d1, d2, format=DATE_FMT):
|
|
8
|
-
if isinstance(d1, str):
|
|
9
|
-
d1 = datetime.strptime(d1, format)
|
|
10
|
-
if isinstance(d2, str):
|
|
11
|
-
d2 = datetime.strptime(d2, format)
|
|
12
|
-
|
|
13
|
-
return abs(d2 - d1)
|
|
14
|
-
|
|
15
|
-
def convert_delta(self, timeframe):
|
|
16
|
-
if timeframe == 'max':
|
|
17
|
-
return timedelta(days=36500)
|
|
18
|
-
|
|
19
|
-
periods = {'y': 365, 'm': 30, 'w': 7, 'd': 1}
|
|
20
|
-
period = 'y'
|
|
21
|
-
idx = -1
|
|
22
|
-
|
|
23
|
-
for curr_period in periods:
|
|
24
|
-
idx = timeframe.find(curr_period)
|
|
25
|
-
if idx != -1:
|
|
26
|
-
period = curr_period
|
|
27
|
-
break
|
|
28
|
-
|
|
29
|
-
if idx == -1:
|
|
30
|
-
supported = ', '.join(list(periods))
|
|
31
|
-
error_msg = f'Only certain suffixes ({supported}) are supported.'
|
|
32
|
-
raise ValueError(error_msg)
|
|
33
|
-
|
|
34
|
-
num = int(timeframe[:idx])
|
|
35
|
-
days = periods[period] * num
|
|
36
|
-
delta = timedelta(days=days)
|
|
37
|
-
|
|
38
|
-
return delta
|
|
39
|
-
|
|
40
|
-
def convert_dates(self, timeframe, format=DATE_FMT):
|
|
41
|
-
# if timeframe='max': timeframe = '25y'
|
|
42
|
-
end = datetime.now(TZ) - self.convert_delta('1d')
|
|
43
|
-
delta = self.convert_delta(timeframe) - self.convert_delta('1d')
|
|
44
|
-
start = end - delta
|
|
45
|
-
if format:
|
|
46
|
-
start = start.strftime(format)
|
|
47
|
-
end = end.strftime(format)
|
|
48
|
-
return start, end
|
|
49
|
-
|
|
50
|
-
def dates_in_range(self, timeframe, format=DATE_FMT):
|
|
51
|
-
start, end = self.convert_dates(timeframe, None)
|
|
52
|
-
dates = [start + timedelta(days=x)
|
|
53
|
-
for x in range(0, (end - start).days + 1)]
|
|
54
|
-
if format:
|
|
55
|
-
dates = [date.strftime(format) for date in dates]
|
|
56
|
-
return dates
|
|
57
|
-
|
|
58
|
-
def get_time(self, time):
|
|
59
|
-
return datetime.strptime(
|
|
60
|
-
time, TIME_FMT if len(time.split(':')) == 2 else PRECISE_TIME_FMT
|
|
61
|
-
).time()
|
|
62
|
-
|
|
63
|
-
def combine_date_time(self, date, time):
|
|
64
|
-
date = datetime.strptime(date, DATE_FMT)
|
|
65
|
-
time = self.get_time(time)
|
|
66
|
-
return date.combine(date, time)
|
|
67
|
-
|
|
68
|
-
def get_diff(self, t1, t2):
|
|
69
|
-
return abs((t1 - t2).total_seconds())
|
|
70
|
-
|
|
71
|
-
def sleep_until(self, time, tz=UTC):
|
|
72
|
-
# time could be "00:00"
|
|
73
|
-
curr = datetime.now(tz)
|
|
74
|
-
prev_sched = datetime.combine(curr.date(), self.get_time(time), tz)
|
|
75
|
-
next_sched = prev_sched + timedelta(days=1)
|
|
76
|
-
|
|
77
|
-
prev_diff = self.get_diff(curr, prev_sched)
|
|
78
|
-
next_diff = self.get_diff(curr, next_sched)
|
|
79
|
-
|
|
80
|
-
sched = next_sched if next_diff < prev_diff else prev_sched
|
|
81
|
-
diff = self.get_diff(curr, sched) if sched > curr else 0
|
|
82
|
-
|
|
83
|
-
while diff > 0:
|
|
84
|
-
curr = datetime.now(tz)
|
|
85
|
-
diff = self.get_diff(curr, sched) if sched > curr else 0
|
|
86
|
-
sleep(diff)
|
|
87
|
-
|
|
88
|
-
def convert_date(self, date):
|
|
89
|
-
return date if isinstance(date, str) else date.strftime(DATE_FMT)
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
python-dotenv==1.0.0
|
|
2
|
-
pandas==1.5.3
|
|
3
|
-
robin-stocks==3.3.0
|
|
4
|
-
boto3==1.26.165
|
|
5
|
-
polygon-api-client==1.10.1
|
|
6
|
-
pytz==2023.3
|
|
7
|
-
vectorbt==0.25.4
|
|
8
|
-
scipy==1.11.1
|
|
9
|
-
scikit-learn==0.24.2
|
|
10
|
-
auto-sklearn==0.15.0
|
|
11
|
-
cryptography==41.0.1
|
|
12
|
-
ta==0.10.2
|
|
13
|
-
python-binance==1.0.17
|
|
14
|
-
imbalanced-learn==0.8.1
|
|
15
|
-
icosphere==0.1.3
|
|
16
|
-
pynisher==0.6.4
|
|
17
|
-
numpy==1.23.5
|
|
18
|
-
beautifulsoup4==4.12.3
|
|
19
|
-
lxml==5.3.0
|
|
20
|
-
selenium
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|