forked from sofienkaabar/trend-following-strategies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Master_Function.py
448 lines (293 loc) · 15.1 KB
/
Master_Function.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
import datetime
import pytz
import pandas as pd
import MetaTrader5 as mt5
import matplotlib.pyplot as plt
import numpy as np
import statistics as stats
frame_MIN1 = mt5.TIMEFRAME_M1
frame_M5 = mt5.TIMEFRAME_M5
frame_M10 = mt5.TIMEFRAME_M10
frame_M15 = mt5.TIMEFRAME_M15
frame_M20 = mt5.TIMEFRAME_M20
frame_M30 = mt5.TIMEFRAME_M30
frame_H1 = mt5.TIMEFRAME_H1
frame_H2 = mt5.TIMEFRAME_H2
frame_H3 = mt5.TIMEFRAME_H3
frame_H4 = mt5.TIMEFRAME_H4
frame_D1 = mt5.TIMEFRAME_D1
frame_W1 = mt5.TIMEFRAME_W1
frame_M1 = mt5.TIMEFRAME_MN1
now = datetime.datetime.now()
def asset_list(asset_set):
if asset_set == 'FX':
assets = ['EURUSD', 'USDCHF', 'GBPUSD', 'AUDUSD', 'NZDUSD',
'USDCAD', 'EURCAD', 'EURGBP', 'EURCHF', 'AUDCAD',
'USDJPY', 'NZDCHF', 'NZDCAD', 'EURAUD','AUDNZD',
'GBPCAD', 'AUDCHF', 'GBPAUD', 'GBPCHF', 'GBPNZD']
elif asset_set == 'CRYPTO':
assets = ['BTCUSD', 'ETHUSD', 'XRPUSD', 'LTCUSD']
elif asset_set == 'COMMODITIES':
assets = ['XAUUSD', 'XAGUSD', 'XPTUSD', 'XPDUSD']
return assets
def mass_import(asset, horizon):
if horizon == 'MN1':
data = get_quotes(frame_MIN1, 2021, 8, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M5':
data = get_quotes(frame_M5, 2021, 6, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M10':
data = get_quotes(frame_M10, 2021, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M15':
data = get_quotes(frame_M15, 2021, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M30':
data = get_quotes(frame_M30, 2016, 8, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M20':
data = get_quotes(frame_M20, 2018, 8, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'H1':
data = get_quotes(frame_H1, 2011, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'H2':
data = get_quotes(frame_H2, 2010, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'H3':
data = get_quotes(frame_H3, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'H4':
data = get_quotes(frame_H4, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'H6':
data = get_quotes(frame_H6, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'D1':
data = get_quotes(frame_D1, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'W1':
data = get_quotes(frame_W1, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
if horizon == 'M1':
data = get_quotes(frame_M1, 2000, 1, 1, asset = assets[asset])
data = data.iloc[:, 1:5].values
data = data.round(decimals = 5)
return data
def get_quotes(time_frame, year = 2005, month = 1, day = 1, asset = "EURUSD"):
# Establish connection to MetaTrader 5
if not mt5.initialize():
print("initialize() failed, error code =", mt5.last_error())
quit()
timezone = pytz.timezone("Europe/Paris")
utc_from = datetime.datetime(year, month, day, tzinfo = timezone)
utc_to = datetime.datetime(now.year, now.month, now.day + 1, tzinfo = timezone)
rates = mt5.copy_rates_range(asset, time_frame, utc_from, utc_to)
rates_frame = pd.DataFrame(rates)
return rates_frame
def adder(Data, times):
for i in range(1, times + 1):
new = np.zeros((len(Data), 1), dtype = float)
Data = np.append(Data, new, axis = 1)
return Data
def deleter(Data, index, times):
for i in range(1, times + 1):
Data = np.delete(Data, index, axis = 1)
return Data
def jump(Data, jump):
Data = Data[jump:, ]
return Data
def rounding(Data, how_far):
Data = Data.round(decimals = how_far)
return Data
def volatility(Data, lookback, what, where):
# Adding an extra column
Data = adder(Data, 1)
for i in range(len(Data)):
try:
Data[i, where] = (Data[i - lookback + 1:i + 1, what].std())
except IndexError:
pass
# Cleaning
Data = jump(Data, lookback)
return Data
def ohlc_plot_bars(Data, window):
Chosen = Data[-window:, ]
for i in range(len(Chosen)):
plt.vlines(x = i, ymin = Chosen[i, 2], ymax = Chosen[i, 1], color = 'black', linewidth = 1)
plt.vlines(x = i, ymin = Chosen[i, 2], ymax = Chosen[i, 1], color = 'black', linewidth = 1)
if Chosen[i, 3] > Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 0], ymax = Chosen[i, 3], color = 'black', linewidth = 1.00)
if Chosen[i, 3] < Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0], color = 'black', linewidth = 1.00)
if Chosen[i, 3] == Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0], color = 'black', linewidth = 1.00)
plt.grid()
def ohlc_plot_candles(Data, window):
Chosen = Data[-window:, ]
for i in range(len(Chosen)):
plt.vlines(x = i, ymin = Chosen[i, 2], ymax = Chosen[i, 1], color = 'black', linewidth = 1)
if Chosen[i, 3] > Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 0], ymax = Chosen[i, 3], color = 'green', linewidth = 3)
if Chosen[i, 3] < Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0], color = 'red', linewidth = 3)
if Chosen[i, 3] == Chosen[i, 0]:
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0] + 0.00001, color = 'black', linewidth = 6)
plt.grid()
def signal_chart(Data, close, what_bull, what_bear, window = 500):
Plottable = Data[-window:, ]
fig, ax = plt.subplots(figsize = (10, 5))
ohlc_plot_candles(Data, window)
for i in range(len(Plottable)):
if Plottable[i, what_bull] == 1:
x = i
y = Plottable[i, close]
ax.annotate(' ', xy = (x, y),
arrowprops = dict(width = 9, headlength = 11, headwidth = 11, facecolor = 'green', color = 'green'))
elif Plottable[i, what_bear] == -1:
x = i
y = Plottable[i, close]
ax.annotate(' ', xy = (x, y),
arrowprops = dict(width = 9, headlength = -11, headwidth = -11, facecolor = 'red', color = 'red'))
def indicator_plot_double(Data, opening, high, low, close, second_panel, window = 250):
fig, ax = plt.subplots(2, figsize = (10, 5))
Chosen = Data[-window:, ]
for i in range(len(Chosen)):
ax[0].vlines(x = i, ymin = Chosen[i, low], ymax = Chosen[i, high], color = 'black', linewidth = 1)
if Chosen[i, close] > Chosen[i, opening]:
color_chosen = 'green'
ax[0].vlines(x = i, ymin = Chosen[i, opening], ymax = Chosen[i, close], color = color_chosen, linewidth = 2)
if Chosen[i, close] < Chosen[i, opening]:
color_chosen = 'red'
ax[0].vlines(x = i, ymin = Chosen[i, close], ymax = Chosen[i, opening], color = color_chosen, linewidth = 2)
if Chosen[i, close] == Chosen[i, opening]:
color_chosen = 'black'
ax[0].vlines(x = i, ymin = Chosen[i, close], ymax = Chosen[i, opening], color = color_chosen, linewidth = 2)
ax[0].grid()
ax[1].plot(Data[-window:, second_panel], color = 'royalblue', linewidth = 1)
ax[1].grid()
def performance_variable_period(Data, close, buy, sell, long_result_col, short_result_col, total_result_col):
# Adding a few columns
Data = adder(Data, 10)
# Variable Holding Period
for i in range(len(Data)):
try:
if Data[i, buy] == 1:
for a in range(i + 1, i + 1000):
if Data[a, buy] == 1 or Data[a, sell] == -1:
Data[a, long_result_col] = Data[a, close] - Data[i, close]
break
else:
continue
else:
continue
except IndexError:
pass
for i in range(len(Data)):
try:
if Data[i, sell] == -1:
for a in range(i + 1, i + 1000):
if Data[a, buy] == 1 or Data[a, sell] == -1:
Data[a, short_result_col] = Data[i, close] - Data[a, close]
break
else:
continue
else:
continue
except IndexError:
pass
# Aggregating the Long & Short Results Into One Column
Data[:, total_result_col] = Data[:, long_result_col] + Data[:, short_result_col]
# Profit Factor
total_net_profits = Data[Data[:, total_result_col] > 0, total_result_col]
total_net_losses = Data[Data[:, total_result_col] < 0, total_result_col]
total_net_losses = abs(total_net_losses)
profit_factor = round(np.sum(total_net_profits) / np.sum(total_net_losses), 2)
# Hit Ratio
hit_ratio = len(total_net_profits) / (len(total_net_losses) + len(total_net_profits))
hit_ratio = round(hit_ratio, 2) * 100
# Risk Reward Ratio
average_gain = total_net_profits.mean()
average_loss = total_net_losses.mean()
realized_risk_reward = average_gain / average_loss
# Expectancy
expectancy = (average_gain * (hit_ratio / 100)) - ((1 - (hit_ratio / 100)) * average_loss)
expectancy = round(expectancy, 4)
# Number of Trades
trades = len(total_net_losses) + len(total_net_profits)
print('Hit Ratio = ', hit_ratio)
print('Average Gain = ', average_gain * 100000)
print('Average Loss = ', average_loss * 100000)
print('Expectancy = ', expectancy * 100000)
print('Profit factor = ', profit_factor)
print('Realized RR = ', round(realized_risk_reward, 3))
print('Number of Trades = ', trades)
return Data
def performance_fixed_period(Data, close, buy, sell, period, long_result_col, short_result_col, total_result_col):
# Adding a few columns
Data = adder(Data, 10)
# Fixed Period Holding
for i in range(len(Data)):
try:
if Data[i, buy] == 1:
Data[i + period, long_result_col] = Data[i + period, close] - Data[i, close]
elif Data[i, sell] == -1:
Data[i + period, short_result_col] = Data[i, close] - Data[i + period, close]
except IndexError:
pass
# Aggregating the Long & Short Results Into One Column
Data[:, total_result_col] = Data[:, long_result_col] + Data[:, short_result_col]
# Profit Factor
total_net_profits = Data[Data[:, total_result_col] > 0, total_result_col]
total_net_losses = Data[Data[:, total_result_col] < 0, total_result_col]
total_net_losses = abs(total_net_losses)
profit_factor = round(np.sum(total_net_profits) / np.sum(total_net_losses), 2)
# Hit Ratio
hit_ratio = len(total_net_profits) / (len(total_net_losses) + len(total_net_profits))
hit_ratio = round(hit_ratio, 2) * 100
# Risk Reward Ratio
average_gain = total_net_profits.mean()
average_loss = total_net_losses.mean()
realized_risk_reward = average_gain / average_loss
# Expectancy
expectancy = (average_gain * (hit_ratio / 100)) - ((1 - (hit_ratio / 100)) * average_loss)
expectancy = round(expectancy, 4)
# Number of Trades
trades = len(total_net_losses) + len(total_net_profits)
print('Hit Ratio = ', hit_ratio)
print('Average Gain = ', average_gain * 100000)
print('Average Loss = ', average_loss * 100000)
print('Expectancy = ', expectancy * 100000)
print('Profit factor = ', profit_factor)
print('Realized RR = ', round(realized_risk_reward, 3))
print('Number of Trades = ', trades)
return Data
def signal_chart_bars(Data, close, what_bull, what_bear, window = 500):
Plottable = Data[-window:, ]
fig, ax = plt.subplots(figsize = (10, 5))
ohlc_plot_bars(Data, window)
for i in range(len(Plottable)):
if Plottable[i, what_bull] == 1:
x = i
y = Plottable[i, close]
ax.annotate(' ', xy = (x, y),
arrowprops = dict(width = 9, headlength = 11, headwidth = 11, facecolor = 'green', color = 'green'))
elif Plottable[i, what_bear] == -1:
x = i
y = Plottable[i, close]
ax.annotate(' ', xy = (x, y),
arrowprops = dict(width = 9, headlength = -11, headwidth = -11, facecolor = 'red', color = 'red'))