-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktest_stoplimit_ema_cross
More file actions
246 lines (214 loc) · 9.92 KB
/
backtest_stoplimit_ema_cross
File metadata and controls
246 lines (214 loc) · 9.92 KB
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
import backtrader as bt
import datetime
import matplotlib.pyplot as plt
import numpy as np
class EMACrossStrategy(bt.Strategy):
COMMRATE = 0.001
def __init__(self):
self.inds = dict()
self.inds['1h'] = dict()
self.inds['1h']['RSI6'] = bt.talib.RSI(self.datas[1].close, timeperiod=6)
self.pos = dict()
self.close_price = 0
self.EMA600 = bt.talib.EMA(self.data,timeperiod=600)
self.EMA400 = bt.talib.EMA(self.data,timeperiod=400)
self.rsi = bt.talib.RSI(self.data, timeperiod=2)
self.BBANDS20 = bt.talib.BBANDS(self.data.close, timeperiod=20, nbdevup=2.0, nbdevdn=2.0)
self.EMA100 = bt.talib.EMA(self.data,timeperiod=100)
self.EMA50 = bt.talib.EMA(self.data,timeperiod=50)
self.plot_time = []
self.plot_bal = []
self.indicator_plot_time = []
self.indicator_plot_ema400 = []
self.current_balance = 0
self.buyprice = 0
self.buytime = 0
self.buycomm = 0
self.buysize = 0
self.sellprice = 0
self.selltime = 0
self.prev_max_balance = 0
self.buy_order_finished = True
self.sell_cond_count = {'LimitBuy': [0, 0, 0],
'LimitSell': [0, 0, 0],
'StopTrailBuy': [0, 0, 0],
'StopTrailSell': [0, 0, 0],
}
# To keep track of pending orders
self.order = None
self.order_stop_trail = None
self.order_sell_high = None
self.order_buy = None
def buy_logic(self):
if self.EMA400 > self.EMA600:
if self.EMA50[-1] < self.EMA100[-1] and self.EMA50[0] > self.EMA100[0]:
return True
return False
def sell_logic(self):
if self.close_price >= 1.02*self.BBANDS20.upperband and self.close_price > self.buyprice:
return True
return False
def log(self, txt, dt=None):
#Logging function for this strategy
dt = self.datas[0].datetime
print('%s, %s, %s' % (dt.date(0).isoformat(), dt.time(), txt))
def next(self):
for i, d in enumerate(self.datas):
dt, dn = self.datetime.date(), d._name
self.pos[d._name] = self.getposition(d).size
data = self.datas[0]
self.close_price = data.close[0]
self.indicator_plot_time.append(self.datas[0].datetime.date(0).isoformat())
self.indicator_plot_ema400.append(self.inds['1h']['RSI6'][-1])
# BUYING CONDITIONS
# if no position, and no open buy
# if ema400 is over ema 600
# if ema50 just crossed over ema100
# buy!
if not self.pos['15m']:
if self.buy_order_finished:
if self.buy_logic():
self.buysize = float("{:.0f}".format(0.98*self.broker.get_cash()/data.close[0]))
self.buyprice = float("{:.4f}".format(self.close_price))
self.order_buy = self.buy(
exectype=bt.Order.Limit,
price=self.buyprice,
size=self.buysize,
valid=bt.date2num(data.num2date())+(16/1440) # x min * (1h / 60m) * (1d / 24h) // x min to days
)
self.buy_order_finished = False
# SELLING CONDITIONS
if self.position.size > 0:
if not self.check_order_status(self.order_stop_trail) and not self.check_order_status(self.order_sell_high):
self.order_stop_trail = self.sell(
exectype=bt.Order.StopTrail,
trailpercent=0.0522,
price=self.close_price,
size=self.getposition().size,
info={'sellcode': 3},
# valid=bt.date2num(data.num2date())+(2880/1440)
)
elif not self.check_order_status(self.order_sell_high):
# if trailstop order still open but indicator says sell / price is high then cancel trailstop and sell
if self.sell_logic():
self.order_sell_high = self.sell(
exectype=bt.Order.Limit,
price=self.close_price,
size=self.getposition().size,
info={'sellcode': 1},
valid=bt.date2num(data.num2date())+(30/1440)
)
self.cancel(self.order_stop_trail)
return
def sellcount(self, order_name_sellcount, order_type_sellcount, net_gain_sellcount, net_gain_percent_sellcount):
sell_key = order_name_sellcount + order_type_sellcount
# Count of that action
self.sell_cond_count[sell_key][0] += 1
# Accumulated profit per action (divide by count later to get avg)
self.sell_cond_count[sell_key][1] += net_gain_sellcount
# Accumulated profit percent per action (divide by count later to get avg)
self.sell_cond_count[sell_key][2] += net_gain_percent_sellcount
return
def log_data(self, order):
order_name = order.getordername()
if order.isbuy():
order_type = 'Buy'
net_gain = 0
net_gain_percent = 0
else:
order_type = 'Sell'
net_gain = (order.executed.price-self.buyprice)*self.buysize - order.executed.comm - self.buycomm
net_gain_percent = 100*net_gain/(self.buysize*self.buyprice)
output = (f"Order: {order.ref:3d} Type: {order_name:<9} {order_type:<4} Status:" +
f" {order.getstatusname():1} ".ljust(12) +
f"Size: ".ljust(6) +
f"{order.created.size:6.0f} ".rjust(8)+
f"Price: {self.close_price:6.4f} ")
if order.status in [order.Completed]:
output += ( f"Cost: {order.executed.value:6.2f} " +
f"Comm: {order.executed.comm:4.2f} " +
f"RSI: {float(self.rsi[0]):3.2f} "
)
if not order.isbuy():
output += ( f"net gain: {net_gain:4.2f} " +
f"net gain %: {net_gain_percent:3.2f}% "
)
self.plot_time.append(self.datas[0].datetime.date(0).isoformat())
self.plot_bal.append(order.executed.value)
self.sellcount(order_name, order_type, net_gain, net_gain_percent)
self.log(output)
return
def check_order_status(self, order):
if order:
if order.alive():
return True
return False
def notify_order(self, order):
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if not order.alive():
if order.isbuy():
self.buycomm = order.executed.comm
self.buytime = order.executed.dt
self.buy_order_finished = True
elif order.issell():
self.current_balance = self.broker.get_cash()
if self.current_balance > self.prev_max_balance:
self.prev_max_balance = self.current_balance
else:
print('Order is not buy or sell(?)')
elif order.status in [order.Expired]:
self.buy_order_finished = True
elif order.status in [order.Accepted]:
pass
elif order.status in [order.Submitted]:
pass
elif order.status in [order.Canceled]:
pass
else:
print('weird order status: {}'.format(order.getstatusname()))
self.log_data(order)
return
def plot_results(self):
plt.rc('axes', labelsize=8)
fig = plt.figure()
# change subplot(x) to 121 if adding subplot
# first num is total rows, second is total columns, third is which location to put that named plot (i think)
ax1 = fig.add_subplot(111)
ax1.plot(self.plot_time, self.plot_bal)
ax1.title.set_text('Balance Over Time')
ax1.set_xlabel('Time')
ax1.set_ylabel('Money')
#ax2 = fig.add_subplot(122)
#ax2.plot(self.indicator_plot_time, self.indicator_plot_ema400)
#ax2.title.set_text('Indicators')
plt.xticks(rotation=90, ha='right')
plt.show()
pass
def stop(self):
print('Sell Condition Summary:')
print(f"\t{'Type':<13}\t{'Count':<5}\t{'Avg Profit':<10}\t {'Avg Profit %':<12}")
for key in self.sell_cond_count:
if self.sell_cond_count[key][0]:
avg_profit = self.sell_cond_count[key][1]/self.sell_cond_count[key][0]
avg_profit_percent = self.sell_cond_count[key][2]/self.sell_cond_count[key][0]
else:
avg_profit = 0
avg_profit_percent = 0
print(f'\t{key:<13}\t{self.sell_cond_count[key][0]:5.0f}\t{avg_profit:10.2f}\t{avg_profit_percent:12.2f}%')
print(f'Initial Balance: {initial_cash:.2f}, Max Balance: {self.prev_max_balance:.2f}, End Balance: {self.current_balance:.2f}')
self.plot_results()
pass
cerebro = bt.Cerebro()
fromdate = datetime.datetime.strptime('2020-01-01', '%Y-%m-%d')
todate = datetime.datetime.strptime('2023-02-10', '%Y-%m-%d')
data_15m = bt.feeds.GenericCSVData(dataname='data/2020-23_15m.csv', dtformat=2, compression=15, timeframe=bt.TimeFrame.Minutes, fromdate=fromdate, todate=todate)
#data_5m = bt.feeds.GenericCSVData(dataname='data/2020-23_5m.csv', dtformat=2, compression=5, timeframe=bt.TimeFrame.Minutes, fromdate=fromdate, todate=todate)
data_1h = bt.feeds.GenericCSVData(dataname='data/2020-23_1h.csv', dtformat=2, compression=60, timeframe=bt.TimeFrame.Minutes, fromdate=fromdate, todate=todate)
cerebro.adddata(data_15m, name='15m')
cerebro.adddata(data_1h, name='1h')
initial_cash = 10000
cerebro.broker.set_cash(initial_cash)
cerebro.broker.setcommission(commission=EMACrossStrategy.COMMRATE)
cerebro.addstrategy(EMACrossStrategy)
cerebro.run()