forked from enarjord/passivbot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptimize.py
282 lines (247 loc) · 12.5 KB
/
optimize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import argparse
import asyncio
import glob
import json
import os
import pprint
import sys
from time import time
from typing import Union
import nevergrad as ng
import numpy as np
import psutil
import ray
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest import ConcurrencyLimiter
from ray.tune.suggest.nevergrad import NevergradSearch
from backtest import backtest
from backtest import plot_wrap
from downloader import Downloader
from procedures import prep_config, add_argparse_args
from pure_funcs import pack_config, unpack_config, get_template_live_config, ts_to_date, analyze_fills
from reporter import LogReporter
os.environ['TUNE_GLOBAL_CHECKPOINT_S'] = '240'
def create_config(config: dict) -> dict:
updated_ranges = {}
unpacked = unpack_config(get_template_live_config(config['n_spans']))
for k0 in unpacked:
if '£' in k0 or k0 in config['ranges']:
for k1 in config['ranges']:
if k1 in k0:
updated_ranges[k0] = config['ranges'][k1]
if 'leverage' in k0:
updated_ranges[k0] = [updated_ranges[k0][0],
min(updated_ranges[k0][1], config['max_leverage'])]
for k in updated_ranges:
if updated_ranges[k][0] == updated_ranges[k][1]:
unpacked[k] = updated_ranges[k][0]
else:
unpacked[k] = tune.uniform(updated_ranges[k][0], updated_ranges[k][1])
return {**config, **unpacked, **{'ranges': updated_ranges}}
def clean_start_config(start_config: dict, config: dict) -> dict:
clean_start = {}
for k, v in unpack_config(start_config).items():
if k in config:
if type(config[k]) == ray.tune.sample.Float or type(config[k]) == ray.tune.sample.Integer:
clean_start[k] = min(max(v, config['ranges'][k][0]), config['ranges'][k][1])
return clean_start
def clean_result_config(config: dict) -> dict:
for k, v in config.items():
if type(v) == np.float64:
config[k] = float(v)
if type(v) == np.int64 or type(v) == np.int32 or type(v) == np.int16 or type(v) == np.int8:
config[k] = int(v)
return config
def iter_slices_full_first(data, sliding_window_days, ticks_to_prepend, minimum_days):
yield data
for d in iter_slices(data, sliding_window_days, ticks_to_prepend, minimum_days):
yield d
def iter_slices(data, sliding_window_days: float, ticks_to_prepend: int = 0, minimum_days: float = 7.0):
sliding_window_ms = sliding_window_days * 24 * 60 * 60 * 1000
minimum_ms = minimum_days * 24 * 60 * 60 * 1000
span_ms = data[2][-1] - data[2][0]
if min(span_ms, sliding_window_ms) < minimum_ms:
raise Exception('time span too short')
if sliding_window_ms > span_ms:
yield data
return
n_windows = int(np.ceil(span_ms / sliding_window_ms)) + 1
thresholds_ms = np.linspace(data[2][ticks_to_prepend], data[2][-1] - sliding_window_ms, n_windows)
for threshold_ms in thresholds_ms[::-1]:
start_i = max(0, np.searchsorted(data[2], threshold_ms) - int(ticks_to_prepend))
end_i = np.searchsorted(data[2], threshold_ms + sliding_window_ms)
sspan = data[2][end_i] - data[2][start_i]
yield tuple(d[start_i:end_i] for d in data)
for ds in iter_slices(data, sliding_window_days * 2, ticks_to_prepend, minimum_days):
yield ds
def objective_function(analysis: dict, config: dict) -> float:
if analysis['n_fills'] == 0:
return -1.0
return (analysis['adjusted_daily_gain']
* min(1.0, config["maximum_hrs_no_fills"] / analysis["max_hrs_no_fills"])
* min(1.0, config["maximum_hrs_no_fills_same_side"] / analysis["max_hrs_no_fills_same_side"])
* min(1.0, analysis["closest_bkr"] / config["minimum_bankruptcy_distance"]))
def simple_sliding_window_wrap(config, data, do_print=False):
analyses = []
objective = 0.0
n_days = config['n_days']
sliding_window_days = max([config['maximum_hrs_no_fills'] / 24,
config['maximum_hrs_no_fills_same_side'] / 24,
config['sliding_window_days']]) * 1.05
data_slices = list(iter_slices(data, sliding_window_days, int(config['max_span']),
minimum_days=sliding_window_days * 0.95)) \
if config['sliding_window_days'] != 0.0 else [data]
n_slices = len(data_slices)
print('n_days', n_days, 'sliding_window_days', sliding_window_days, 'n_slices', n_slices)
for z, data_slice in enumerate(data_slices):
fills, info = backtest(pack_config(config), data_slice, do_print=do_print)
_, analysis = analyze_fills(fills, {**config, **{'lowest_eqbal_ratio': info[1], 'closest_bkr': info[2]}},
data_slice[2][max(0, min(len(data_slice[2]) - 1, int(config['max_span'])))],
data_slice[2][-1])
analysis['score'] = objective_function(analysis, config) * (analysis['n_days'] / n_days)
analyses.append(analysis)
#objective = np.mean([r['score'] for r in analyses]) * ((z + 1) / n_slices)
objective = np.mean([r['score'] for r in analyses]) * (2**(z + 1))
print(f'z {z}, n {n_slices}, adg {analysis["average_daily_gain"]:.4f}, bkr {analysis["closest_bkr"]:.4f}, '
f'eqbal {analysis["lowest_eqbal_ratio"]:.4f} n_days {analysis["n_days"]:.1f}, '
f'score {analysis["score"]:.4f}, objective {objective:.4f}, '
f'hrs stuck ss {str(round(analysis["max_hrs_no_fills_same_side"], 1)).zfill(4)}, '
f'scores {[round(e["score"], 2) for e in analyses]}, ')
bef = config['break_early_factor']
if bef > 0.0:
if analysis['closest_bkr'] < config['minimum_bankruptcy_distance'] * (1 - bef):
break
if analysis['max_hrs_no_fills'] > config['maximum_hrs_no_fills'] * (1 + bef):
break
if analysis['max_hrs_no_fills_same_side'] > config['maximum_hrs_no_fills_same_side'] * (1 + bef):
break
tune.report(objective=objective,
daily_gain=np.mean([r['average_daily_gain'] for r in analyses]),
closest_bankruptcy=np.min([r['closest_bkr'] for r in analyses]),
max_hrs_no_fills=np.max([r['max_hrs_no_fills'] for r in analyses]),
max_hrs_no_fills_same_side=np.max([r['max_hrs_no_fills_same_side'] for r in analyses]))
def tune_report(result):
tune.report(
objective=result["objective_gmean"],
daily_gain=result["daily_gains_gmean"],
closest_bankruptcy=result["closest_bkr"],
max_hrs_no_fills=result["max_hrs_no_fills"],
max_hrs_no_fills_same_side=result["max_hrs_no_fills_same_side"],
)
def backtest_tune(data: np.ndarray, config: dict, current_best: Union[dict, list] = None):
memory = int(np.sum([sys.getsizeof(d) for d in data]) * 1.2)
virtual_memory = psutil.virtual_memory()
if (virtual_memory.available - memory) / virtual_memory.total < 0.1:
print("Available memory would drop below 10%. Please reduce the time span.")
return None
config = create_config(config)
print('tuning:')
for k, v in config.items():
if type(v) in [ray.tune.sample.Float, ray.tune.sample.Integer]:
print(k, (v.lower, v.upper))
config['optimize_dirpath'] = os.path.join(config['optimize_dirpath'],
ts_to_date(time())[:19].replace(':', ''), '')
if 'iters' in config:
iters = config['iters']
else:
print('Parameter iters should be defined in the configuration. Defaulting to 10.')
iters = 10
if 'num_cpus' in config:
num_cpus = config['num_cpus']
else:
print('Parameter num_cpus should be defined in the configuration. Defaulting to 2.')
num_cpus = 2
n_particles = config['n_particles'] if 'n_particles' in config else 10
phi1 = 1.4962
phi2 = 1.4962
omega = 0.7298
if 'options' in config:
phi1 = config['options']['c1']
phi2 = config['options']['c2']
omega = config['options']['w']
current_best_params = []
if current_best is not None:
if type(current_best) == list:
for c in current_best:
c = clean_start_config(c, config)
if c not in current_best_params:
current_best_params.append(c)
else:
current_best = clean_start_config(current_best, config)
current_best_params.append(current_best)
ray.init(num_cpus=num_cpus,
object_store_memory=memory if memory > 4000000000 else None) # , logging_level=logging.FATAL, log_to_driver=False)
pso = ng.optimizers.ConfiguredPSO(transform='identity', popsize=n_particles, omega=omega, phip=phi1, phig=phi2)
algo = NevergradSearch(optimizer=pso, points_to_evaluate=current_best_params)
algo = ConcurrencyLimiter(algo, max_concurrent=num_cpus)
scheduler = AsyncHyperBandScheduler()
print('\n\nsimple sliding window optimization\n\n')
backtest_wrap = tune.with_parameters(simple_sliding_window_wrap, data=data)
analysis = tune.run(
backtest_wrap, metric='objective', mode='max', name='search',
search_alg=algo, scheduler=scheduler, num_samples=iters, config=config, verbose=1,
reuse_actors=True, local_dir=config['optimize_dirpath'],
progress_reporter=LogReporter(
metric_columns=['daily_gain',
'closest_bankruptcy',
'max_hrs_no_fills',
'max_hrs_no_fills_same_side',
'objective'],
parameter_columns=[k for k in config['ranges']
if (any(k0 in k for k0 in ['const', 'leverage', 'stop_psize_pct']) and '£' in k)
or '_span' in k]),
# if type(config[k]) == ray.tune.sample.Float
# or type(config[k]) == ray.tune.sample.Integer]),
raise_on_failed_trial=False
)
ray.shutdown()
return analysis
def save_results(analysis, config):
df = analysis.results_df
df.reset_index(inplace=True)
df.rename(columns={column: column.replace('config.', '') for column in df.columns}, inplace=True)
df = df.sort_values('objective', ascending=False)
df.to_csv(os.path.join(config['optimize_dirpath'], 'results.csv'), index=False)
print('Best candidate found:')
pprint.pprint(analysis.best_config)
async def main():
parser = argparse.ArgumentParser(prog='Optimize', description='Optimize passivbot config.')
parser = add_argparse_args(parser)
parser.add_argument('-t', '--start', type=str, required=False, dest='starting_configs',
default=None,
help='start with given live configs. single json file or dir with multiple json files')
args = parser.parse_args()
config = await prep_config(args)
if config['exchange'] == 'bybit' and not config['inverse']:
print('bybit usdt linear backtesting not supported')
return
downloader = Downloader(config)
print()
for k in (keys := ['exchange', 'symbol', 'starting_balance', 'start_date', 'end_date', 'latency_simulation_ms',
'do_long', 'do_shrt', 'minimum_bankruptcy_distance', 'maximum_hrs_no_fills',
'maximum_hrs_no_fills_same_side', 'iters', 'n_particles', 'sliding_window_days',
'min_span', 'max_span', 'n_spans']):
if k in config:
print(f"{k: <{max(map(len, keys)) + 2}} {config[k]}")
print()
data = await downloader.get_data()
config['n_days'] = (data[2][-1] - data[2][0]) / (1000 * 60 * 60 * 24)
start_candidate = None
if args.starting_configs is not None:
try:
if os.path.isdir(args.starting_configs):
start_candidate = [json.load(open(f)) for f in glob.glob(os.path.join(args.starting_configs, '*.json'))]
print('Starting with all configurations in directory.')
else:
start_candidate = json.load(open(args.starting_configs))
print('Starting with specified configuration.')
except Exception as e:
print('Could not find specified configuration.', e)
analysis = backtest_tune(data, config, start_candidate)
if analysis:
save_results(analysis, config)
config.update(clean_result_config(analysis.best_config))
plot_wrap(pack_config(config), data)
if __name__ == '__main__':
asyncio.run(main())