-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions_gandalf_wintermute.py
3095 lines (2583 loc) · 122 KB
/
functions_gandalf_wintermute.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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Version Wintermute 20220314
import datetime
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import math
import colorama
from colorama import Fore
#import talib as tape
#%matplotlib inline
pd.options.display.max_rows = 99999
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
print(__version__) # necessaria versione >= 1.9.0
import cufflinks as cf
# Per utilizzo con Notebooks
init_notebook_mode(connected=True)
# Per utilizzo offline
cf.go_offline()
import warnings
warnings.filterwarnings("ignore")
# LOADING FUNCTIONS ********************************************************************************************************start
def load_data_intraday_old(filename: str) -> pd.core.frame.DataFrame:
"""
Funzione per il parsing di una serie intraday
con estensione txt esportata da Tradestation
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename,
usecols=['Date','Time','Open','High','Low','Close','Up','Down'],
parse_dates=[['Date', 'Time']], )
data.columns = ["date_time","open","high","low","close","up","down"]
data.set_index('date_time', inplace = True)
data['volume'] = data['up'] + data['down']
data.drop(['up','down'],axis=1,inplace=True)
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
data["hour"] = data.index.hour
data["minute"] = data.index.minute
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data
def load_data_intraday(filename):
"""
Funzione per il parsing di una serie intraday
con estensione txt esportata da Tradestation
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename,
usecols=['Date','Time','Open','High','Low','Close','Up','Down'],
parse_dates=[['Date', 'Time']])
data.columns = ["date_time","open","high","low","close","up","down"]
data.set_index('date_time', inplace = True)
data['volume'] = data['up'] + data['down']
data.drop(['up','down'],axis=1,inplace=True)
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
data["hour"] = data.index.hour
data["minute"] = data.index.minute
data["daily_open"] = daily_open(data,0)
data["daily_open1"] = daily_open(data,1)
data["daily_high1"] = daily_high(data,1)
data["daily_low1"] = daily_low(data,1)
data["daily_close1"] = daily_close(data,1)
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data.dropna()
def load_data_daily(filename):
"""
Funzione per il caricamento di uno storico daily
Fonte dati: Tradestation .txt
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename, parse_dates = ["Date","Time"])
data.columns = ["date","time","open","high","low","close","volume","oi"]
data.set_index("date", inplace = True)
data.drop(["time","oi"], axis=1, inplace=True)
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data
def load_data_ffn(filename):
"""
Function to load and elaborate an history
coming from FFN
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename, usecols=['date','open','high','low','close','volume'])
data.volume = data.volume.apply(lambda x: int(x))
data["date"] = pd.to_datetime(data["date"])
data.set_index('date', inplace = True)
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data
def load_data_daily_rci(filename):
"""
Funzione per il caricamento di uno storico daily
Fonte dati: Gandalf Project Crypto .txt
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename, sep = " ", header = None)
data.columns = ["date","open","high","low","close","volume"]
data.set_index("date", inplace = True)
data.index = pd.to_datetime(data.index, format='%d/%m/%Y')
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data
def load_data_daily_ccxt(filename):
"""
Function to load and elaborate an history
coming from CCXT Download
"""
import datetime
start = datetime.datetime.now()
data = pd.read_csv(filename)
data.columns = ["date","open","high","low","close","volume"]
data.volume = data.volume.apply(lambda x: int(x))
data["date"] = pd.to_datetime(data["date"])
data.set_index('date', inplace = True)
#data.drop(['date'],axis=1,inplace=True)
data["dayofweek"] = data.index.dayofweek
data["day"] = data.index.day
data["month"] = data.index.month
data["year"] = data.index.year
data["dayofyear"] = data.index.dayofyear
data["quarter"] = data.index.quarter
end = datetime.datetime.now()
print("loaded", len(data), "records in", end - start)
return data
def load_multiple_data_intraday(*args):
i = 1
# First of all we create aligned dataframe with all historical data
for file in args:
service = load_data_intraday(file)
if i == 1:
dataset = service
else:
dataset = pd.concat([dataset, service], axis = 1).dropna()
i += 1
fields = int(len(dataset.columns) / len(args))
#print(fields)
# Then we separate each historical data aligned
results = []
for i in range(1,len(args) + 1):
if i == 1:
results.append(dataset.iloc[:,:fields])
else:
results.append(dataset.iloc[:,(i - 1) * fields: i * fields])
if len(results) == 1:
return results[0]
else:
return results
def load_data_daily_slim(folder,filename):
"""
Funzione per il caricamento di uno storico daily
Fonte dati: Tradestation .txt
"""
path = folder + filename
data = pd.read_csv(path, parse_dates = ["Date","Time"])
data.columns = ["date","time","open","high","low","close","volume","oi"]
data.set_index("date", inplace = True)
data.drop(["time","oi"], axis=1, inplace=True)
return data
def load_multiple_data_daily(folder,asset_filelist):
i = 1
# First of all we create aligned dataframe with all historical data
for file in asset_filelist:
ticker = file.split("_")[0].lower()
service = load_data_daily_slim(folder,file)
new_col_names = []
[new_col_names.append(ticker + "_" + col) for col in service.columns]
service.columns = new_col_names
if i == 1:
dataset = service
else:
dataset = pd.concat([dataset, service], axis = 1).dropna()
i += 1
return dataset
# LOADING FUNCTIONS **********************************************************************************************************end
# INDICATORS ***************************************************************************************************************start
def atr(data,period):
"""
Function to calculate average true range
Inputs: dataframe of prices ["open","high","low","close"]
Output: average true range
"""
data["m1"] = data.high - data.low
data["m2"] = abs(data.high - data.close.shift(1))
data["m3"] = abs(data.low - data.close.shift(1))
data["maximum"] = data[["m1", "m2", "m3"]].max(axis = 1)
data["atr"] = data.maximum.rolling(5).mean()
return data.atr
def avg_true_range(dataframe, period):
dataframe["M1"] = dataframe.high - dataframe.low
dataframe["M2"] = abs(dataframe.high - dataframe.low.shift(1)).fillna(0)
dataframe["M3"] = abs(dataframe.low - dataframe.close.shift(1)).fillna(0)
dataframe["Max"] = dataframe[["M1", "M2", "M3"]].max(axis = 1)
dataframe["MeanMax"] = dataframe["Max"].rolling(period).mean()
return dataframe.MeanMax.fillna(0)
def RSI(series, period):
"""
Function to calculate the Relative Strength Index of a close serie
"""
df = pd.DataFrame(series, index = series.index)
df["chg"] = series.diff(1)
df["gain"] = np.where(df.chg > 0, 1, 0)
df["loss"] = np.where(df.chg <= 0, 1, 0)
df["avg_gain"] = df.gain.rolling(period).sum() / period * 100
df["avg_loss"] = df.loss.rolling(period).sum() / period * 100
rs = abs(df["avg_gain"] / df["avg_loss"])
rsi = 100 - (100 / (1 + rs))
return rsi
def MFI(df, period):
"""
Function to calculate the Money Flow Index of a price serie (OHLCV)
"""
df["typical_price"] = (df.iloc[:,1] + df.iloc[:,2] + df.iloc[:,3]) / 3
df["raw_money_flow"] = df.typical_price * df.iloc[:,4]
df["chg"] = df.raw_money_flow.diff(1)
df["pos_money_flow"] = np.where(df.chg > 0,1,0)
df["neg_money_flow"] = np.where(df.chg <= 0,1,0)
df["avg_gain"] = df.pos_money_flow.rolling(period).sum() / period * 100
df["avg_loss"] = df.neg_money_flow.rolling(period).sum() / period * 100
mfr = abs(df["avg_gain"] / df["avg_loss"])
mfi = 100 - (100 / (1 + mfr))
return mfi
def BollingerBand(serie,period,multiplier):
return serie.rolling(period).mean() + multiplier * serie.rolling(period).std()
def ROC(serie,period):
return ((serie / serie.shift(period)) - 1) * 100
def Momentum(serie,period):
return (serie - serie.shift(period))
def SMA(serie,period):
return serie.rolling(period).mean()
def Range(serie):
"""
Function to calculate the Range of a price serie (OHLCV)
"""
return (serie.iloc[:,1] - serie.iloc[:,2])
def Body(serie):
"""
Function to calculate the Body of a price serie (OHLCV)
"""
return (serie.iloc[:,3] - serie.iloc[:,0])
def AvgPrice(serie):
"""
Function to calculate the AvgPrice of a price serie (OHLCV)
"""
return (serie.iloc[:,0] + serie.iloc[:,1] + serie.iloc[:,2] + serie.iloc[:,3]) / 4
def MedPrice(serie):
"""
Function to calculate the MedPrice of a price serie (OHLCV)
"""
return (serie.iloc[:,1] + serie.iloc[:,2]) / 2
def MedBodyPrice(serie):
"""
Function to calculate the MedBodyPrice of a price serie (OHLCV)
"""
return (serie.iloc[:,0] + serie.iloc[:,3]) / 2
def Blastoff(serie):
return abs(serie.iloc[:,0] - serie.iloc[:,3]) / (serie.iloc[:,1] - serie.iloc[:,2])
def OpenToLowLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.open) - np.log(data.low))
def OpenToAvgPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
return pd.Series(np.log(data.open) - np.log(data.avgprice))
def OpenToMedPriceLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.open) - np.log(data.medprice))
def OpenToOpenLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.open) - np.log(data.open.shift(1)))
def OpenToMedBodyPriceLog(dataset):
data = dataset.copy()
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.open) - np.log(data.medbodyprice))
def CloseToMedPriceLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.close) - np.log(data.medprice))
def CloseToCloseLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.close) - np.log(data.close.shift(1)))
def CloseToLowLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.close) - np.log(data.low))
def CloseToAvgPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
return pd.Series(np.log(data.close) - np.log(data.avgprice))
def CloseToMedBodyPriceLog(dataset):
data = dataset.copy()
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.close) - np.log(data.medbodyprice))
def HighToCloseLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.high) - np.log(data.close))
def HighToOpenLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.high) - np.log(data.open))
def HighToMedBodyPriceLog(dataset):
data = dataset.copy()
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.high) - np.log(data.medbodyprice))
def HighToMedPriceLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.high) - np.log(data.medprice))
def HighToAvgPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
return pd.Series(np.log(data.high) - np.log(data.avgprice))
def HighToHighLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.high) - np.log(data.high.shift(1)))
def LowToLowLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.low) - np.log(data.low.shift(1)))
def AvgPriceToMedPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.avgprice) - np.log(data.medprice))
def AvgPriceToLowLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
return pd.Series(np.log(data.avgprice) - np.log(data.low))
def AvgPriceToAvgPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
return pd.Series(np.log(data.avgprice) - np.log(data.avgprice.shift(1)))
def AvgPriceToMedBodyPriceLog(dataset):
data = dataset.copy()
data["avgprice"] = data.iloc[:,:4].mean(axis = 1)
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.avgprice) - np.log(data.medbodyprice))
def MedPriceToLowLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.medprice) - np.log(data.low))
def MedBodyPriceToLowLog(dataset):
data = dataset.copy()
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.medbodyprice) - np.log(data.low))
def MedPriceToMedBodyPriceLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.medprice) - np.log(data.medbodyprice))
def MedPriceToMedPriceLog(dataset):
data = dataset.copy()
data["medprice"] = (data.high + data.low) / 2
return pd.Series(np.log(data.medprice) - np.log(data.medprice.shift(1)))
def MedBodyPriceToMedBodyPriceLog(dataset):
data = dataset.copy()
data["medbodyprice"] = (data.open + data.close) / 2
return pd.Series(np.log(data.medbodyprice) - np.log(data.medbodyprice).shift(1))
def RangeLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.high) - np.log(data.low))
def BodyLog(dataset):
data = dataset.copy()
return pd.Series(np.log(data.close) - np.log(data.open))
def BodyToRangeLog(dataset):
data = dataset.copy()
data["body"] = (data.close - data.open)
data["range"] = (data.high - data.low)
return pd.Series(np.log(data.body) - np.log(data.range))
def daily_high(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["day"] != df["day"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["high"].groupby(df["grouper"]).max().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_high" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def weekly_high(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["week"] != df["week"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["high"].groupby(df["grouper"]).max().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_high" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def daily_low(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["day"] != df["day"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["low"].groupby(df["grouper"]).min().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_low" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def weekly_low(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["week"] != df["week"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["low"].groupby(df["grouper"]).min().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_low" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def daily_open(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["day"] != df["day"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["open"].groupby(df["grouper"]).first().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_open" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def weekly_open(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["week"] != df["week"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["open"].groupby(df["grouper"]).first().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_open" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def daily_close(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["day"] != df["day"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["close"].groupby(df["grouper"]).last().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_close" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def weekly_close(dataframe, delay):
df = dataframe.copy()
df["rule"] = np.where(df["week"] != df["week"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["close"].groupby(df["grouper"]).last().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_close" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def daily_close_sma(dataframe, delay, period):
df = dataframe.copy()
df["rule"] = np.where(df["day"] != df["day"].shift(1),1,0)
df["grouper"] = df.rule.cumsum()
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["close"].groupby(df["grouper"]).last().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "daily_close" + "_" + str(delay)
service.columns = [field_name]
sma_field_name = "daily_close_sma" + "_" + str(delay)
service[sma_field_name] = service[field_name].rolling(period).mean()
df1 = pd.concat([df, service], axis = 1)
df1[sma_field_name] = df1[sma_field_name].fillna(method = "ffill")
return df1[sma_field_name]
def session_high(dataframe, session_hour, session_minute, delay):
df = dataframe.copy()
df["rule"] = np.where((df["hour"] == session_hour) & (df["minute"] == session_minute),1,0)
df["grouper"] = df.rule.cumsum()
df = df[df.grouper > 0] #innesto per cancellare i record precedenti al primo trigger
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["high"].groupby(df["grouper"]).max().shift(delay))#.dropna()
service.set_index(indexes, inplace = True)
field_name = "session_high" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def session_low(dataframe, session_hour, session_minute, delay):
df = dataframe.copy()
df["rule"] = np.where((df["hour"] == session_hour) & (df["minute"] == session_minute),1,0)
df["grouper"] = df.rule.cumsum()
df = df[df.grouper > 0] #innesto per cancellare i record precedenti al primo trigger
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["low"].groupby(df["grouper"]).min().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "session_low" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def session_open(dataframe, session_hour, session_minute, delay):
df = dataframe.copy()
df["rule"] = np.where((df["hour"] == session_hour) & (df["minute"] == session_minute),1,0)
df["grouper"] = df.rule.cumsum()
df = df[df.grouper > 0] #innesto per cancellare i record precedenti al primo trigger
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["open"].groupby(df["grouper"]).first().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "session_open" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def session_close(dataframe, session_hour, session_minute, delay):
df = dataframe.copy()
df["rule"] = np.where((df["hour"] == session_hour) & (df["minute"] == session_minute),1,0)
df["grouper"] = df.rule.cumsum()
df = df[df.grouper > 0] #innesto per cancellare i record precedenti al primo trigger
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["close"].groupby(df["grouper"]).last().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "session_close" + "_" + str(delay)
service.columns = [field_name]
df1 = pd.concat([df, service], axis = 1)
df1[field_name] = df1[field_name].fillna(method = "ffill")
return df1[field_name]
def session_close_sma(dataframe, session_hour, session_minute, delay, period):
df = dataframe.copy()
df["rule"] = np.where((df["hour"] == session_hour) & (df["minute"] == session_minute),1,0)
df["grouper"] = df.rule.cumsum()
df = df[df.grouper > 0] #innesto per cancellare i record precedenti al primo trigger
indexes = df[df.rule == 1].index
service = pd.DataFrame(df["close"].groupby(df["grouper"]).last().shift(delay))
service.set_index(indexes, inplace=True)
field_name = "session_close" + "_" + str(delay)
service.columns = [field_name]
sma_field_name = "session_close_sma" + "_" + str(delay)
service[sma_field_name] = service[field_name].rolling(period).mean()
df1 = pd.concat([df, service], axis = 1)
df1[sma_field_name] = df1[sma_field_name].fillna(method = "ffill")
return df1[sma_field_name]
def adx(data,period):
"""
Function to calculate average directional index for a period of 14 days
Inputs: dataframe of prices ["open","high","low","close"]
Output: adx
"""
data["+DM"] = np.where((data.high - data.high.shift(1) > data.low - data.low.shift(1)) & (data.high - data.high.shift(1)>0),\
data.high - data.high.shift(1),0)
data["-DM"] = np.where((data.high - data.high.shift(1) < data.low - data.low.shift(1)) & (data.low - data.low.shift(1)>0),\
data.low - data.low.shift(1),0)
data["m1"] = data.high - data.low
data["m2"] = abs(data.high - data.close.shift(1))
data["m3"] = abs(data.low - data.close.shift(1))
data["TR"] = data[["m1", "m2", "m3"]].max(axis = 1)
data["+DM14"] = data["+DM"].rolling(period).sum()
data["-DM14"] = data["-DM"].rolling(period).sum()
data["TR14"] = data["TR"].rolling(period).sum()
data["+DI"] = round(((data["+DM14"]/data["TR14"])*100), 0)
data["-DI"] = round(((data["-DM14"]/data["TR14"])*100), 0)
data["DX"] = round(abs((data["+DI"]-data["-DI"])/(data["+DI"]+data["-DI"])),0)
data["ADX"] = (data.DX.rolling(14).mean())*100
return data.ADX
def trix(data,period):
"""
Function to calculate triple exponential moving average
Inputs: dataframe of prices ["open","high","low","close"]
Output: trix
"""
data["MOV_1"] = data.close.ewm(span=period, adjust=False).mean()
data["MOV_2"] = data.MOV_1.ewm(span=period, adjust=False).mean()
data["MOV_3"] = data.MOV_2.ewm(span=period, adjust=False).mean()
data["TRIX"] = ((data.MOV_3 - data.MOV_3.shift(1))/data.MOV_3.shift(1))*100
return data.TRIX
# INDICATORS *****************************************************************************************************************end
# PERFORMANCE METRICS ******************************************************************************************************start
def drawdown(equity):
"""
Funzione che calcola il draw down data un'equity line
"""
maxvalue = equity.expanding(0).max()
drawdown = equity - maxvalue
drawdown_series = pd.Series(drawdown, index = equity.index)
return drawdown_series
def max_drawdown_date(equity):
return drawdown(equity).idxmin()
def drawdown_perc(equity,basic_quantity):
"""
Funzione che calcola il draw down percentuale data un'equity line
ed un capitale iniziale
"""
real_equity = basic_quantity + equity
eq_max = real_equity.expanding().max()
dd = drawdown(equity)
dd_perc = (dd / eq_max) * 100
dd_perc = pd.Series(np.where(dd_perc > 0, 0 , dd_perc), index = equity.index)
return dd_perc
def max_draw_down_perc(equity,basic_quantity):
dd_perc = drawdown_perc(equity,basic_quantity)
return round(dd_perc.min(),2)
def max_drawdown_perc_date(equity,basic_quantity):
return drawdown_perc(equity,basic_quantity).idxmin()
def avgdrawdownperc_nozero(equity,basic_quantity):
"""
calcola la media del draw down storico
non considerando i valori nulli (nuovi massimi di equity line)
"""
dd_perc = drawdown_perc(equity,basic_quantity)
return round(dd_perc[dd_perc < 0].mean(),2)
def profit(equity):
return round(equity[-1],2)
def operation_number(operations):
return operations.count()
def avg_trade(operations):
return round(operations.mean(),2)
def max_draw_down(equity):
dd = drawdown(equity)
return round(dd.min(),2)
def avgdrawdown_nozero(equity):
"""
calcola la media del draw down storico
non considerando i valori nulli (nuovi massimi di equity line)
"""
dd = drawdown(equity)
return round(dd[dd < 0].mean(),2)
def drawdown_statistics(operations):
dd = drawdown(operations)
return dd.describe(percentiles=[0.30, 0.20, 0.10, 0.05, 0.01])
def avg_loss(operations):
return round(operations[operations < 0].mean(),2)
def max_loss(operations):
return round(operations.min(),2)
def max_loss_date(operations):
return operations.idxmin()
def avg_gain(operations):
return round(operations[operations > 0].mean(),2)
def max_gain(operations):
return round(operations.max(),2)
def max_gain_date(operations):
return operations.idxmax()
def gross_profit(operations):
return round(operations[operations > 0].sum(),2)
def gross_loss(operations):
return round(operations[operations <= 0].sum(),2)
def profit_factor(operations):
a = gross_profit(operations)
b = gross_loss(operations)
if b != 0:
return round(abs(a / b), 2)
else:
return round(abs(a / 0.00000001), 2)
def percent_win(operations):
return round((operations[operations > 0].count() / operations.count() * 100),2)
def reward_risk_ratio(operations):
if operations[operations <= 0].mean() != 0:
return round((operations[operations > 0].mean() / -operations[operations <= 0].mean()),2)
else:
return np.inf
def sustainability(operations):
pw = percent_win(operations)
rrr = reward_risk_ratio(operations)
return pw * rrr - (100 - pw) * (1 / rrr)
def delay_between_peaks(equity):
"""
Funzione per calcolare i ritardi istantanei in barre
nel conseguire nuovi massimi di equity line
Input: equity line
"""
work_df = pd.DataFrame(equity, index = equity.index)
work_df["drawdown"] = drawdown(equity)
work_df["delay_elements"] = work_df["drawdown"].apply(lambda x: 1 if x < 0 else 0)
work_df["resets"] = np.where(work_df["drawdown"] == 0, 1, 0)
work_df['cumsum'] = work_df['resets'].cumsum()
#print(work_df.iloc[-20:,:])
a = pd.Series(work_df['delay_elements'].groupby(work_df['cumsum']).cumsum())
return a
def max_delay_between_peaks(equity):
"""
Funzione per calcolare il più lungo ritardo in barre dall'ultimo massimo
Input: equity line
"""
a = delay_between_peaks(equity)
return a.max()
def avg_delay_between_peaks(equity):
"""
Funzione per calcolare il ritardo medio in barre
nel conseguire nuovi massimi di equity line
Input: equity line
"""
work_df = pd.DataFrame(equity, index = equity.index)
work_df["drawdown"] = drawdown(equity)
work_df["delay_elements"] = work_df["drawdown"].apply(lambda x: 1 if x < 0 else np.nan)
work_df["resets"] = np.where(work_df["drawdown"] == 0, 1, 0)
work_df['cumsum'] = work_df['resets'].cumsum()
work_df.dropna(inplace = True)
a = work_df['delay_elements'].groupby(work_df['cumsum']).sum()
return round(a.mean(),2)
def old_omega_ratio(operations,threshold):
downside=0
upside=0
i=0
while i < len(operations):
if operations[i] < threshold:
downside += (threshold - operations[i])
if operations[i] > threshold:
upside += (operations[i] - threshold)
i+=1
if downside != 0:
return round(upside / downside,2)
else:
return np.inf
def omega_ratio(operations,threshold):
upside = np.where(operations > threshold, operations - threshold, 0).sum()
downside = np.where(operations < threshold, threshold - operations, 0).sum()
if downside != 0:
return round(upside / downside, 2)
else:
return np.inf
def old_sharpe_ratio(operations):
"""
Il rapporto tra il guadagno totale
e la deviazione standard dell'equity line
"""
equity = operations.cumsum()
netprofit = equity[-1]
std = equity.std()
if std != 0:
return round(netprofit / std,2)
else:
return np.inf
def sharpe_ratio_yearly(operations):
"""
Il rapporto medio su base annuale tra
il guadagno annuale ed il draw down annuale
"""
yearly_operations = operations.resample('A').sum()
yearly_std = operations.resample('A').std()
records = []
for i in range(len(yearly_operations)):
if yearly_std[i] != 0:
records.append(yearly_operations[i] / yearly_std[i])
else:
records.append(np.inf)
records = pd.Series(records, index = yearly_operations.index)
return round(records.mean(),2), records
def sharpe_ratio_old(operations, start_nav, period_risk_free):
"""
Sharpe Ratio
Rocket Capital Investment Version 2021
operations: list of trades
start_nav: starting money
period_risk_free: annual risk free percent profit
"""
results = pd.DataFrame(operations.resample('A').sum())
results.columns = ["yearly_profit"]
results["yearly_returns"] = results.yearly_profit / start_nav * 100
results["excess_return"] = results.yearly_returns - period_risk_free
results["yearly_std"] = operations.resample('A').std()
avg_excess_return = results.excess_return.mean()
risk = results.yearly_std.mean()
if risk != 0:
sharpe = round(avg_excess_return / risk * 100,2)
else:
if avg_excess_return >= 0:
sharpe = np.inf
else:
sharpe = -np.inf
return sharpe
def sharpe_ratio_high_value(operations, start_nav, period_risk_free):
"""
Sharpe Ratio
Rocket Capital Investment Version Version 20211023
operations: list of trades
start_nav: starting money
period_risk_free: annual risk free percent profit
"""
results = pd.DataFrame(operations.resample('A').sum())
results.columns = ["yearly_profit"]
results["yearly_returns"] = results.yearly_profit / start_nav * 100
results["excess_return"] = results.yearly_returns - period_risk_free
results["yearly_std"] = operations.resample('A').std()
results["yearly_std_perc"] = results.yearly_std / results.yearly_profit * 100
avg_excess_return = results.excess_return.mean()
risk = results.yearly_std_perc.mean()
#print(results)
#print(avg_excess_return, risk)
if risk != 0:
sharpe = round(avg_excess_return / risk,2)
else:
if avg_excess_return >= 0:
sharpe = np.inf
else:
sharpe = -np.inf
return sharpe
def sharpe_ratio(operations, start_nav, period_risk_free):
"""
Sharpe Ratio
Rocket Capital Investment Version 20211023
operations: list of trades
start_nav: starting money
period_risk_free: annual risk free percent profit
"""
results = pd.DataFrame(operations.resample('A').sum())
results.columns = ["yearly_profit"]
results["yearly_returns"] = results.yearly_profit / start_nav * 100