-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.py
101 lines (85 loc) · 3.29 KB
/
main.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
from BacktestTrendBreakerPL import BacktestTrendBreakerPL
import backtrader as bt
import warnings
warnings.filterwarnings("ignore")
from pyswarm import pso
# The objective function for optimization
def obj_fun(x):
print('')
print('Launched the iteration with ' + str(x))
ap = {'pivot_window_len': int(x[0]),
'history_bars_as_multiple_pwl': int(x[1]),
'fixed_tp': x[2],
'fixed_sl_as_multiple_tp': x[3]
}
os = {'order_full': False,
'order_status': False,
'trades': False,
'performance': True,
'plot': False
}
# Creater object for Backtesting
backtest = BacktestTrendBreakerPL(file_data='./SBER_140101_171231_hourly_train.csv',
algo_params=ap,
output_settings=os)
# Run the strategy (hourly timeframe)
backtest.run_strategy(cash=1000,
commission=0.0004,
tf=bt.TimeFrame.Minutes,
compression=60)
# Add "minus" for minimization
return -backtest.stability
# Bounds for parameters space
lb = [2, 10, 0.01, 0.1]
ub = [120, 100, 0.2, 1.5]
# Run the optimization
xopt, fopt = pso(obj_fun, lb, ub, swarmsize=20, maxiter=40)
print('OPTIMAL PARAMETERS:')
print(xopt, fopt)
# Store the best params
algo_params = {'pivot_window_len': int(xopt[0]),
'history_bars_as_multiple_pwl': int(xopt[1]),
'fixed_tp': xopt[2],
'fixed_sl_as_multiple_tp': xopt[3],
}
output_settings = {'order_full': False,
'order_status': False,
'trades': False,
'performance': True,
'plot': True
}
# Run the strategy with best params
# Using train, test and full datasets
for file in ['./data/SBER_140101_171231_hourly_train.csv',
'./data/SBER_180101_200224_hourly_test.csv',
'./data/SBER_140101_200224_hourly_full.csv']:
print('Launched backtest for ' + file)
backtest = BacktestTrendBreakerPL(file_data=file,
algo_params=algo_params,
output_settings=output_settings)
backtest.run_strategy(cash=1000,
commission=0.0004,
tf=bt.TimeFrame.Minutes,
compression=60)
'''
# Manual fitted parameters
algo_params = {'pivot_window_len': 12,
'history_bars_as_multiple_pwl': 30,
'fixed_tp': 0.08, # Inf - off
'fixed_sl_as_multiple_tp': 0.15, # fixed_tp * fixed_sl_as_multiple_tp >= 1.0 - off
}
# Just output parameters
output_settings = {'order_full': False,
'order_status': True,
'trades': True,
'performance': True,
'plot': True
}
backtest = BacktestTrendBreakerPL(file_data='./data/SBER_140101_200224_hourly_full.csv',
algo_params=algo_params,
output_settings=output_settings)
backtest.run_strategy(cash=1000,
commission=0.0004,
tf=bt.TimeFrame.Minutes,
compression=60)
'''