-
Notifications
You must be signed in to change notification settings - Fork 40
/
backtest.py
255 lines (186 loc) · 7.24 KB
/
backtest.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
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import backtrader as bt # Import the backtrader platfor
# Create a Stratey
class SMAStrategy(bt.Strategy):
params = (
('maperiod', None),
('quantity', None)
)
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
# To keep track of pending orders and buy price/commission
self.order = None
self.buyprice = None
self.buycomm = None
self.amount = None
# Add a MovingAverageSimple indicator
self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
self.order = None
def next(self):
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market
if not self.position:
# Not yet ... we MIGHT BUY if ...
if self.dataclose[0] > self.sma[0]:
# Keep track of the created order to avoid a 2nd order
self.amount = (self.broker.getvalue() * self.params.quantity) / self.dataclose[0]
self.order = self.buy(size=self.amount)
else:
# Already in the market ... we might sell
if self.dataclose[0] < self.sma[0]:
# Keep track of the created order to avoid a 2nd order
self.order = self.sell(size=self.amount)
class RSIStrategy(bt.Strategy):
params = (
('maperiod', None),
('quantity', None)
)
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
# To keep track of pending orders and buy price/commission
self.order = None
self.buyprice = None
self.buycomm = None
self.amount = None
# Add a MovingAverageSimple indicator
self.rsi = bt.talib.RSI(self.datas[0], timeperiod=self.params.maperiod)
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
self.order = None
def next(self):
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market
if not self.position:
# Not yet ... we MIGHT BUY if ...
if self.rsi < 30:
# Keep track of the created order to avoid a 2nd order
self.amount = (self.broker.getvalue() * self.params.quantity) / self.dataclose[0]
self.order = self.buy(size=self.amount)
else:
# Already in the market ... we might sell
if self.rsi > 70:
# Keep track of the created order to avoid a 2nd order
self.order = self.sell(size=self.amount)
# ______________________ End Strategy Class
def timeFrame(datapath):
"""
Select the write compression and timeframe.
"""
sepdatapath = datapath[5:-4].split(sep='-') # ignore name file 'data/' and '.csv'
tf = sepdatapath[3]
if tf == '1mth':
compression = 1
timeframe = bt.TimeFrame.Months
elif tf == '12h':
compression = 720
timeframe = bt.TimeFrame.Minutes
elif tf == '15m':
compression = 15
timeframe = bt.TimeFrame.Minutes
elif tf == '30m':
compression = 30
timeframe = bt.TimeFrame.Minutes
elif tf == '1d':
compression = 1
timeframe = bt.TimeFrame.Days
elif tf == '1h':
compression = 60
timeframe = bt.TimeFrame.Minutes
elif tf == '3m':
compression = 3
timeframe = bt.TimeFrame.Minutes
elif tf == '2h':
compression = 120
timeframe = bt.TimeFrame.Minutes
elif tf == '3d':
compression = 3
timeframe = bt.TimeFrame.Days
elif tf == '1w':
compression = 1
timeframe = bt.TimeFrame.Weeks
elif tf == '4h':
compression = 240
timeframe = bt.TimeFrame.Minutes
elif tf == '5m':
compression = 5
timeframe = bt.TimeFrame.Minutes
elif tf == '6h':
compression = 360
timeframe = bt.TimeFrame.Minutes
elif tf == '8h':
compression = 480
timeframe = bt.TimeFrame.Minutes
else:
print('dataframe not recognized')
exit()
return compression, timeframe
def getWinLoss(analyzer):
return analyzer.won.total, analyzer.lost.total, analyzer.pnl.net.total
def getSQN(analyzer):
return round(analyzer.sqn,2)
def runbacktest(datapath, start, end, period, strategy, commission_val=None, portofolio=10000.0, stake_val=1, quantity=0.01, plt=False):
# Create a cerebro entity
cerebro = bt.Cerebro()
# Add a FixedSize sizer according to the stake
cerebro.addsizer(bt.sizers.FixedSize, stake=stake_val) # Multiply the stake by X
cerebro.broker.setcash(portofolio) # default : 10000.0
if commission_val:
cerebro.broker.setcommission(commission=commission_val/100) # divide by 100 to remove the %
# Add a strategy
if strategy == 'SMA':
cerebro.addstrategy(SMAStrategy, maperiod=period, quantity=quantity)
elif strategy == 'RSI':
cerebro.addstrategy(RSIStrategy, maperiod=period, quantity=quantity)
else :
print('no strategy')
exit()
compression, timeframe = timeFrame(datapath)
# Create a Data Feed
data = bt.feeds.GenericCSVData(
dataname = datapath,
dtformat = 2,
compression = compression,
timeframe = timeframe,
fromdate = datetime.datetime.strptime(start, '%Y-%m-%d'),
todate = datetime.datetime.strptime(end, '%Y-%m-%d'),
reverse = False)
# Add the Data Feed to Cerebro
cerebro.adddata(data)
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
strat = cerebro.run()
stratexe = strat[0]
try:
totalwin, totalloss, pnl_net = getWinLoss(stratexe.analyzers.ta.get_analysis())
except KeyError:
totalwin, totalloss, pnl_net = 0, 0, 0
sqn = getSQN(stratexe.analyzers.sqn.get_analysis())
if plt:
cerebro.plot()
return cerebro.broker.getvalue(), totalwin, totalloss, pnl_net, sqn