-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadv_in_fin_ml.py
More file actions
1405 lines (1248 loc) · 51.8 KB
/
adv_in_fin_ml.py
File metadata and controls
1405 lines (1248 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import adfuller
from sklearn.metrics import log_loss,accuracy_score
from sklearn.datasets import make_classification
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection._split import _BaseKFold
from scipy.stats import norm
from itertools import product
from random import gauss
import scipy.cluster.hierarchy as sch
import time
import multiprocessing as mp
import datetime as dt
import sys
import copy
def pcaWeights(cov,riskDist=None,riskTarget=1.):
"""
PCA weights from a risk distribution R
"""
# Following the riskAlloc distribution, match riskTarget
eVal, eVec = np.linalg.eigh(cov) # must be Hermitian (complete complex square matrix A with A[i,j] = complex conjugate of A[j,i])
indicies = eVal.argsort()[::-1] # arguments for sorting
eVal, eVec = eVal[indicies], eVec[:,indicies] # sort
if riskDist is None: # make null dist
riskDist = np.zeros(cov.shape[0])
riskDist[-1] = 1
loads = riskTarget * (riskDist/eVal)**.5
wghts = np.dot(eVec, np.reshape(loads,(-1,1)))
return wghts
def getRolledSeries(pathIn,key):
series = pd.read_hdf(pathIn,key=key)
series['Time'] = pd.to_datetime(series['Time'],format='%Y%m%d%H%M%S%f')
series = series.set_index('Time')
gaps = rollGaps(series)
for fld in ['Close','VWAP']:series[fld] -= gaps
return series
def rollGaps(series,diction={'Instrument':'FUT_CUR_GEN_TICKER','Open':'PX_OPEN','Close':'PX_LAST'},matchEnd=True):
# Compute gaps at each roll, between previous close and next open
rollDates = series[diction['Instrument']].drop_duplicates(keep='first').index
gaps = series[diction['Close']]*0
iloc = list(series.index)
iloc = [iloc.index(i)-1 for i in rollDates] # index if dates prior to roll
gaps.loc[rollDates[1:]] = series[diction['Open']].loc[rollDates[1:]] - series[diction['Close']].iloc[iloc[1:]].values
gaps = gaps.cumsum()
if matchEnd:gaps -= gaps.iloc[-1] # roll backward
return gaps
def getDailyVol(close,span0=100):
"""
Daily vol, reindexed to close
"""
df0 = close.index.searchsorted(close.index-pd.Timedelta(days=1))
df0 = df0[df0>0]
df0 = pd.Series(close.index[df0-1], index=close.index[close.shape[0]-df0.shape[0]:])
df0 = close.loc[df0.index]/close.loc[df0.values].values-1 # daily returns
df0 = df0.ewm(span=span0).std()
return df0
def getTEvents(gRaw,h):
"""
symmetric CUSUM filter
"""
tEvents,sPos,sNeg = [],0,0
diff = gRaw.diff()
for i in diff.index[1:]:
sPos,sNeg = max(0,sPos+diff.loc[i]),min(0,sNeg+diff.loc[i])
if sNeg<-h:
sNeg=0;tEvents.append(i)
if sPos>h:
sPos=0;tEvents.append(i)
return pd.DatetimeIndex(tEvents)
def applyPtSlOnTl(close,events,ptSl,molecule):
"""
Triple-barrier labelling method
close = pandas series of prices
events = pandas dataframe with columns:
t1 = timestamp of vertical barrier. When the value is np.nan, there will be no vertical barrier
trgt = the unit width of the horizontal barriers
ptSl = a list of two non-negative float values:
ptSl[0] = The factor that multiplies the trgt to set the width of the upper barrier. If 0 no barrier
ptSl[1] = The factor that multiplies the trgt to set the width of the lower barrier. If 0 no barrier
molecule = a list with the subset of event indicies that will be processed by a single thread
"""
# apply stop loss/profit taking, if it takes place before t1 (end of event)
events_ = events.loc[molecule]
out = events_[['t1']].copy(deep=True)
if ptSl[0] > 0: pt=ptSl[0]*events_['trgt']
else: pt=pd.Series(index=events.index) # NaNs
if ptSl[1] > 0: sl=ptSl[1]*events_['trgt']
else:sl=pd.Series(index=events.index) # NaNs
for loc,t1 in events_['t1'].fillna(close.index[-1]).iteritems():
df0 = close[loc:t1] # path prices
df0 = (df0/close[loc] - 1)*events_.at[loc,'side'] # path returns
out.loc[loc,'sl'] = df0[df0<sl[loc]].index.min() # earliest stop loss
out.loc[loc,'pt'] = df0[df0>pt[loc]].index.min() # earliest profit taking
return out
def getEvents(close,tEvents,ptSl,trgt,minRet,numThreads,t1=False,side=None):
"""
Getting time of first touch of barriers
close = pandas series of prices
tEvents = pandas timeindex containing the timestamps that will seed every triple barrier
ptSl = A non negative float that sets the width of the two barriers
t1 = a pandas series with the timestamps of the verical barriers.
trgt = a pandas series of targets, expressed as absolute returns
minRet = the min target return required for running the triple barrier search
numThreads = number of threads used by the function concurrently
"""
# 1) get target
trgt = trgt.loc[tEvents]
trgt = trgt[trgt>minRet] # min retention
# 2) get t1 max holding period
if t1 is False: t1 = pd.Series(pd.NaT,index=tEvents)
# 3) form events object, apply stop loss on t1
if side is None: side_,ptSl_ = pd.Series(1.,index=trgt.index), [ptSl[0],ptSl[0]]
else: side_,ptSl_ = side.loc[trgt.index],ptSl[:2]
events = pd.concat({'t1':t1,'trgt':trgt,'side':side_}, axis=1).dropna(subset=['trgt'])
df0 = mpPandasObj(func=applyPtSlOnTl,pdObj=('molecule',events.index),numThreads=numThreads,close=close,events=events,ptSl=ptSl_)
events['t1'] = df0.dropna(how='all').min(axis=1) # pd.min ignores nan
if side is None: events = events.drop('side',axis=1)
return events
def getBins(events,close):
"""
Labelling for side and size
events.index = event's starttime
events['t1'] = event's endtime
events['trgt'] = event's target
events['side'] = implies algo's position side (optional)
Case 1: ('side' not in events): bin in (-1,1) <- label by price action
Case 2: ('side' in events): bin in (0,1) <- label by pnl (meta-labelling)
output dataframe columns:
ret = the return realized at the time of the first touched barrier
bin = label [-1,0,1] as a function of sign of an outcome
"""
# 1) prices aligned with events
events_ = events.dropna(subset=['t1'])
px = events_.index.union(events_['t1'].values).drop_duplicates()
px = close.reindex(px,method='bfill')
# 2) create out object
out = pd.DataFrame(index=events_.index)
out['ret'] = px.loc[events_['t1'].values].values/px.loc[events_.index] - 1
if 'side' in events_:out['ret'] *= events_['side'] # meta-labelling
out['bin'] = np.sign(out['ret'])
if 'side' in events_:out.loc[out['ret']<=0,'bin']=0 # meta-labelling
out.loc[out.index==events['t1'],'bin'] = 0
return out
def dropLabels(events,minPtc=.05):
"""
drop under populated labels
"""
while True:
df0 = events['bin'].value_counts(normalize=True)
if df0.min()>minPtc or df0.shape[0]<3:break
print('dropped label',df0.argmin(),df0.min())
events = events[events['bin'] != df0.argmin()]
return events
# Sample weights
def mpNumCoEvents(closeIdx,t1,molecule):
"""
Compute number of concurrent events per bar
molecule[0] = date of the first event on which the weight will be computed
molecule[1] = date of the last event of which the weight will be computed
Any event that starts before t1[molecule].max() impacts the count
"""
# 1) find events that span the period [molecule[0],molecule[-1]]
t1 = t1.fillna(closeIdx[-1]) # unclosed events must still impact other events
t1 = t1[t1>=molecule[0]] # events that end at or after molecule[0]
t1 = t1.loc[:t1[molecule].max()] # event that starts at or before t1[molecule].max()
# 2) events spanning a bar
iloc = closeIdx.searchsorted(np.array([t1.index[0],t1.max()]))
count = pd.Series(0,index=closeIdx[iloc[0]:iloc[1]+1])
for tIn, tOut in t1.iteritems():count.loc[tIn:tOut] += 1
return count.loc[molecule[0]:t1[molecule].max()]
def mpSampleTW(t1,numCoEvents,molecule):
"""
average uniqueness of an event over its lifespan
"""
wght = pd.Series(index=molecule)
for tIn, tOut in t1.loc[wght.index].iteritems():
wght.loc[tIn] = (1./numCoEvents.loc[tIn:tOut]).mean()
return wght
def getIndMatrix(barIx,t1):
"""
Get indicator matrix
"""
indM = pd.DataFrame(0,index=barIx,columns=range(t1.shape[0]))
for i, (t0,t1) in enumerate(t1.iteritems()):indM.loc[t0:t1,i] = 1.
return indM
def getAvgUniqueness(indM):
"""
Average uniqueness from indicator matrix
"""
c = indM.sum(axis=1) # concurrency
u = indM.div(c,axis=0) # uniqueness
avgU = u[u>0].mean() # average uniqueness
return avgU
def seqBootstrap(indM, sLength=None):
"""
Generates a sample via sequential bootstrap
"""
if sLength is None: sLength=indM.shape[1]
phi = []
while len(phi)<sLength:
avgU = pd.Series()
for i in indM:
indM_ = indM[phi+[i]] # reduce indM
avgU.loc[i] = getAvgUniqueness(indM_).iloc[-1]
prob = avgU/avgU.sum() # get prob
phi += [np.random.choice(indM.columns,p=prob)]
return phi
def getRndT1(numObs,numBars,maxH):
"""
random t1 series
"""
t1 = pd.Series()
for i in range(numObs):
ix = np.random.randint(0,numBars)
val = ix + np.random.randint(1,maxH)
t1.loc[ix] = val
return t1.sort_index()
def auxMC(numObs,numBars,maxH):
"""
Uniqueness from standard and sequential bootstaps
Parallelised auxiliary function
"""
t1 = getRndT1(numObs,numBars,maxH)
barIx = range(t1.max()+1)
indM = getIndMatrix(barIx,t1)
phi = np.random.choice(indM.columns,size=indM.shape[1])
stdU = getAvgUniqueness(indM[phi]).mean()
phi = seqBootstrap(indM)
seqU = getAvgUniqueness(indM[phi]).mean()
return {'stdU':stdU,'seqU':seqU}
def mainMC(numObs=10,numBars=100,maxH=5,numIters=1E6,numThreads=4):
"""
multi-threaded monte carlo experiments
"""
jobs=[]
for i in range(int(numIters)):
job = {'func':auxMC,'numObs':numObs,'numBars':numBars,'maxH':maxH}
jobs.append(job)
if numThreads==1:out=processJobs_(jobs)
else: out = processJobs(jobs,numThreads=numThreads)
print(pd.DataFrame(out).describe())
return
def mpSampleW(t1,numCoEvents,close,molecule):
"""
derive sample weight by return attribution
"""
ret = np.log(close).diff() # log returns for additivity
wght = pd.Series(index=molecule)
for tIn, tOut in t1.loc[wght.index].iteritems():
wght.loc[tIn] = (ret.loc[tIn:tOut]/numCoEvents.loc[tIn:tOut]).sum()
return wght.abs()
def getTimeDecay(tW,clfLastW=1.):
"""
apply piecewise linear decay to observed uniqueness (tW)
newest observation gets weight=1, oldest get weight=clfLastW
"""
clfW = tW.sort_index().cumsum()
if clfLastW >= 0: slope = (1.-clfLastW)/clfW.iloc[-1]
else: slope = 1./((clfLastW+1)*clfW.iloc[-1])
const = 1.-slope*clfW.iloc[-1]
clfW=const+slope*clfW
clfW[clfW<0]=0
print(const,slope)
return clfW
def getWeights(d,size):
w = [1.]
for k in range(1,size):
w_ = -w[-1]/k*(d-k+1)
w.append(w_)
w = np.array(w[::-1]).reshape(-1,1)
return w
def plotWeights(dRange,nPlots,size):
w = pd.DataFrame()
for d in np.linspace(dRange[0],dRange[1],nPlots):
w_ = getWeights(d,size=size)
w_ = pd.DataFrame(w_,index=range(w_.shape[0])[::1],columns=d)
w = w.join(w_,how='outer')
ax = w.plot()
ax.legend(loc='upper left'); mpl.show()
return
def fracDiff(series,d,thres=.01):
"""
Increasing width window with treatment of NaNs
Note 1: For thres=1 nothing is skipped
Note 2: d can be any positive fractional not necessarily in [0,1]
"""
# 1) compute weights for the longest series
w = getWeights(d,series.shape[0])
# 2) determine initial calcs skipped based on weight loss threshold
w_ = np.cumsum(abs(w))
w_/=w_[-1]
skip=w_[w_>thres].shape[0]
# 3) apply weights to values
df = {}
for name in series.columns:
seriesF,df_ = series[[name]].fillna(method='ffill').dropna(),pd.Series()
for iloc in range(skip,seriesF.shape[0]):
loc = seriesF.index[iloc]
if not np.isfinite(series.loc[loc,name]):continue # exclude NAs
df_[loc] = np.dot(w[-(iloc+1):,:],seriesF.loc[:loc])[0,0]
df[name] = df_.copy(deep=True)
df = pd.concat(df,axis=1)
return df
# fixed window width
def getWeights_FFD(d,thres):
w,k = [1.], 1
while True:
w_ = -w[-1]/k*(d-k+1)
if abs(w_)<thres:break
w.append(w_);k+=1
return np.array(w[::1]).reshape(-1,1)
def fracDiff_FDD(series,d,thres=1e-5):
"""
constant window width
"""
w,width,df=getWeights_FFD(d,thres),len(w)-1,{}
for name in series.columns:
seriesF,df_ = series[[name]].fillna(method='ffill').dropna(), pd.Series()
for iloc1 in range(width,seriesF.shape[0]):
loc0,loc1 = seriesF.index[iloc1-width],seriesF[iloc1]
if not np.isfinite(series.loc[loc1,name]): continue # exclude NAs
df_[loc1] = np.dot(w.T,seriesF.loc[loc0:loc1])[0,0]
df[name] = df_.copy(deep=True)
df = pd.concat(df,axis=1)
return df
def plotMinFFD():
path,instName = './','ES1_Index_Method12'
out = pd.DataFrame(columns=['adfStat','pVal','lags','nObs','95% conf','corr'])
df0 = pd.read_csv(path+instName+'.csv',indeex_col=0,parse_dates=True)
for d in np.linspace(0,1,11):
df1 = np.log(df0[['Close']]).resample('1D').last() # downcast to daily obs
df2 = fracDiff_FFD(df1,d,thres=.01)
corr = np.corrcoef(df1.loc[df2.index,'Close'],df2['Close'])[0,1]
df2 = adfuller(df2['Close'],maxlag=1,regression='c',autolag=None)
out.loc[d] = list(df2[:4]) + [df2[4]['5%']] + [corr] # with critical value
out.to_csv(path+instName+'_testMinFFD.csv')
out[['adfStat','corr']].plot(secondary_y='adfStat')
mpl.axhline(out['95% conf'].mean(),linewidth=1,color='r',linestyle='dotted')
mpl.savefig(path+instName+'_testMinFFD.png')
return
# validation
def getTrainTimes(t1,testTimes):
"""
Given testTimes, find the times of the training observations.
-t1.index: time when the observation started
-t1.value: time when the observation ended
-testTimes: times of testing observations a pandas series
"""
trn=t1.copy(deep=True)
for i,j in testTimes.iteritems():
df0 = trn[(i<=trn.index) & (trn.index<=j)].index # train starts with test
df1 = trn[(i<=trn) & (trn<=j)].index # train ends within test
df2 = trn[(trn.index<=i) & (j<=trn)].index # train envelops test
trn = trn.drop(df0.union(df1).union(df2))
return trn
def getEmbargoTimes(times,pctEmbargo):
"""
get embargo time for each bar
"""
step = int(times.shape[0]*pctEmbargo)
if step==0:
mbrg = pd.Series(times,index=times)
else:
mbrg = pd.Series(times[step:],index=times[:-step])
mbrg = mbrg.append(pd.Series(times[-1],index=times[-step:]))
return mbrg
class PurgedKFold(_BaseKFold):
"""
Extend KFold class to work with labels that span intervals
The train is purged of observations overlapping the test-label intervals
Test set is assumed contigous (shuffle=False), w/o training samples in between
"""
def __init__(self,n_splits=3,t1=None,pctEmbargo=0.):
if not isinstance(t1,pd.Series):
raise ValueError('Label Through Dates must be a pd.Series')
super(PurgedKFold,self).__init__(n_splits,shuffle=False,random_state=None)
self.t1 = t1
self.pctEmbargo = pctEmbargo
def split(self,X,y=None,groups=None):
if (X.index==self.t1.index).sum() != len(self.t1):
raise ValueError('X and ThruDateValues must have the same index')
indicies = np.arange(X.shape[0])
mbrg = int(X.shape[0]*self.pctEmbargo)
test_starts = [(i[0],i[-1]+1) for i in np.array_split(np.arange(X.shape[0]),self.n_splits)]
for i,j in test_starts:
t0 = self.t1.index[i] # start of test set
test_indicies = indicies[i:j]
maxT1Idx = self.t1.index.searchsorted(self.t1[test_indicies].max())
train_indicies = self.t1.index.searchsorted(self.t1[self.t1<=t0].index)
if maxT1Idx<X.shape[0]: # right train with embargo
train_indicies = np.concatenate((train_indicies,indicies[maxT1Idx+mbrg:]))
yield train_indicies,test_indicies
def cvScore(clf,X,y,sample_weight,scoring='neg_log_loss',t1=None,cv=None,cvGen=None,pctEmbargo=None):
if scoring not in ['neg_log_loss','accuracy']:
raise Exception('Wrong scoring method')
if cvGen is None:
cvGen = PurgedKFold(n_splits=cv,t1=t1,pctEmbargo=pctEmbargo) # purged
score = []
for train,test in cvGen.split(X=X):
fit = clf.fit(X=X.iloc[train,:],y=y.iloc[train],sample_weight=sample_weight.iloc[train].values)
if scoring == 'neg_log_loss':
prob = fit.predict_proba(X.iloc[test,:])
score_ = -log_loss(y.iloc[test],prob,sample_weight=sample_weight.iloc[test].values,labels=clf.classes_)
else:
prob = fit.predict_proba(X.iloc[test,:])
score_ = accuracy_score(y.iloc[test],prob,sample_weight=sample_weight.iloc[test].values)
score.append(score_)
return np.array(score)
# feature importance
def featImpMDI(fit,featNames):
"""
feat importance based on IS mean impurity reduction
"""
df0 = {i:tree.feature_importances_ for i,tree in enumerate(fit.estimators_)}
df0 = pd.DataFrame.from_dict(df0,orient='index')
df0.columns = featNames
df0 = df0.replace(0,np.nan) # because max_features=1
imp = pd.concat({'mean':df0.mean(),'std':df0.std()*df0.shape[0]**-.5},axis=1)
imp /= imp['mean'].sum()
return imp
def featImpMDA(clf,X,y,cv,sample_weight,t1,pctEmbargo,scoring='neg_log_loss'):
"""
feat importance based on OOS score reduction
"""
if scoring not in ['neg_log_loss','accuracy']:
raise Exception('Wrong scoring method')
cvGen = PurgedKFold(n_splits=cv,t1=t1,pctEmbargo=pctEmbargo) # purged
scr0,scr1 = pd.Series(),pd.DataFrame(columns=X.columns)
for i, (train,test) in enumerate(cvGen.split(X=X)):
X0,y0,w0 = X.iloc[train,:],y.iloc[train],sample_weight.iloc[train]
X1,y1,w1 = X.iloc[test,:],y.iloc[test],sample_weight.iloc[test]
fit = clf.fit(X=X0,y=y0,sample_weight=w0.values)
if scoring == 'neg_log_loss':
prob = fit.predict_proba(X1)
scr0.loc[i] = -log_loss(y1,prob,sample_weight=w1.values,labels=clf.classes_)
else:
prob = fit.predict_proba(X1)
scr0.loc[i] = accuracy_score(y1,prob,sample_weight=w1.iloc[test].values)
for j in X.columns:
X1_ = X1.copy(deep=True)
np.random.shuffle(X1_[j].values) # permutation of single column
if scoring == 'neg_log_loss':
prob = fit.predict_proba(X1_)
scr1.loc[i,j] = -log_loss(y1,prob,sample_weight=w1.values,labels=clf.classes_)
else:
prob = fit.predict_proba(X1_)
scr1.loc[i.j] = accuracy_score(y1,prob,sample_weight=w1.iloc[test].values)
imp = (-scr1).add(scr0,axis=0)
if scoring == 'neg_log_loss':imp = imp/-scr1
else:imp=imp/(1.-scr1)
imp = pd.concat({'mean':imp.mean(),'std':imp.std()*imp.shape[0]**-.5},axis=1)
return imp,scr0.mean()
def auxFeatImpSFI(featNames,clf,trnsX,cont,scoring,cvGen):
"""
single feat importance
"""
imp = pd.DataFrame(columns=['mean','std'])
for featName in featNames:
df0 = cvScore(clf,X=trnsX[[featname]],y=cont['bin'],sample_weight=cont['w'],scoring=scoring,cvGen=cvGen)
imp.loc[featName,'mean'] = df0.mean()
imp.loc[featName,'std'] = df0.std()*df0.shape[0]**-.5
return imp
def get_eVec(dot,varThres):
"""
compute eVec from dot prod matrix, reduce dimension
"""
eVal,eVec = np.linalg.eigh(dot)
idx = eVal.argsort()[::-1] # args for sorting eVal
eVal,eVec = eVal[idx],eVec[:,idx]
# only positive eVals
eVal = pd.Series(eVal,index=['PC_'+str(i+1) for i in range(eVal.shape[0])])
eVec = pd.DataFrame(eVec,index=dot.index,columns=eVal.index)
eVec = eVec.loc[:,eVal.index]
# dim reduction
cumVar = eVal.cumsum()/eVal.sum()
dim = cumVar.values.searchsorted(varThres)
eVal,eVec = eVal.iloc[:dim+1],eVec.iloc[:,:dim+1]
return eVal,eVec
def orthFeats(dfX,varThres=.95):
"""
Given a datafram dfX of features, compute orthogonal features dfP
"""
dfZ = dfX.sub(dfX.mean(),axis=1).div(dfX.std(),axis=1) # standardise
dot = pd.DataFrame(np.dot(dfZ.T,dfZ),index=dfX.columns,columns=dfX.columns)
eVal,eVec = get_eVec(dot, varThres)
dfP = np.dot(dfZ,eVec)
return dfP
def getTestData(n_features=40,n_informative=10,n_redundant=10,n_samples=10000):
"""
Generate a random dataset for a classification problem
"""
trnsX,cont = make_classification(n_samples=n_samples,n_features=n_features,n_informative=n_informative,
n_redundant=n_redundant,random_state=0,shuffle=False)
df0 = pd.DatetimeIndex(periods=n_samples,freq=pd.tseries.offsets.BDay(),end=pd.datetime.today())
trnsX,cont = pd.DataFrame(trnsX,index=df0),pd.Series(cont,index=df0).to_frame('bin')
df0 = ['I_'+str(i) for i in range(n_informative)]+['R_'+str(i) for i in range(n_redundant)]
df0 += ['N_'+str(i) for i in range(n_features-len(df0))]
trnsX.columns = df0
cont['w'] = 1./cont.shape[0]
cont['t1'] = pd.Series(cont.index,index=cont.index)
return trnsX,cont
def featImportance(trnsX,cont,n_estimators=1000,cv=10,max_samples=1.,numThreads=4,
pctEmbargo=0,scoring='accuracy',method='SFI',minWLeaf=0.,**kargs):
"""
feature importance from a random forest
"""
n_jobs = (-1 if numThreads>1 else 1) # run 1 thread with ht_helper in dirac1
# prepare classifier
clf = DecisionTreeClassifier(criterion='entropy',max_features=1,class_weight='balanced',
min_weight_fraction_leaf=minWLeaf)
clf = BaggingClassifier(base_estimator=clf,n_estimators=n_estimators,max_features=1.,
max_samples=max_samples,oob_score=True,n_jobs=n_jobs)
fit = clf.fit(X=trnsX,y=cont['bin'],sample_weight=cont['w'].values)
oob = fit.oob_score_
if method == 'MDI':
imp = featImpMDI(fit,featNames=trnsX.columns)
oos = cvScore(clf,X=trnsX,y=cont['bin'],cv=cv,sample_weight=cont['w'],
t1=cont['t1'],pctEmbargo=pctEmbargo,scoring=scoring).mean()
elif method == 'MDA':
imp,oos = featImpMDA(clf,X=trnsX,y=cont['t1'],cv=cv,sample_weight=cont['w'],
t1=cont['t1'],pctEmbargo=pctEmbargo,scoring=scoring)
elif method == 'SFI':
cvGen = PurgedKFold(n_splits=cv,t1=cont['t1'],pctEmbargo=pctEmbargo)
oos = cvScore(clf,X=trnsX,y=cont['bin'],sample_weight=cont['w'],
scoring=scoring,cvGen=cvGen).mean()
clf.n_jobs = 1 # paralellise auxFeatImpSFI rather than clf
imp = mpPandasObj(auxFeatImpSFI,('featNames',trnsX.columns),numThreads,
clf=clf,trnsX=trnsX,cont=cont,scoring=scoring,cvGen=cvGen)
return imp,oob,oos
def testFunc(n_features=40,n_informative=10,n_redundant=10,n_estimators=1000,
n_samples=10000,cv=10):
"""
test the perdormance of the feat importance on artificial data
Nr noise features = n_features-n_informative-n_redundant
"""
trnsX,cont = getTestData(n_features,n_informative,n_redundant,n_samples)
dict0 = {'minWLeaf':[0.],'scoring':['accuracy'],'method':['MDI','MDA','SFI'],
'max_samples':[1.]}
jobs,out = (dict(zip(dict0,i)) for i in product(*dict0.values())),[]
kargs={'pathOut':'./testFunc','n_estimators':n_estimators,'tag':'testFunc','cv':cv}
for job in jobs:
job['simNum'] = job['method']+'_'+job['scoring']+'_'+'%.2f'%job['minWLeaf']+'_'+str(job['max_samples'])
print(job['simNum'])
kargs.update(job)
imp,oob,oos = featImportance(trnsX=trnsX,cont=cont,**kargs)
plotFeatImportance(imp=imp,oob=oob,oos=oos,**kargs)
df0 = imp[['mean']]/imp['mean'].abs().sum()
df0['type'] = df0.groupby('type')['mean'].sum().to_dict()
df0.update({'oob':oob,'oos':oos});df0.update(job)
out.append(df0)
out = pd.DataFrame(out).sort_values(['method','scoring','minWleaf','max_samples'])
out = out['method','scoring','minWLeaf','max_samples','I','R','N','oob','oos']
out.to_csv(kargs['pathOut']+'stats.csv')
return
def plotFeatImportance(pathOut,imp,oob,oos,method,tag=0,simNum=0,**kargs):
"""
plot mean imp bars with std
"""
mpl.figure(figsize=(10,imp.shape[0]/5.))
imp = imp.sort_values('mean',ascending=True)
ax = imp['mean'].plot(kind='barh',color='b',alpha=.25,xerr=imp['std'],
error_kw={'ecolor':'r'})
if method == 'MDI':
mpl.xlim([0,imp.sum(axis=1).max()])
mpl.axvline(1./imp.shape[0],linewidth=1,color='r',linestyle='dotted')
ax.get_yaxis().set_visible(False)
for i,j in zip(ax.patches,imp.index):ax.text(i.get_width()/2,i.get_y()+i.get_height()/2,
j,ha='center',va='center',color='black')
mpl.title('tag='+tag+' | simNum='+simNum+' | oob='+str(round(oob,4))+' | oos='+str(round(oos,4)))
mpl.savefig(pathOut+'featImportance_'+str(simNum)+'.png',dpi=100)
mpl.clf();mpl.close()
return
# hyperparameter tuning with cross validation
class MyPipeline(Pipeline):
def fit(self,X,y,sample_weight=None,**fit_params):
if sample_weight is not None:
fit_params[self.steps[-1][0]+'__sample_weight']=sample_weight
return super(MyPipeline,self).fit(X,y,**fit_params)
def clfHyperFitRand(feat,lbl,t1,pipe_clf,param_grid,cv=3,bagging=[0,None,1.],
rndSearchIter=0,n_jobs=-1,pctEmbargo=0,**fit_params):
"""
randomised search with purged k fold cross val
"""
if set(lbl.values)=={0,1}:scoring='f1' # f1 for meta-labelling
else: scoring='neg_log_loss' # symmetric to all cases
# 1) hyper parameter search on training data
inner_cv = PurgedKFold(n_splits=cv,t1=t1,pctEmbargo=pctEmbargo) # purged
if rndSearchIter==0:
gs = GridSearchCV(estimator=pipe_clf,param_grid=param_grid,scoring=scoring,
cv=inner_cv,n_jobs=n_jobs,iid=False)
else:
gs = RandomSearchCV(estimator=pipe_clf,param_grid=param_grid,scoring=scoring,
cv=inner_cv,n_jobs=n_jobs,iid=False,n_iter=rndSearchIter)
gs = gs.fit(feat,lbl,**fit_params).best_estimator_ # pipeline
# 2) fit validated model on the entirety of the data
if bagging[1] > 0:
gs = BaggingClassifier(base_estimator=MyPipeline(gs.steps),n_estimators=int(bagging[0]),
max_samples=float(bagging[1]),max_features=float(bagging[2]),n_jobs=n_jobs)
gs = gs.fit(feat,lbl,sample_weight=fit_params[gs.base_estimator.steps[-1][0]+'__sample_weight'])
gs=Pipeline(['bag',gs])
return gs
# backtesting
# bet sizing
def getSignal(events,stepSize,prob,numClasses,numThreads,**kargs):
"""
get signals from predictions
"""
if prob.shape[0]==0:return pd.Series()
# 1) generate signals from multinomial classification (one-vs-rest,OvR)
signal0 = (prob-1./numClasses)/(prob*(1-prob))**.5 # t value of OvR
signal0 = pred*(2*norm.cdf(signal0)-1) # signal=side*size
if 'side' in events:signal0*=events.loc[signal0.index,'side'] # meta-labelling
# 2) compute average signal among those concurrently open
df0 = signal0.to_frame('signal').join(events[['t1']],how='left')
df0 = avgActiveSignals(df0,numThreads)
signal1 = discreteSignal(signal0=df0,stepSize=stepSize)
return signal1
def avgActiveSignals(signals,numThreads):
"""
compute the average signal among those active
"""
tPnts = set(signals['t1'].dropna().values)
tPnts = tPnts.union(signals.index.values)
tPnts = list(tPnts);tPnts.sort()
out = mpPandasObj(mpAvgActiveSignals,('molecule',tPnts),numThreads,signals=signals)
return out
def mpAvgActiveSignals(signals,molecule):
"""
At time loc, average signal among those still active
signal is active if:
issued before or at loc AND
loc before signals endtime, or endtime is unknown NaT
"""
out = pd.Series()
for loc in molecule:
df0 = (signals.index.values<=loc)&((loc<singals['t1'])|pd.isnull(signals['t1']))
act = signals[df0].index
if len(act)>0:out[loc]=signals.loc[act,'signal'].mean()
else: out[act]=0 # no signals active at this time
return out
def discreteSignal(signal0,stepSize):
"""
discretise signal
"""
signal1 = (signal0/stepSize).round()*stepSize #discretise
signal1[signal1>1] = 1 # cap
signal1[signal1<0] = 0 # floor
return signal1
# dynamic position size and limit price (using sigmoid function)
def betSize(w,x):
return x*(w+x**2)**-.5
def getTpos(w,f,mP,maxPos):
return int(betSize(w,f-mP)*maxPos)
def invPrice(f,w,m):
return f-m*(w/(1-m**2))**.5
def limitPrice(tPos,pos,f,w,maxPos):
sgn = (1 if tPos>=pos else -1)
lP = 0
for j in range(abs(pos+sgn),abs(tPos+1)):
lP+=invPrice(f,w,j/float(maxPos))
lP /= tPos-pos
return lP
def getW(x,m):
# 0 < alpha < 1
return x**2*(m**-2-1)
# optimal trading rules
def batch(coeffs,nIter=1e5,maxHP=100,rPT=np.linspace(.5,10,20),
rSLm=np.linspace(.5,10,20),seed=0):
phi,output1 = 2**(-1./coeffs['hl']), []
for comb_ in product(rPT,rSLm):
output2 = []
for iter_ in range(int(nIter)):
p,hp,count = seed,0,0
while True:
p = (1-phi)*coeffs['forecast']+phi*p+coeffs['sigma']*gauss(0,1)
cP = p-seed;hp+=1
if cP>comb_[0] or cP<-comb_[1] or hp>maxHP:
output2.append(cP)
break
mean,std = np.mean(output2),np.std(output2)
print(comb_[0],comb_[1],mean,std,mean/std)
output1.append((comb_[0],comb_[1],mean,std,mean/std))
return output1
# backtest stats
def getHoldingPeroid(tPos):
"""
Derive avg holding period (in days) using avg entry time pairing algo
"""
hp,tEntry = pd.DataFrame(columns=['dT','w']),0.
pDiff,tDiff = tPos.diff(),(tPos.index-tPos.index[0])/np.timedelta64(1,'D')
for i in range(1,tPos.shape[0]):
if pDiff.iloc[i]*tPos.iloc[i-1]>=0: # increased or unchanged
if tPos.iloc[i] != 0:
tEntry = (tEntry*tPos.iloc[i-1]+tDiff[i]*pDiff.iloc[i])/tPos.iloc[i]
else: # decreased
if tPos.iloc[i]*tPos.iloc[i-1]<0: # flip
hp.loc[tPos.index[i],['dT','w']] = (tDiff[i]-tEntry,abs(tPos.iloc[i-1]))
tEntry = tDiff[i] # reset entry time
else:
hp.loc[tPos.index[i],['dT','w']] = (tDiff[i]-tEntry,abs(pDiff.iloc[i]))
if hp['w'].sum()>0:hp=(hp['dT']*hp['w']).sum()/hp['w'].sum()
else: hp=np.nan
return hp
def getHHI(betRet):
if betRet.shape[0]<=2:return np.nan
wght = betRet/betRet.sum()
hhi = (wght**2).sum()
hhi = (hhi-betRet.shape[0]**-1)/(1.-betRet.shape[0]**-1)
return hhi
def computeDD_TuW(series,dollars=False):
"""
compute series of drawdowns and time under water because of them
"""
df0 = series.to_frame('pnl')
df0['hwm'] = series.expanding().max()
df1 = df0.groupby('hmw').min().reset_index()
df1.columns = ['hmw','min']
df1.index = df0['hmw'].dropduplicate(keep='first').index # time of hmw
df1 = df1[df1['hmw']>df1['min']] # hmw followed by a drawdown
if dollars: dd=df1['hmw']-df1['min']
else: dd = 1-df1['min']/df1['hmw']
tuw = ((df1.index[1:]-df1.index[:-1])/np.timedlta64(1,'Y')).values # in years
tuw = pd.Series(tuw,index=df1.index[:-1])
return dd,tuw
def binHR(sl,pt,freq,tSR):
"""
Given a trading rule charicterised by the parameters {sl,pt,freq},
what's the min precision p reqired to achieve a Sharpe ratio tSR?
sl: stop loss threshold
pt: profit taking threshold
freq: number of bets per year
tSR: target annual Sharpe Ratio
p: the min precision rate p required to achieve tSR
"""
a = (freq+tSR**2)*(pt-sl)**2
b = (2*freq*sl-tSR**2*(pt-sl))*(pt-sl)
c = freq*sl**2
p = (-b+(b**2-4*a*c)**.5)/(2.*a)
return p
def binFreq(sl,pt,p,tSR):
"""
Given a trading rule characterised by the parameters {sl,pt,freq},
what's the number of bets per tear needed to achieve a Sharpe ratio
tSR with precision p?
sl: stop loss threshold
pt: profit taking threshold
p: the precision rate p
tSR: target annual Sharpe Ratio
freq: number of bets per year needed
"""
freq = (tSR*(pt-sl))**2*p*(1-p)/((pt-sl)*p+sl)**2 # possible ectraneous
if not np.isclose(binSR(sl,pt,freq,p),tSR):return
return freq
def getQuasiDiag(link):
"""
sort clustered items by distance.
link = linkage matrix
"""
link = link.astype(int)
sortIx = pd.Series([link[-1,0],link[-1,1]])
numItems = link[-1,3] # number of original items
while sortIx.max()>=numItems:
sortIx.index = range(0,sortIx.shape[0]*2,2) # make space
df0 = sortIx[sortIx>=numItems] # find clusters
i = df0.index; j = df0.values-numItems
sortIx[i] = link[j,0] # item 1
df0 = pd.Series(link[j,1],index=i+1)
sortIx = sortIx.append(df0) # item 2
sortIx = sortIx.sort_index() # resort
sortIx.index = range(sortIx.shape[0]) # reindex
return sortIx.tolist()
def getRecBipart(cov,sortIx):
"""
compute HRP alloc
"""
w = pd.Series(1,index=sortIx)
cItems = [sortIx] # initialise all items in one cluster
while len(cItems)>0:
cItems = [i[j:k] for i in cItems for j,k in ((0,len(i)/2),(len(i)/2,l2n(i))) if len(i)>1] # bi-section
for i in range(0,len(cItems),2): # parse in pairs
cItems0 = cItems[i] # cluster 1
cItems1 = cItems[i+1] # cluster 2
cVar0 = getClusterVar(cov,cItems0)
cVar1 = getClusterVar(cov,cItems1)
alpha = 1- cVar0/(cVar0+cVar1)
w[cItems0] *= alpha # weight 1
w[cItems1] *= 1-alpha # weight 2
return w
def getIVP(cov,**kargs):
"""
compute the inverse-variance portfolio
"""
ivp = 1./np.diag(cov)
ivp /= ivp.sum()
return ivp
def getClusterVar(cov,cItems):
"""
compute variance per cluster
"""
cov_ = cov.loc[cItems,cItems] # matrix slice
w_ = getIVP(cov_).reshape(-1,1)
cVar = np.dot(np.dot(w_.T,cov_),w_)[0,0]
return cVar
# useful financial features
def get_bsadf(logP,minSL,constant,lags):
"""
SADF's inner loop
logP = pandas series of log prices
minSL minimum sample length tau, used ny the final regression
constant = the regressions time trend component
-'nc' = no time trend only a constant
-'ct' = constant plus linear time trend
-'ctt' = constant plus a second degree polynomial time trend
lags = the number of lags used in the ADF specification
"""
y,x = getYX(logP,constant=constant,lags=lags)
startPoints,bsadf,allADF = range(0,y.shape[0]+lags-minSL+1),None,[]
for start in startPoints:
y_,x_ = y[start:],x[start:]
bMean_,bStd_ = getBetas(y_,x_)
bMean_,bStd_ = bMean_[0,0],bStd_[0,0]**.5
allADF.append(bMean_/bStd_)
if allADF[-1]>bsadf:bsadf=allADF[-1]
out = {'Time':logP.index[-1],'gsadf':bsadf}
return out
def getYX(series,constant,lags):
"""
Prepare data
"""
series_ = series.diff().dropna()
x = lagDF(series_,lags).dropna()
x.iloc[:,0] = series.values[-x.shape[0]-1:-1,0] # lagged level
y = series_.iloc[-x.shape[0]:].values
if constant != 'nc':
x = np.append(x,np.ones((x.shape[0],1)),axis=1)
if constant[:2]=='ct':
trend = np.arange(x.shape[0]).reshape(-1,1)
x = np.append(x,trend,axis=1)
if constant=='ctt':
x = np.append(x,trend**2,axis=1)
return y,x
def lagDF(df0,lags):
df1 = pd.DataFrame()
if isinstance(lags,int):lags=range(lags+1)
else:lags=[int(lag) for lag in lags]
for lag in lags:
df_ = df0.shift(lag).copy(deep=True)
df_.columns = [str(i)+'_'+str(lag) for i in df_.columns]
df1 = df1.join(df_,how='outer')
return df1
def getBetas(y,x):
xy = np.dot(x.T,y)
xx = np.dot(x.T,x)
xxinv = np.linalg.inv(xx)
bMean = np.dot(xxinv,xy)
err = y - np.dot(x,bMean)
bVar = np.dot(err.T,err)/(x.shape[0]-x.shape[1])*xxinv
return bMean,bVar
# entropy
def plugIn(msg,w):
"""
compute the prob mass function fo a one-dim discrete rv
"""
pmf = pmf1(msg,w)
out = -sum([pmf[i]*np.log2(pmf[i]) for i in pmf])/w
return out,pmf
def pmf1(msg,w):
"""
Compute the prob mass function for a one-dim rv
len(msg)-w occurences
"""
lib = {}
if not isinstance(msg,str):msg=''.join(map(str,msg))
for i in range(w,len(msg)):
msg_ = msg[i-w:i]
if msg_ not in lib:lib[msg_]=[i-w]
else: lib[msg_]=lib[msg_]+[i-w]
pmf = float(len(msg)-w)
pmf = {i:len(lib[i])/pmf for i in lib}
return pmf
def lemelZiv_lib(msg):
"""
A library built using the LZ algorithm
"""
i,lib = 1,[msg[0]]
while i<len(msg):
for j in range(i,len(msg)):
msg_ = msg[i:j+1]
if msg_ not in lib:
lib.append(msg_)
break
i = j+1
return lib
def matchLength(msg,i,n):
"""
Maximum matched length+1, with overlap
i>=n & len(msg) >= i+n
"""
subS = ''
for l in range(n):
msg1 = msg[i:i+1+1]
for j in range(i-n,i):
msg0 = msg[j:j+1+1]