forked from dimr/forexTrade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy.py
520 lines (396 loc) · 22.2 KB
/
strategy.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import datetime
import numpy as np
import pandas as pd
import Queue
import talib
from abc import ABCMeta, abstractmethod
from event import SignalEvent
import matplotlib.pyplot as plt
import matplotlib.finance
import matplotlib.dates as mdates
import time
from collections import namedtuple
from matplotlib.finance import candlestick
import heapq
class Strategy(object):
"""
Strategy is an abstract base class providing an interface for
all subsequent (inherited) strategy handling objects.
The goal of a (derived) Strategy object is to generate Signal
objects for particular symbols based on the inputs of Bars
(OLHCVI) generated by a DataHandler object.
This is designed to work both with historic and live data as
the Strategy object is agnostic to the data source,
since it obtains the bar tuples from a queue object.
"""
__metaclass__ = ABCMeta
@abstractmethod
def calculate_signals(self,events):
raise NotImplementedError("Should implement calculate_signals()")
class BuyAndHoldStrategy(Strategy):
def __init__(self, bars, events):
"""
Initialises the buy and hold strategy.
Parameters:
bars - The DataHandler object that provides bar information
events - The Event Queue object.
"""
self.bars = bars
self.symbol_list = self.bars.symbol_list
self.events = events
# Once buy & hold signal is given, these are set to True
self.bought = self._calculate_initial_bought()
self.lock = False
self.close= np.array([])
self.high=np.array([])
self.low=np.array([])
self.open = np.array([])
self.counter=0
self.i=0
self.position = namedtuple('Position','direction')
self.position.direction = 'EXIT'
self.long_close_enter_price = 0
self.short_close_enter_price =0
self.stop_loss = 0.0030
self.temp_close=[]
self.fig=plt.figure(figsize=(18,10),dpi=80,facecolor='w',edgecolor='k')
self.ax1=self.fig.add_subplot(1,1,1)
self.ax1.cla()
plt.ion()
plt.show(False)
self.ax1.hold(True)
self.ema_short,self.ema_middle,self.ema_fast,self.close_plotting,self.time_stamp=[],[],[],[],[]
self.line1, = self.ax1.plot(self.time_stamp,self.close,alpha=0.8,color='blue',markerfacecolor='red')
self.line2, = self.ax1.plot(self.time_stamp,self.ema_short,alpha=0.8,color='green')
self.fig.show()
self.fig.canvas.draw()
self.background=self.fig.canvas.copy_from_bbox(self.ax1.bbox)
self.start_short_span=0
self.end_short_span=0
self.start_long_span=0
self.end_long_span=0
self.s=[]
# self.fig = plt.figure(num=1, figsize=(20,12), dpi=80,facecolor='w', edgecolor='k')
# self.ax1 = plt.subplot(1,1,1)
def _calculate_initial_bought(self):
"""
Adds keys to the bought dictionary for all symbols
and sets them to False.
"""
bought = {}
for s in self.symbol_list:
bought[s]= False
return bought
def around(self,a,decimals=4):
return np.around(a,decimals)
def calculate_signals(self, event):
"""
For "Buy and Hold" we generate a single signal per symbol
and then no additional signals. This means we are
constantly long the market from the date of strategy
initialisation.
Parameters
event - A MarketEvent object.
"""
#---------- WORKING ----------
#plt.xlabel("Dates")
# fig=plt.figure(figsize=(14,10),dpi=80,facecolor='w',edgecolor='k')
# ax1=fig.add_subplot(1,1,1)
# ax1.cla()
# plt.ion()
# plt.show(False)
# ax1.hold(True)
# ema_short,ema_middle,ema_fast,close,time_stamp=[],[],[],[],[]
# line1, = ax1.plot(time_stamp,close,alpha=0.8,color='blue',markerfacecolor='red')
# line2, = ax1.plot(time_stamp,ema_short,alpha=0.8,color='green')
# fig.show()
# fig.canvas.draw()
# background=fig.canvas.copy_from_bbox(ax1.bbox)
if event.type == 'MARKET':
for s in self.symbol_list:
bars = self.bars.get_latest_bars(s,N=1)
#if s == 'GBPEUR':
self.close = np.append(self.close,bars[0][5])
self.high = np.append(self.high,bars[0][3])
self.low = np.append(self.low,bars[0][4])
# print bars[0][1], type(bars[0][1])
# exit()
ema_10 = np.around(talib.EMA(self.close,timeperiod=10),decimals=4)
ema_25 = np.around(talib.EMA(self.close,timeperiod=25),decimals=4)
ema_50 = np.around(talib.EMA(self.close,timeperiod=50),decimals=4)
atr_22=np.around(talib.ATR(self.high,self.low,self.close,timeperiod=22),decimals=4)
min_22=np.around(talib.MIN(self.low,timeperiod = 22),decimals=4)
max_22=np.around(talib.MAX(self.high,timeperiod = 22),decimals=4)
ts_long = max_22 - atr_22*3.5
ts_short = min_22+atr_22*3.5
#--------PLOTTING----------------
#if bars[0][1].dayofweek<4:
self.time_stamp.append(bars[0][1])
self.close_plotting.append(bars[0][5])
#print bars[0][1],bars[0][1].dayofweek
self.ema_short.append(ema_10[-1])
if len(self.time_stamp)>250:
del self.time_stamp[0]
del self.close_plotting[0]
del self.ema_short[0]
xmin, xmax, ymin, ymax = [min(self.time_stamp) , max(self.time_stamp) , .82,1]
self.line1.set_xdata(self.time_stamp)
self.line1.set_ydata(self.close_plotting)
self.line2.set_xdata(self.time_stamp)
self.line2.set_ydata(self.ema_short)
plt.axis([xmin, xmax, ymin, ymax])
self.fig.canvas.restore_region(self.background) # restore background
self.ax1.draw_artist(self.line1) # redraw just the points
self.fig.canvas.blit(self.ax1.bbox)
#candlestick(self.ax1,bars)
#x=mdates.datestr2num(bars[0][1])
#plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d %H:%M:%S'))
#plt.gca().xaxis.set_major_locator(mdates.SecondLocator())
#print x
#ax1.autofmt_xdate()
# ax1.fmt_xdata =bars[0][1] #mdates.DateFormatter(bars[0][1])
# day = mdates.DayLocator()
# daysFmt=mdates.DateFormatter('%Y%m%d %H:%M:%S')
# ax1.xaxis.set_major_locator(day)
#
#
# plt.gcf().autofmt_xdate() #rotates labels
# #ax1.plot(bars[0][1])
# plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d'))
#plt.plot(atr_22,'g--')
# plt.draw()
y_min=0
y_max=0
# #plt.plot(atr_22,"#DDA0A0",label='ATR_22')
#plt.plot(min_22,"#DDA0A0",label='ATR_22')
#assert(len(self.a) == sma)
if bars is not None and bars != []:
if self.position.direction == 'EXIT':
if self.close[-1] < ema_50[-1]:
if ema_10[-1] < ema_50[-1] and pd.Series(ema_50).shift().values[-1] <= pd.Series(ema_10).shift().values[-1] and self.bought[s]==False:
self.short_close_enter_price = self.close[-1]
self.events.put(SignalEvent(bars[0][0], bars[0][1],'SHORT'))
#print self.i,' ENTER SHORT-->',bars[0][1],'close enter','-->',self.close[-1]
self.position.direction = 'SHORT'
self.bought[s]=True
self.temp_close.append(self.close[-1])
#print self.temp_close,self.close
#y_min=bars[0][1]
self.start_short_span=self.time_stamp[-1]
# p=plt.axvspan(self.start_span,self.time_stamp[-1])
#self.s.append(self.time_stamp[-1])
return
elif self.close[-1] > ema_50[-1]:
if ema_10[-1] > ema_50[-1] and pd.Series(ema_50).shift().values[-1] >= pd.Series(ema_10).shift().values[-1]:
self.long_close_enter_price = self.close[-1]
#self.bought[s] = True
self.events.put(SignalEvent(bars[0][0],bars[0][1],'LONG'))
self.position.direction ='LONG'
#print self.i,"ENTER LONG-->",bars[0][1], 'close enter','-->',self.close[-1]
self.bought[s]=True
self.temp_close.append(self.close[-1])
self.start_long_span=self.time_stamp[-1]
return
elif self.position.direction == 'SHORT' :
if self.close[-1] >= min(self.temp_close)+(0.0035/(1.1+((self.temp_close[0]-(min(self.temp_close)))*100))):
#print self.close[-1], self.temp_close[0], min(self.temp_close) ,min(self.temp_close)+(0.0040/(1.2+((self.temp_close[0]-(min(self.temp_close)))*100)))
self.position.direction='EXIT'
#print self.i,'EXIT SHORT',bars[0][1],'close enter','-->',self.close[-1]
self.bought[s]=False
self.events.put(SignalEvent(bars[0][0],bars[0][1],'EXIT'))
self.temp_close=[]
#y_max=bars[0][1]
#plt.axvspan(y_min,y_max,facecolor='g')
#plt.draw()
self.end_short_span=self.time_stamp[-1]
p=plt.axvspan(self.start_short_span,self.end_short_span,facecolor='r',alpha=.3)
return
elif self.position.direction == 'LONG' :
if self.close[-1] <= max(self.temp_close)-(0.0035/(1.1+(((max(self.temp_close)-self.temp_close[0]))*100))):
#if self.long_close_enter_price - self.close[-1] >=0.0020:
#assert(self.long_close_enter_price-self.close[-1]>=0.0020)
self.position.direction='EXIT'
self.long_close_enter_price = 0
self.bought[s]=False
self.events.put(SignalEvent(bars[0][0],bars[0][1],'EXIT'))
self.end_long_span=self.time_stamp[-1]
p=plt.axvspan(self.start_long_span,self.end_long_span,facecolor='g',alpha=.3)
#print self.i,'EXIT LONG', bars[0][1],'close exit','-->',self.close[-1]
self.temp_close=[]
return
self.i+=1
if self.position.direction=='SHORT' or self.position.direction=='LONG':
self.temp_close.append(self.close[-1])
elif self.position.direction == 'EXIT':
self.temp_close=[]
class PivotMA(Strategy):
def __init__(self,bars,events,plot=False):
self.bars = bars
self.symbol_list = self.bars.symbol_list
self.events = events
self.plot=plot
# Once buy & hold signal is given, these are set to True
self.bought = self._calculate_initial_bought()
self.lock = False
self.close= np.array([])
self.high=np.array([])
self.low=np.array([])
self.open = np.array([])
self.counter=0
self.i=0
self.position = namedtuple('Position','direction')
self.position.direction = 'EXIT'
self.long_close_enter_price = 0
self.short_close_enter_price =0
self.stop_loss = 0.0030
# keep closing price when in short
self.temp_close=[]
# FOR PIVOT POINTS
self.days=[]
self.previous_low=[]
self.previous_high=[]
self.previous_close=[]
self.min_previous_low=0
self.max_previous_high=0
self.last_close=0
self.pivot_points=np.array([])
self.hourly_pivot_points=np.array([])
if self.plot:
self.fig=plt.figure(figsize=(18,10),dpi=80,facecolor='w',edgecolor='k')
self.ax1=self.fig.add_subplot(1,1,1)
self.ax1.cla()
plt.ion()
plt.show(False)
self.ax1.hold(True)
#self.ema_short,self.ema_middle,self.ema_fast,self.close_plotting,self.time_stamp=[],[],[],[],[]
self.time_stamp,self.close_plotting,self.pivot_points_plotting,self.r1_plotting,self.s1_plotting=[],[],[],[],[]
self.line1, = self.ax1.plot(self.time_stamp,self.close_plotting,alpha=0.8,color='blue',markerfacecolor='red')
self.line2, = self.ax1.plot(self.time_stamp,self.pivot_points_plotting,alpha=0.8,color='green')
self.line3, = self.ax1.plot(self.time_stamp,self.r1_plotting,alpha=0.8,color='grey')
self.line4, = self.ax1.plot(self.time_stamp,self.s1_plotting,alpha=0.8,color='black')
self.fig.show()
self.fig.canvas.draw()
self.background=self.fig.canvas.copy_from_bbox(self.ax1.bbox)
self.start_short_span=0
self.end_short_span=0
def _calculate_initial_bought(self):
"""
Adds keys to the bought dictionary for all symbols
and sets them to False.
"""
bought = {}
for s in self.symbol_list:
bought[s]= False
return bought
def calculate_signals(self,event):
if event.type == 'MARKET':
for s in self.symbol_list:
bars = self.bars.get_latest_bars(s,N=1)
#if s == 'GBPEUR':
self.close = np.append(self.close,bars[0][5])
self.high = np.append(self.high,bars[0][3])
self.low = np.append(self.low,bars[0][4])
# atr_22=np.around(talib.ATR(self.high,self.low,self.close,timeperiod=22),decimals=4)
# min_22=np.around(talib.MIN(self.low,timeperiod = 22),decimals=4)
# max_22=np.around(talib.MAX(self.high,timeperiod = 22),decimals=4)
# ts_long = max_22 - atr_22*3.5
# ts_short = min_22+atr_22*3.5
self.days.append(bars[0][1].dayofweek)
if all(day==bars[0][1].dayofweek for day in self.days):
self.previous_high.append(self.high[-1])
self.previous_low.append(self.low[-1])
self.previous_close.append(self.close[-1])
else:
self.max_previous_high,self.min_previous_low= max(self.previous_high),min(self.previous_low)
self.last_close=self.previous_close[-1]
self.days=[]
self.previous_high=[]
self.previous_low=[]
self.previous_high.append(self.high[-1])
self.previous_low.append(self.low[-1])
# print bars[0][1],(self.max_previous_high+self.min_previous_low+self.last_close)/3
# print self.max_previous_high,self.min_previous_low,self.last_close
#---------------INDICATORS -------------------------
daily_pivot_point = (self.max_previous_high+self.min_previous_low+self.last_close)/3
self.pivot_points=np.append(self.pivot_points,daily_pivot_point)
R1=daily_pivot_point*2-self.min_previous_low
R2=daily_pivot_point+self.max_previous_high-self.min_previous_low
R3=self.max_previous_high+2*(daily_pivot_point-self.min_previous_low)
S1=daily_pivot_point*2-self.max_previous_high
S2=daily_pivot_point-self.max_previous_high+self.min_previous_low
S3=self.min_previous_low-2*(self.max_previous_high-daily_pivot_point)
hourly_pivot_point=(self.close[-1]+self.high[-1]+self.low[-1])/3
self.hourly_pivot_points=np.append(self.hourly_pivot_points,hourly_pivot_point)
MA_hourly_pivot_point_3= np.around(talib.SMA(np.array(self.hourly_pivot_points),timeperiod=3),decimals=4)
MA_hourly_pivot_point_5= np.around(talib.SMA(np.array(self.close),timeperiod=5),decimals=4)
if bars is not None and bars != []:
if self.position.direction == 'EXIT':
if ((R1-0.0010) <=self.high[-1] <= R1) or ((R2-0.0010) <=self.high[-1] <= R2) or ((R3-0.0010) <=self.high[-1] <= R3) :
if (MA_hourly_pivot_point_3[-1] < MA_hourly_pivot_point_5[-1] and MA_hourly_pivot_point_3[-2]>=MA_hourly_pivot_point_5[-2]) or (MA_hourly_pivot_point_3[-1] < MA_hourly_pivot_point_5[-1] and MA_hourly_pivot_point_3[-3]>=MA_hourly_pivot_point_5[-3]) and self.close[-1]<MA_hourly_pivot_point_3[-1] and self.close[-1]<MA_hourly_pivot_point_3[-1] and self.bought[s]==False:
self.short_close_enter_price = self.close[-1]
self.events.put(SignalEvent(bars[0][0], bars[0][1],'SHORT'))
#print self.i,' ENTER SHORT-->',bars[0][1],'close enter','-->',self.close[-1]
self.position.direction = 'SHORT'
self.bought[s]=True
self.temp_close.append(self.close[-1])
#print self.temp_close,self.close
return
elif ((S1+0.001)> self.low[-1] > S1) or ((S2+0.001)> self.low[-1] > S2) or ((S3+0.001)> self.low[-1] > S3):
if (MA_hourly_pivot_point_3[-1] < MA_hourly_pivot_point_5[-1] and MA_hourly_pivot_point_3[-2]>=MA_hourly_pivot_point_5[-2]) or (MA_hourly_pivot_point_3[-1] < MA_hourly_pivot_point_5[-1] and MA_hourly_pivot_point_3[-3]>=MA_hourly_pivot_point_5[-3]) and self.close[-1]>MA_hourly_pivot_point_3[-1]:
self.long_close_enter_price = self.close[-1]
#self.bought[s] = True
self.events.put(SignalEvent(bars[0][0],bars[0][1],'LONG'))
self.position.direction ='LONG'
#print self.i,"ENTER LONG-->",bars[0][1], 'close enter','-->',self.close[-1]
self.bought[s]=True
self.temp_close.append(self.close[-1])
return
elif self.position.direction == 'SHORT' :
if self.close[-1] >= self.temp_close[0]+ 0.0035 or self.close[-1] <= self.temp_close[0]-0.007:
#print self.close[-1], self.temp_close[0], min(self.temp_close) ,min(self.temp_close)+(0.0040/(1.2+((self.temp_close[0]-(min(self.temp_close)))*100)))
self.position.direction='EXIT'
#print self.i,'EXIT SHORT',bars[0][1],'close enter','-->',self.close[-1]
self.bought[s]=False
self.events.put(SignalEvent(bars[0][0],bars[0][1],'EXIT'))
self.temp_close=[]
return
elif self.position.direction == 'LONG' :
if self.close[-1] <= self.temp_close[0]-0.0035 or self.close[-1]>= self.temp_close[0]+0.007:
#if self.long_close_enter_price - self.close[-1] >=0.0020:
#assert(self.long_close_enter_price-self.close[-1]>=0.0020)
self.position.direction='EXIT'
self.long_close_enter_price = 0
self.bought[s]=False
self.events.put(SignalEvent(bars[0][0],bars[0][1],'EXIT'))
self.temp_close=[]
return
if self.plot:
self.time_stamp.append(bars[0][1])
self.close_plotting.append(bars[0][5])
#print bars[0][1],bars[0][1].dayofweek
self.pivot_points_plotting.append(daily_pivot_point)
self.r1_plotting.append(R1)
self.s1_plotting.append(S1)
if len(self.time_stamp)>250:
del self.time_stamp[0]
del self.close_plotting[0]
del self.pivot_points_plotting[0]
del self.r1_plotting[0]
del self.s1_plotting[0]
xmin, xmax, ymin, ymax = [min(self.time_stamp) , max(self.time_stamp) , .82,1]
self.line1.set_xdata(self.time_stamp)
self.line1.set_ydata(self.close_plotting)
self.line2.set_xdata(self.time_stamp)
self.line2.set_ydata(self.pivot_points_plotting)
self.line3.set_xdata(self.time_stamp)
self.line3.set_ydata(self.r1_plotting)
self.line4.set_xdata(self.time_stamp)
self.line4.set_ydata(self.s1_plotting)
plt.axis([xmin, xmax, ymin, ymax])
self.fig.canvas.restore_region(self.background) # restore background
self.ax1.draw_artist(self.line1) # redraw just the points
self.fig.canvas.blit(self.ax1.bbox)
if self.position.direction=='SHORT' or self.position.direction=='LONG':
self.temp_close.append(self.close[-1])
elif self.position.direction == 'EXIT':
self.temp_close=[]