-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_futures.py
1752 lines (1585 loc) · 94.8 KB
/
run_futures.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
# -*- coding: utf-8 -*-
"""
v4
premise:
The premise for this system is that there is an insample period in the recent history
that is in sync with the future market out of sample period. This insample period can be
using various methods. More than one in-sample period can be used for prediction.
Additional bias can be added as a parameter.
Major Parameters to be optemised:
bar size
support/resistance lookback
validation length
adfPvalue
AddAuxPairs & nfeatures
Created on Sat Feb 27 10:46:08 2016
@author: Hidemi
"""
import sys
import numpy as np
import math
import talib as ta
import pandas as pd
import arch
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
#from pandas.io.dataSet import DataReader
import random
from scipy import stats
from scipy.stats import kurtosis, skew
import time
from sklearn.grid_search import ParameterGrid
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest, chi2, f_classif
#classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import Perceptron, PassiveAggressiveClassifier, LogisticRegression
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier,\
BaggingClassifier, ExtraTreesClassifier, VotingClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.metrics import confusion_matrix
from sklearn.svm import LinearSVC, SVC, NuSVC
from sklearn.neighbors import RadiusNeighborsClassifier, KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB, MultinomialNB
import re
import copy
import string
from os import listdir
from os.path import isfile, join
import math
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
from scipy import stats
import datetime
from datetime import datetime as dt
from pandas.core import datetools
import time
from suztoolz.transform import RSI, ROC, zScore, softmax, DPO, numberZeros,\
gainAhead, ATR, priceChange, garch, autocorrel, kaufman_efficiency,\
volumeSpike, softmax_score, create_indicators, ratio, perturb_data,\
roofingFilter, getCycleTime, saveParams
from suztoolz.loops import calcEquity2, createBenchmark, createYearlyStats, findBestDPS
from suztoolz.display import displayRankedCharts
from suztoolz.datatools.loadFuturesCSI import loadFutures
from suztoolz.datatools.acPeriodogram import acPeriodogram
from suztoolz.datatools.zigzag2 import zigzag as zg
from suztoolz.datatools.mrClassifier import mrClassifier
from suztoolz.datatools.mrClassifier3 import mrClassifier as mrClassifier3
from suztoolz.datatools.seasonalClass import seasonalClassifier
from suztoolz.position_sizing.calcDPS import calcDPS
from sklearn.preprocessing import scale, robust_scale, minmax_scale
from sklearn.pipeline import Pipeline
import logging
import os
from pytz import timezone
from dateutil.parser import parse
start_time = time.time()
def average(l):
return sum(l)/len(l)
def IBcommission(tradeAmount, asset):
commission = 2.0
if asset == 'FX':
return max(2.0, tradeAmount*2e-5)
else:
return commission
def initSST(close, version_, st, initialEquity):
savedShadowTrades = pd.DataFrame(index=close.index)
savedShadowTrades.index.name = 'dates'
#set to 0 for all signals to start at the same time.
savedShadowTrades['signals']=0
savedShadowTrades['signalType']=st
savedShadowTrades[version_+'_system']=st
savedShadowTrades['gainAhead']=close.pct_change().shift(-1).fillna(0)
savedShadowTrades['netPNL']=0
savedShadowTrades['nodpsComm']=0
savedShadowTrades['nodpsSafef']=0
savedShadowTrades['netEquity']=initialEquity
return savedShadowTrades
def calcEquityLast(i, sst):
#equityBeLongAndShortSignals = np.zeros(nrows)
#equityBeLongAndShortSignals[0] = sst.equity[-1]
#for i in range(1,nrows):
if (sst.signals.iloc[i-1] < 0):
equityBeLongAndShortSignals = (1+-sst.gainAhead.iloc[i-1]*sst.nodpsSafef.iloc[i-1])*sst.netEquity[i-1]
elif (sst.signals.iloc[i-1] > 0):
equityBeLongAndShortSignals= (1+sst.gainAhead.iloc[i-1]*sst.nodpsSafef.iloc[i-1])*sst.netEquity[i-1]
else:
equityBeLongAndShortSignals = sst.netEquity[i-1]
positionChg = abs(sst.signals[i]*sst.nodpsSafef.iloc[i]-sst.signals[i-1]*sst.nodpsSafef.iloc[i-1])
if positionChg !=0:
commission = IBcommission(positionChg*equityBeLongAndShortSignals, asset)
else:
commission = 0.0
lastEquity = round(equityBeLongAndShortSignals-commission,2)
netPNL = round(lastEquity - sst.netEquity[i-1], 2)
return netPNL, commission, lastEquity
def reCalcEquity(sst, metric):
#no dps
nrows=sst.shape[0]
index = sst.index
noDpsEquity = np.zeros(nrows)
netPNL = np.zeros(nrows)
commission = np.zeros(nrows)
noDpsEquity[0] = sst.netEquity[0]
if metric != 'CAR25':
sst['RS_'+metric] = sst[metric].values
for i in range(1,nrows):
if (sst.signals.iloc[i-1] *sst.nodpsSafef.iloc[i-1]< 0):
#print sst.signals.iloc[i-1] , sst.nodpsSafef.iloc[i-1], sst.gainAhead.iloc[i-1]
noDpsEquity[i] = (1+-sst.gainAhead.iloc[i-1]*sst.nodpsSafef.iloc[i-1])*noDpsEquity[i-1]
elif (sst.signals.iloc[i-1]*sst.nodpsSafef.iloc[i-1] > 0):
noDpsEquity[i]= (1+sst.gainAhead.iloc[i-1]*sst.nodpsSafef.iloc[i-1])*noDpsEquity[i-1]
else:
noDpsEquity[i] = sst.netEquity[i-1]
positionChg = abs(sst.signals[i]*sst.nodpsSafef.iloc[i]-sst.signals[i-1]*sst.nodpsSafef.iloc[i-1])
if positionChg !=0:
commission[i] = IBcommission(positionChg*noDpsEquity[i], asset)
else:
commission[i] = 0.0
#print sst.signals[i-1], sst.signals[i], positionChg, commission[i]
noDpsEquity[i] = round(noDpsEquity[i]-commission[i],2)
netPNL[i] = round(noDpsEquity[i] - noDpsEquity[i-1], 2)
#print i, noDpsEquity[i]
sst.set_value(index, 'netEquity', noDpsEquity)
sst.set_value(index,'netPNL',netPNL)
sst.set_value(index,'nodpsComm',commission)
#dps
dpsNetEquity = np.zeros(nrows)
dpsNetPNL = np.zeros(nrows)
dpsCommission = np.zeros(nrows)
dpsNetEquity[0] = sst.dpsNetEquity[0]
for i in range(1,nrows):
if (sst.signals.iloc[i-1] *sst.dpsSafef.iloc[i-1]< 0):
dpsNetEquity[i] = (1+-sst.gainAhead.iloc[i-1]*sst.dpsSafef.iloc[i-1])*dpsNetEquity[i-1]
elif (sst.signals.iloc[i-1]*sst.dpsSafef.iloc[i-1] > 0):
dpsNetEquity[i]= (1+sst.gainAhead.iloc[i-1]*sst.dpsSafef.iloc[i-1])*dpsNetEquity[i-1]
else:
dpsNetEquity[i] = sst.dpsNetEquity[i-1]
positionChg = abs(sst.signals[i]*sst.dpsSafef.iloc[i]-sst.signals[i-1]*sst.dpsSafef.iloc[i-1])
if positionChg !=0:
dpsCommission[i] = IBcommission(positionChg*dpsNetEquity[i], asset)
else:
dpsCommission[i] = 0.0
dpsNetEquity[i] = round(dpsNetEquity[i]-dpsCommission[i],2)
dpsNetPNL[i] = round(dpsNetEquity[i] - dpsNetEquity[i-1], 2)
sst.set_value(index,'dpsNetEquity', dpsNetEquity)
sst.set_value(index,'dpsNetPNL',dpsNetPNL)
sst.set_value(index,'dpsCommission', dpsCommission)
return sst
def createSignalFile(version, version_, ticker, barSizeSetting, signalPath, sst, start_time, dataSet, mrThreshold):
print version_, 'Saving',ticker, 'Signals..'
timenow, lastBartime, cycleTime = getCycleTime(start_time, dataSet)
files = [ f for f in listdir(signalPath) if isfile(join(signalPath,f)) ]
#new version_ file
if version_+'_'+ ticker+'_'+barSizeSetting+ '.csv' not in files:
#signalFile = sst.iloc[-2:]
addLine = sst.iloc[-1]
addLine = addLine.append(pd.Series(data=timenow.strftime("%Y%m%d %H:%M:%S %Z"), index=['timestamp']))
addLine = addLine.append(pd.Series(data=mrThreshold, index=['mrThreshold']))
addLine.name = sst.iloc[-1].name
signalFile = sst.iloc[-2:-1].append(addLine)
signalFile.index.name = 'dates'
filename = signalPath + version_+'_'+ ticker+'_'+barSizeSetting+ '.csv'
print 'Saving', filename
signalFile.to_csv(filename, index=True)
else:
signalFile=pd.read_csv(signalPath+ version_+'_'+ ticker+'_'+barSizeSetting+ '.csv', index_col=['dates'])
addLine = sst.iloc[-1]
addLine = addLine.append(pd.Series(data=timenow.strftime("%Y%m%d %H:%M:%S %Z"), index=['timestamp']))
addLine = addLine.append(pd.Series(data=mrThreshold, index=['mrThreshold']))
addLine.name = sst.iloc[-1].name
signalFile = signalFile.append(addLine)
filename = signalPath + version_+'_'+ ticker+'_'+barSizeSetting+ '.csv'
print 'Saving', filename
signalFile.to_csv(filename, index=True)
#create old version_ file if it dosent exist
if version+'_'+ ticker+ '.csv' not in files:
#signalFile = sst.iloc[-2:]
addLine = sst.iloc[-1]
addLine = addLine.append(pd.Series(data=timenow.strftime("%Y%m%d %H:%M:%S %Z"), index=['timestamp']))
addLine = addLine.append(pd.Series(data=mrThreshold, index=['mrThreshold']))
addLine.name = sst.iloc[-1].name
signalFile = sst.iloc[-2:-1].append(addLine)
signalFile.index.name = 'dates'
filename=signalPath + version+'_'+ ticker+ '.csv'
print 'Saving', filename
signalFile.to_csv(filename, index=True)
'''
else:
signalFile=pd.read_csv(signalPath+ version+'_'+ ticker+ '.csv', index_col=['dates'])
addLine = sst.iloc[-1]
addLine = addLine.append(pd.Series(data=timenow.strftime("%Y%m%d %H:%M:%S %Z"), index=['timestamp']))
addLine = addLine.append(pd.Series(data=mrThreshold, index=['mrThreshold']))
addLine.name = sst.iloc[-1].name
signalFile = signalFile.append(addLine)
filename=signalPath + version+'_'+ ticker+ '.csv'
print 'Saving', filename
signalFile.to_csv(filename, index=True)
'''
#system parameters
version = 'v4'
version_ = 'v4.4'
asset = 'FX'
#filterName = 'DF1'
#data_type = 'ALL'
barSizeSetting='1D'
mrThresholds = [1, .5, 0.75]
if len(sys.argv)==1:
debug=True
#validationSetLength = 90
liveFutures = [
#'AC',
#'AD',
#'AEX',
#'BO',
#'BP',
#'C',
#'CC',
#'CD',
#'CGB',
#'CL',
#'CT',
#'CU',
#'DX',
#'EBL',
#'EBM',
#'EBS',
'ED',
#'EMD',
#'ES',
#'FCH',
#'FC',
#'FDX',
#'FEI',
#'FFI',
#'FLG',
#'FSS',
#'FV',
#'GC',
#'HCM',
#'HG',
#'HIC',
#'HO',
#'JY',
#'KC',
#'KW',
#'LB',
#'LCO',
#'LC',
#'LGO',
#'LH',
#'LRC',
#'LSU',
#'MEM',
#'MFX',
#'MP',
#'MW',
#'NE',
#'NG',
#'NIY',
#'NQ',
#'O',
#'OJ',
#'PA',
#'PL',
#'RB',
#'RR',
#'RS',
#'S',
#'SB',
#'SF',
#'SI',
#'SIN',
#'SJB',
#'SM',
#'SMI',
#'SSG',
#'STW',
#'SXE',
#'TF',
#'TU',
#'TY',
#'US',
#'VX',
#'W',
#'YA',
#'YB',
#'YM',
#'YT2',
#'YT3'
]
ticker =liveFutures[0]
#dataPath = 'Z:/TSDP/data/from_IB/'
#dataPath = 'D:/data/tickerData/'
dataPath = 'D:/ML-TSDP/data/csidata/v4futures2/'
signalPath = 'C:/Users/Hidemi/Desktop/Python/SharedTSDP/data/signals/'
#chartSavePath = None
chartSavePath = 'C:/Users/Hidemi/Desktop/Python/SharedTSDP/data/simCharts/'+version+'_'+ticker
vsfile =pd.read_csv('D:/ML-TSDP/data/futuresATR.csv', index_col=0)
startDate_dt=dt.strptime(vsfile.ix[ticker].vSTART, '%Y-%m-%d')
#Model Parameters
supportResistanceLB=60
#startDate=datetime.date(2016,4,18)
startDate=datetime.date(startDate_dt.year, startDate_dt.month, startDate_dt.day)
endDate = dt.today().replace(hour=0, minute=0, second=0, microsecond=0)
endDate = datetime.date(endDate.year, endDate.month, endDate.day)
validationSetLength = np.busday_count(startDate, endDate)
#startDate=None
#validationSetLength = 29
#supportResistanceLB = max(validationSetLength,supportResistanceLB)
bias=['gainAhead','zigZag','buyHold','sellHold']
#bias = ['gainAhead','zigZag']
#bias = ['gainAhead']
#bias = ['zigZag']
#bias=['sellHold']
#bias=['buyHold']
#cycle mode->threshold=1.1
#adfPvalue=1.1
#trendmode -> threshold = -0.1
adfPvalue=3
#auto ->threshold = 0.2
#adfPvalue=1.1
#adds auxilary pair features
addAux = True
#display params
showCharts=False
showFinalChartOnly=True
showIndicators = False
verbose=True
else:
debug=False
if len(sys.argv)==3:
ticker=sys.argv[1]
#Model Parameters
#startDate=None
#validationSetLength = 10
vsfile =pd.read_csv('./data/futuresATR.csv', index_col=0)
startDate_dt=dt.strptime(vsfile.ix[ticker].vSTART, '%Y-%m-%d')
#Model Parameters
supportResistanceLB=60
#startDate=datetime.date(2016,4,18)
startDate=datetime.date(startDate_dt.year, startDate_dt.month, startDate_dt.day)
endDate = dt.today().replace(hour=0, minute=0, second=0, microsecond=0)
endDate = datetime.date(endDate.year, endDate.month, endDate.day)
validationSetLength = np.busday_count(startDate, endDate)
if sys.argv[2] == '1':
bias=['buyHold']
elif sys.argv[2] == '-1':
bias=['sellHold']
else:
bias=['gainAhead','zigZag','buyHold','sellHold']
adfPvalue=3
else:
startDate=None
ticker=sys.argv[1]
if len(sys.argv[2])==8:
sdate=sys.argv[2]
startDate=datetime.date(int(sdate[0:4]),int(sdate[4:6]),int(sdate[6:8]))
endDate = dt.today().replace(hour=0, minute=0, second=0, microsecond=0)
endDate = datetime.date(endDate.year, endDate.month, endDate.day)
validationSetLength = np.busday_count(startDate, endDate)
supportResistanceLB = max(validationSetLength,int(sys.argv[3]))
else:
validationSetLength = int(sys.argv[2])
supportResistanceLB = int(sys.argv[3])
#Model Parameters
#supportResistanceLB = int(sys.argv[2])
#validationSetLength = int(sys.argv[3])
#bias=['gainAhead','zigZag']
bias=['gainAhead','zigZag','buyHold','sellHold']
adfPvalue=3
#useSignalsFrom='highest_level3_netEquity'
#bias=[sys.argv[2]]
#adfPvalue=float(sys.argv[3])
#validationSetLength =int(sys.argv[4])
#useSignalsFrom=sys.argv[5]
#ticker =liveFutures[0]
#symbol=ticker[0:3]
#currency=ticker[3:6]
signalPath = './data/signals/'
dataPath = './data/csidata/v4futures2/'
chartSavePath = './web/tsdp/betting/static/images/'+version+'_'+ticker
#adds auxilary pair features
addAux = True
#display params
showCharts=False
showFinalChartOnly=True
showIndicators = False
verbose=False
#aux futures
files = [ f for f in listdir(dataPath) if isfile(join(dataPath,f)) ]
auxFutures = [x.split('_')[0] for x in files]
#for PCA/KBest
nfeatures = 10
#if major low/high most recent index. minDatapoints sets the minimum is period.
minDatapoints = 3
#set to 1 for live
#system selection metric
#no post filter goes to 'level1'
metric = 'netEquity'
#'level1' filter
metric2='netEquity'
#'level2' filter
metric3='netEquity'
#robustness
perturbData = False
perturbDataPct = 0.0002
#dps
#save to signal file
useDPSsafef=False
#personal risk tolerance parameters
PRT={}
#ie goes to charts, car25 scoring (affected by commissions)
PRT['initial_equity'] = 100000
#fcst horizon(bars) for dps. for training, horizon is set to nrows. for validation scoring nrows.
PRT['horizon'] = 50
#safef set to dd95 where limit is met. e.g. for 50 bars, set saef to where 95% of the mc eq curves' maxDD <=0.01
PRT['DD95_limit'] = 0.01
PRT['tailRiskPct'] = 95
#rounds safef and safef cannot go below this number. if set to None, no rounding
PRT['minSafef'] =1.0
#no dps safef
PRT['nodpsSafef'] =1.0
#dps max limit
PRT['maxSafef'] = 2.0
#safef=minSafef if CAR25 < threshold
PRT['CAR25_threshold'] = 0
#PRT['CAR25_threshold'] = -np.inf
#needs 2x srlookback to prime indicators.
maxlb = supportResistanceLB*2
#maxReadLines = validationSetLength+maxlb
maxReadLines = 500
initialEquity=PRT['initial_equity']
nodpsSafef=PRT['nodpsSafef']
#model selection
dt_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1)
RFE_estimator = [
("None","None"),\
#("GradientBoostingRegressor",GradientBoostingRegressor()),\
#("DecisionTreeRegressor",DecisionTreeRegressor()),\
#("ExtraTreeRegressor",ExtraTreeRegressor()),\
#("BayesianRidge", BayesianRidge()),\
]
fs_models = [
('PCA'+str(nfeatures),PCA(n_components=nfeatures)),\
('SelectKBest'+str(nfeatures),SelectKBest(f_classif, k=nfeatures))\
]
short_models = [
#("LR", LogisticRegression(class_weight={1:1})), \
#("PRCEPT", Perceptron(class_weight={1:1})), \
#("PAC", PassiveAggressiveClassifier(class_weight={1:1})), \
#("LSVC", LinearSVC()), \
("GNBayes",GaussianNB()),\
#("LDA", LinearDiscriminantAnalysis()), \
#("QDA", QuadraticDiscriminantAnalysis()), \
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),
#("rbf1SVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("rbf10SVM", SVC(C=10, gamma=.01, cache_size=200, class_weight={-1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("polySVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='poly', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("sigSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='sigmoid', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("NuSVM", NuSVC(nu=0.9, kernel='rbf', degree=3, gamma=.100, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, verbose=False, max_iter=-1, random_state=None)),\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#("RF", RandomForestClassifier(class_weight={1:1}, n_estimators=10, criterion='gini',max_depth=3, min_samples_split=2, min_samples_leaf=1, max_features='auto', bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0))\
#("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=5, weights='uniform')),\
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=15, weights='distance')),\
#("rNeighbors-uniform", RadiusNeighborsClassifier(radius=8, weights='uniform')),\
#("rNeighbors-distance", RadiusNeighborsClassifier(radius=10, weights='distance')),\
#("VotingHard", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
#("GNBayes",GaussianNB()),\
#("LDA", LinearDiscriminantAnalysis()), \
#("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=2, weights='uniform')),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=8, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#], voting='hard', weights=None)),
#("VotingSoft", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
#("GNBayes",GaussianNB()),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=8, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
# ], voting='soft', weights=None)),
]
noAuxPairs_models = [
#("LR", LogisticRegression(class_weight={1:1})), \
#("PRCEPT", Perceptron(class_weight={1:1})), \
#("PAC", PassiveAggressiveClassifier(class_weight={1:1})), \
#("LSVC", LinearSVC()), \
#("GNBayes",GaussianNB()),\
#("LDA", LinearDiscriminantAnalysis()), \
#("QDA", QuadraticDiscriminantAnalysis()), \
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),
#("rbf1SVM", SVC(C=10, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("rbf10SVM", SVC(C=10, gamma=.01, cache_size=200, class_weight={-1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("polySVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='poly', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("sigSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='sigmoid', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("NuSVM", NuSVC(nu=0.9, kernel='rbf', degree=3, gamma=.100, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, verbose=False, max_iter=-1, random_state=None)),\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#("RF", RandomForestClassifier(class_weight={1:1}, n_estimators=10, criterion='gini',max_depth=3, min_samples_split=2, min_samples_leaf=1, max_features='auto', bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0))\
#("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=5, weights='uniform')),\
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=15, weights='distance')),\
#("rNeighbors-uniform", RadiusNeighborsClassifier(radius=8, weights='uniform')),\
#("rNeighbors-distance", RadiusNeighborsClassifier(radius=10, weights='distance')),\
("VotingHard", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
("GNBayes",GaussianNB()),\
("LDA", LinearDiscriminantAnalysis()), \
("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=minDatapoints, weights='uniform')),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=8, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
], voting='hard', weights=None)),
#("VotingSoft", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
#("GNBayes",GaussianNB()),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=8, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#], voting='soft', weights=None)),
]
auxPairs_models = [
#("LR", LogisticRegression(class_weight={1:1})), \
#("PRCEPT", Perceptron(class_weight={1:1})), \
#("PAC", PassiveAggressiveClassifier(class_weight={1:1})), \
#("LSVC", LinearSVC()), \
#("GNBayes",GaussianNB()),\
#("LDA", LinearDiscriminantAnalysis()), \
#("QDA", QuadraticDiscriminantAnalysis()), \
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),
#("rbf1SVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("rbf10SVM", SVC(C=10, gamma=.01, cache_size=200, class_weight={-1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("polySVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='poly', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("sigSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, coef0=0.0, degree=3, kernel='sigmoid', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("NuSVM", NuSVC(nu=0.9, kernel='rbf', degree=3, gamma=.100, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, verbose=False, max_iter=-1, random_state=None)),\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#("RF", RandomForestClassifier(class_weight={1:1}, n_estimators=10, criterion='gini',max_depth=3, min_samples_split=2, min_samples_leaf=1, max_features='auto', bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0))\
#("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=5, weights='uniform')),\
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=15, weights='distance')),\
#("rNeighbors-uniform", RadiusNeighborsClassifier(radius=8, weights='uniform')),\
#("rNeighbors-distance", RadiusNeighborsClassifier(radius=10, weights='distance')),\
#("VotingHard", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
#("GNBayes",GaussianNB()),\
#("LDA", LinearDiscriminantAnalysis()), \
#("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=5, weights='uniform')),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:500}, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=5, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
#], voting='hard', weights=None)),
("VotingSoft", VotingClassifier(estimators=[\
#("ada_discrete", AdaBoostClassifier(base_estimator=dt_stump, learning_rate=1, n_estimators=400, algorithm="SAMME")),\
#("ada_real", AdaBoostClassifier(base_estimator=dt_stump,learning_rate=1,n_estimators=180,algorithm="SAMME.R")),\
#("GBC", GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')),\
#("QDA", QuadraticDiscriminantAnalysis()),\
("GNBayes",GaussianNB()),\
("LDA", LinearDiscriminantAnalysis()), \
("kNeighbors-uniform", KNeighborsClassifier(n_neighbors=minDatapoints, weights='uniform')),\
#("MLPC", Classifier([Layer("Sigmoid", units=150), Layer("Softmax")],learning_rate=0.001, n_iter=25, verbose=True)),\
#("rbfSVM", SVC(C=1, gamma=.01, cache_size=200, class_weight={1:1}, kernel='rbf', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False)), \
#("kNeighbors-distance", KNeighborsClassifier(n_neighbors=8, weights='distance')),\
#("Bagging",BaggingClassifier(base_estimator=dt_stump, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=1, random_state=None, verbose=0)),\
#("ETC", ExtraTreesClassifier(class_weight={1:1}, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False)),\
], voting='soft', weights=None)),
]
inner_zz_std =2
outer_zz_std=4
if addAux ==True:
#trend mode
shortTrendSignalTypes = bias
shortModel=short_models[0]
shortTrendPipelines=[
[shortModel],
[fs_models[0],shortModel],
#[fs_models[1],shortModel],
]
pv2e_SignalTypes =bias
#pv2e_p2p_zz_std =long_zz_std
pv2e_Model=auxPairs_models[0]
pv2e_Pipelines=[
[pv2e_Model],
[fs_models[0],pv2e_Model],
#[fs_models[1],pv2e_p2pModel],
]
pv3s_SignalTypes = bias
#pv3s_v2v_zz_std =long_zz_std
pv3s_Model= auxPairs_models[0]
pv3s_Pipelines=[
[pv3s_Model],
[fs_models[0],pv3s_Model],
#[fs_models[1],pv3s_v2vModel],
]
else:
#trend mode
shortTrendSignalTypes = bias
shortModel=short_models[0]
shortTrendPipelines=[
[shortModel],
#[fs_models[0],shortModel],
#[fs_models[1],shortModel],
]
pv2e_SignalTypes =bias
#pv2e_p2p_zz_std =long_zz_std
pv2e_Model=noAuxPairs_models[0]
pv2e_Pipelines=[
[pv2e_Model],
#[fs_models[0],pv2e_Model],
#[fs_models[1],pv2e_p2pModel],
]
pv3s_SignalTypes = bias
#pv3s_v2v_zz_std =long_zz_std
pv3s_Model= noAuxPairs_models[0]
pv3s_Pipelines=[
[pv3s_Model],
#[fs_models[0],pv3s_Model],
#[fs_models[1],pv3s_v2vModel],
]
#cycle mode pipelines same as trend mode
shortCycleSignalTypes = shortTrendSignalTypes
shortModel=short_models[0]
shortCyclePipelines=shortTrendPipelines
p2pSignalTypes =pv2e_SignalTypes
#p2p_zz_std =long_zz_std
p2pModel=pv2e_Model
p2pPipelines=pv2e_Pipelines
v2vSignalTypes = pv3s_SignalTypes
#v2v_zz_std =long_zz_std
v2vModel= pv3s_Model
v2vPipelines=pv3s_Pipelines
dataSet, auxFuturesDict = loadFutures(auxFutures, dataPath,\
barSizeSetting, maxlb, ticker,\
signalPath, version, version_, maxReadLines,\
perturbData=perturbData, perturbDataPct=perturbDataPct,\
verbose=verbose, addAux=addAux)
#account for data loss
#validationSetLength = dataSet.shape[0]-supportResistanceLB*2
validationSetLength = dataSet.ix[startDate:].shape[0]-1
#hotfix for sdate=data.index[-validationSetLength-1].to_datetime()
if validationSetLength>supportResistanceLB:
validationSetLength=supportResistanceLB-2
dataSet2= dataSet.copy()
dataSet=dataSet.iloc[-(maxlb+validationSetLength):]
signalSets={
'wf_is_short':{},
'wf_is_pv2e_p2p':{},
'wf_is_pv3s_v2v':{},
}
DpsRankByMetricB={
'best_wf_is_short':{},
'best_wf_is_pv2e_p2p':{},
'best_wf_is_pv3s_v2v':{},
'best_wf_is_all':{},
}
DpsRankByMetricW={
'worst_wf_is_short':{},
'worst_wf_is_pv2e_p2p':{},
'worst_wf_is_pv3s_v2v':{},
'worst_wf_is_all':{},
}
finalDF={}
signalDF={}
stop=dataSet.shape[0]
dataSet.index = dataSet.index.to_datetime()
dataSet['gainAhead']=pd.Series(data=np.where(dataSet.Close.pct_change().shift(-1).values>0, 1,-1),index=dataSet.index)
dataSet['gainAhead'].set_value(dataSet.index[-1],0)
#for i in range(supportResistanceLB,dataSet.shape[0]):
for start,i in enumerate(range(supportResistanceLB,stop-supportResistanceLB+1)):
if start == supportResistanceLB or start==validationSetLength:
if showCharts==False and showFinalChartOnly == True:
showCharts=True
showIndicators=True
#maxlb is 2x support resistance lookback. the first half is used to prime indicators
data_primer = dataSet[start:maxlb+start]
data_primer.index = data_primer.index.to_datetime()
data_primer_ga = pd.Series(data=gainAhead(data_primer.Close),\
index=data_primer.index, name='gainAhead')
data_primer_ga_sig = pd.Series(data=np.where(gainAhead(data_primer.Close)>0,1,-1),\
index=data_primer.index, name='gainAhead')
dataSets={
'wf_is_short':pd.DataFrame(index=data_primer.index),
'wf_is_pv2e_p2p':pd.DataFrame(index=data_primer.index),
'wf_is_pv3s_v2v':pd.DataFrame(index=data_primer.index),
}
#set the data to move one bar at a time.
data = dataSet[i:i+supportResistanceLB]
contractExpiry = str(data.R.iloc[-1])
nrows = data.shape[0]
data.index = data.index.to_datetime()
pv_sorted = []
majorPeak=None
majorValley=None
minorPeak=None
minorValley=None
zz_std=outer_zz_std
#modes = smoothHurst(data.Close, data.shape[0]-1,threshold=adfPvalue, showPlot=True)
#pc = data.Close.pct_change().fillna(0)
#zs=abs(pc[-1]-pc.mean())/pc.std()
modes = mrClassifier(data.Close, data.shape[0]-1,threshold=adfPvalue, showPlot=debug,\
ticker=ticker+contractExpiry)
mode = modes[-1]
if i ==supportResistanceLB:
modePred = pd.Series(data=-1, index=data.index, name='adfPrediction')
modePred.set_value(data.index[-1],mode)
else:
modePred.set_value(data.index[-1],mode)
if mode ==0:
#sort by small peaks
reversePeaks = True
reverseValleys = False
#addAux = False
else:
#sort by large peaks
reversePeaks = False
reverseValleys = True
#addAux = True
#decrease stdev until there are three pivot points
while majorPeak ==None or majorValley == None or minorPeak ==None or minorValley == None:
zz = zg(data,data.Close.pct_change().std()*zz_std,\
-data.Close.pct_change().std()*zz_std)
#data2 has integer index
data2 = dataSet[i:i+supportResistanceLB].reset_index()
peaks = [x for x in np.where(zz.peak_valley_pivots()==1)[0]\
if supportResistanceLB-x>minDatapoints and x >0]
peaksSorted=data2.Close.iloc[peaks].sort_values(ascending=reversePeaks).index
if len(peaksSorted)>1:
if mode==0:
minorPeak = peaksSorted[0]
plist=[peak for peak in peaksSorted if abs(minorPeak-peak) > minDatapoints]
if len(plist)>0:
#find closest peak to ensure single cycle
idx = (np.abs(np.array(plist)-minorPeak)).argmin()
majorPeak = plist[idx]
else:
majorPeak = peaksSorted[0]
plist=[peak for peak in peaksSorted if abs(majorPeak-peak) > minDatapoints]
if len(plist)>0:
idx = (np.abs(np.array(plist)-majorPeak)).argmin()
minorPeak = plist[idx]
#peaksSorted=data2.Close.iloc[peaks].sort_values(ascending=False).index
#startPeak = peaksSorted[0]
#minorPeak = [peak for peak in peaksSorted if abs(startPeak-peak) > minDatapoints][0]
valleys = [x for x in np.where(zz.peak_valley_pivots()==-1)[0]\
if supportResistanceLB-x>minDatapoints and x >0]
valleysSorted = data2.Close.iloc[valleys].sort_values(ascending=reverseValleys).index
if len(valleysSorted)>1:
if mode==0:
minorValley = valleysSorted[0]
vlist = [valley for valley in valleysSorted if abs(minorValley-valley) > minDatapoints]
if len(vlist)>0:
#find closest valley to ensure single cycle
idx = (np.abs(np.array(vlist)-minorValley)).argmin()
majorValley = vlist[idx]
else:
majorValley = valleysSorted[0]
vlist = [valley for valley in valleysSorted if abs(majorValley-valley) > minDatapoints]
if len(vlist)>0:
idx = (np.abs(np.array(vlist)-majorValley)).argmin()
minorValley = vlist[idx]
#valleysSorted = data2.Close.iloc[valleys].sort_values(ascending=True).index
#startValley = valleysSorted[0]
#minorValley = [valley for valley in valleysSorted if abs(startValley-valley) > minDatapoints][0]
#shortStart=[x for x in np.where(zz.peak_valley_pivots()!=0)[0]\
# if supportResistanceLB-x>minDatapoints][-1]
#pv2e_p2p_period=sorted([supportResistanceLB-startPeak, supportResistanceLB-minorPeak])
#pv3s_v2v_period=sorted([supportResistanceLB-startValley, supportResistanceLB-minorValley])
pv_sorted = np.asarray(sorted(peaks+valleys))
zz_std=zz_std*.9
halfCycles = np.diff(pv_sorted).tolist()
cycleList = [[halfCycles[j], (x,data2.Close[x])] for j,x in \
enumerate(pv_sorted[1:])]
cycleList.append([supportResistanceLB-pv_sorted[-1],\
(supportResistanceLB, data2.Close.iloc[-1])])
#zz.plot_pivots(cycleList=cycleList)
#shBars = average(np.array(halfCycles)*2)
train_index = []
if mode==0:
#0 cycle mode
#calc peaks and valleys
#peaksSorted=data2.Close.iloc[peaks].sort_values(ascending=False).index
#majorPeak = peaksSorted[0]
#minorPeak = [peak for peak in peaksSorted if abs(majorPeak-peak) > minDatapoints][0]
#valleysSorted = data2.Close.iloc[valleys].sort_values(ascending=True).index
#majorValley = valleysSorted[0]
#minorValley = [valley for valley in valleysSorted if abs(majorValley-valley) > minDatapoints][0]
shortStart=[x for x in np.where(zz.peak_valley_pivots()!=0)[0]\
if supportResistanceLB-x>minDatapoints][-1]
short_period =supportResistanceLB- shortStart
p2p_period=sorted([supportResistanceLB-majorPeak, supportResistanceLB-minorPeak])
v2v_period=sorted([supportResistanceLB-majorValley, supportResistanceLB-minorValley])
ytrain1=zz.pivots_to_modes()[-len(data2.index[-short_period:-1]):]
ytrain2=zz.pivots_to_modes()[data2.index[-p2p_period[1]:-p2p_period[0]+1]+1]
ytrain3=zz.pivots_to_modes()[data2.index[-v2v_period[1]:-v2v_period[0]+1]+1]
train_index = [
#-1 to exclude last index for y_train
('wf_is_short',ytrain1,\
data2.index[-short_period:-1],shortCyclePipelines,\
shortCycleSignalTypes),
#+1 to include bottom of valley/top of the peak
('wf_is_pv2e_p2p',ytrain2,\
data2.index[-p2p_period[1]:-p2p_period[0]+1],\
p2pPipelines,p2pSignalTypes),
('wf_is_pv3s_v2v', ytrain3,\
data2.index[-v2v_period[1]:-v2v_period[0]+1],\
v2vPipelines,v2vSignalTypes)
]
else:
#1 trend mode
shortStart = pv_sorted[-1]
short_period =supportResistanceLB- shortStart
is_period='wf_is_short'
index = data2.index[-short_period:-1]
#spike mode
#y_train_zz = np.where(zz.pivots_to_modes()[-len(index):]<0,1,-1)
#non-spike mode
y_train_zz =zz.pivots_to_modes()[-len(index):]
signal_types=shortTrendSignalTypes
pipelines=shortTrendPipelines
train_index.append((is_period,y_train_zz,index,pipelines,signal_types))
pv2=2
if pv_sorted[-pv2] in peaks:
startPeak=pv_sorted[-pv2]
#-1 to exclude last index for y_train
pv2e_period=range(pv_sorted[-pv2],supportResistanceLB-1)
is_period='wf_is_pv2e_p2p'
index = data2.index[pv2e_period]
y_train_zz = zz.pivots_to_modes()[-len(index):]
signal_types=pv2e_SignalTypes
pipelines=pv2e_Pipelines
train_index.append((is_period,y_train_zz,index,pipelines,signal_types))
else:
startValley=pv_sorted[-pv2]
#-1 to exclude last index for y_train
pv2e_period=range(pv_sorted[-pv2],supportResistanceLB-1)
is_period='wf_is_pv2e_p2p'
index = data2.index[pv2e_period]
y_train_zz = zz.pivots_to_modes()[-len(index):]
signal_types=pv2e_SignalTypes
pipelines=pv2e_Pipelines
train_index.append((is_period,y_train_zz,index,pipelines,signal_types))
pv3=3
if pv_sorted[-pv3] in peaks:
startPeak=pv_sorted[-pv3]
#+1 because range starts from 0 index
#pv3s_v2v_period=range(pv_sorted[-3]+1,shortStart+1)
#pv3s_v2v_period=range(pv_sorted[-3],shortStart)
is_period='wf_is_pv3s_v2v'
index = data2.index[-supportResistanceLB-pv_sorted[-3]:-short_period+1]
y_train_zz = zz.pivots_to_modes()[index+1]
signal_types=pv3s_SignalTypes
pipelines=pv3s_Pipelines
train_index.append((is_period,y_train_zz,index,pipelines,signal_types))
else:
startValley=pv_sorted[-pv3]