-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinancialMachineLearning.py
More file actions
2148 lines (1894 loc) · 89.3 KB
/
FinancialMachineLearning.py
File metadata and controls
2148 lines (1894 loc) · 89.3 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
# ===============================================================================================================
# Libraries
# =================================================================================================================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import re
import os
import time
from collections import OrderedDict as od
import math
import sys
import datetime as dt
from pathlib import PurePath, Path
from dask import dataframe as dd
from dask.diagnostics import ProgressBar
import scipy.stats as stats
from scipy import interp
import copyreg, types, multiprocessing as mp
import copy
import platform
from multiprocessing import cpu_count
from numba import jit
import pyarrow as pa
import pyarrow.parquet as pq
from tqdm import tqdm, tqdm_notebook
import warnings
#statsmodels
import statsmodels.api as sm
import statsmodels.tsa.stattools as tsa
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
#sklearn
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, classification_report
from sklearn.metrics import log_loss, accuracy_score
from itertools import product
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.pipeline import Pipeline
from sklearn.model_selection._split import _BaseKFold
from sklearn import metrics
warnings.filterwarnings("ignore")
RANDOM_STATE = 42
pd.set_option('display.max_rows', 100)
pbar = ProgressBar()
pbar.register()
# ===============================================================================================================
# Bar Sampling
# =================================================================================================================
def getDataFrame(df):
"""
High Frequency Data를 정리해주는 함수입니다.
Return
----------------------------
- pandas.DataFrame형태의 OHCL Data가 반환됩니다
"""
temp = df[['price', 'buy', 'sell', 'volume']]
temp['v'] = temp.volume
temp['dv'] = temp.volume * temp.price
temp.index = pd.to_datetime(temp.index)
return temp
@jit(nopython = True)
def numba_isclose(a, b, rel_tol = 1e-09, abs_tol = 0.0):
# rel_tol: relative tolerance
# abs_tol: absolute tolerance
return np.fabs(a-b) <= np.fmax(rel_tol*np.fmax(np.fabs(a),np.fabs(b)),abs_tol)
def getOHLC(ref, sub):
"""
fn: get ohlc from custom
# args
ref: reference pandas series with all prices
sub: custom tick pandas series
# returns
tick_df: dataframe with ohlc values
"""
ohlc = []
# for i in tqdm(range(sub.index.shape[0]-1)):
for i in range(sub.index.shape[0] - 1):
start, end = sub.index[i], sub.index[i + 1]
tmp_ref = ref.loc[start:end]
max_px, min_px = tmp_ref.max(), tmp_ref.min()
o, h, l, c = sub.iloc[i], max_px, min_px, sub.iloc[i + 1]
ohlc.append((end, start, o, h, l, c))
cols = ['end', 'start', 'open', 'high', 'low', 'close']
return (pd.DataFrame(ohlc, columns = cols))
@jit(nopython=True)
def madOutlier(y, thresh = 3.):
"""
outlier를 탐지하는 함수입니다.
:param y: pandas.Series 형태의 Price 계열 input data입니다
:param thresh: outlier를 탐지하기 위한 구간을 지정합니다(default = 3.0)
:return:
"""
median = np.median(y)
print(median)
diff = np.sum((y - median) ** 2, axis=-1)
diff = np.sqrt(diff)
print(diff)
med_abs_deviation = np.median(diff)
modified_z_score = 0.6745 * diff / med_abs_deviation
print(modified_z_score)
return modified_z_score > thresh
def BarSampling(df, column, threshold, tick = False):
"""
Argument
----------------------------
df : getDataFrame 함수의 output을 입력으로 사용합니다
column : 기준으로 사용할 column을 지정합니다
'price' - time bar 사용
'v' - volume 사용
'dv' - dollar value 사용
tick : tick bar를 사용하고 싶은 경우 True로 변경합니다
Hyperparameter
----------------------------
threshold : threshold를 넘길 때마다 Sampling
output
----------------------------
DataFrame 형태의 Sampling된 Data가 반환됩니다
"""
t = df[column]
ts = 0
idx = []
if tick:
for i, x in enumerate(t):
ts += 1
if ts >= threshold:
idx.append(i)
ts = 0
else:
for i, x in enumerate(t):
ts += x
if ts >= threshold:
idx.append(i)
ts = 0
return df.iloc[idx].drop_duplicates()
def get_ratio(df, column, n_ticks):
"""
Argument
----------------------------
df : bar_sampling 함수의 output을 입력으로 사용합니다
column : 비율 기준 설정 (dollar_value, volume)
n_ticks : tick 지정
"""
return df[column].sum() / n_ticks
def select_sample_data(ref, sub, price_col, date):
"""
DatetimeIndex를 index로 가진 Data를 기반으로 Sample Data를 선정합니다
# args
ref: 틱을 가지고 있는 DataFrame
sub: subordinated pd.DataFrame of prices
price_col: str(), price colume
date: str(), date to select
# returns
xdf: ref pd.Series
xtdf: subordinated pd.Series
"""
xdf = ref[price_col].loc[date]
xtdf = sub[price_col].loc[date]
return xdf, xtdf
def count_bars(df, price_col = 'price'):
"""
일주일에 Bar가 Sampling되는 횟수를 계산해 줍니다
"""
return df.groupby(pd.Grouper(freq='1W'))[price_col].count()
def scale(s):
"""
비교를 위해 Scale을 조정해 줍니다
"""
return (s - s.min()) / (s.max() - s.min())
def getReturns(s):
arr = np.diff(np.log(s))
return (pd.Series(arr, index=s.index[1:]))
def get_test_stats(bar_types, bar_returns, test_func, *args, **kwds):
dct = {bar: (int(bar_ret.shape[0]), test_func(bar_ret, *args, **kwds))
for bar, bar_ret in zip(bar_types, bar_returns)}
df = (pd.DataFrame.from_dict(dct)
.rename(index={0: 'sample size', 1: f'{test_func.__name__}_stat'}).T)
return df
def df_rolling_autocorr(df, window, lag = 1):
"""
DataFrame의 rolling column-wise autocorrelation을 계산합니다
"""
return (df.rolling(window = window).corr(df.shift(lag)))
def signed_tick(tick, initial_value=1.0):
diff = tick['price'] - tick['price'].shift(1)
return (abs(diff) / diff).ffill().fillna(initial_value)
def tick_imbalance_bar(tick, initial_expected_bar_size = 150, initial_expected_signed_tick = .1,
lambda_bar_size = .1, lambda_signed_tick = .1):
tick = tick.sort_index(ascending = True)
tick = tick.reset_index()
# Part 1. Tick imbalance 값을 기반으로, bar numbering(`tick_imbalance_group`)
tick_imbalance = signed_tick(tick).cumsum().values
tick_imbalance_group = []
expected_bar_size = initial_expected_bar_size
expected_signed_tick = initial_expected_signed_tick
expected_tick_imbalance = expected_bar_size * expected_signed_tick
current_group = 1
previous_i = 0
for i in range(len(tick)):
tick_imbalance_group.append(current_group)
if abs(tick_imbalance[i]) >= abs(expected_tick_imbalance): # 수식이 복잡해 보이지만 EMA임.
expected_bar_size = (lambda_bar_size * (i - previous_i + 1) + (1 - lambda_bar_size) * expected_bar_size)
expected_signed_tick = (lambda_signed_tick * tick_imbalance[i] /
(i - previous_i + 1) + (1 - lambda_signed_tick) * expected_signed_tick)
expected_tick_imbalance = expected_bar_size * expected_signed_tick
tick_imbalance -= tick_imbalance[i]
previous_i = i
current_group += 1
# Part 2. Bar numbering 기반으로, OHLCV bar 생성
tick['tick_imbalance_group'] = tick_imbalance_group
groupby = tick.groupby('tick_imbalance_group')
bars = groupby['price'].ohlc()
bars[['volume', 'value']] = groupby[['volume', 'value']].sum()
bars['t'] = groupby['t'].first()
bars.set_index('t', inplace=True)
return bars
def tick_runs_bar(tick, initial_expected_bar_size, initial_buy_prob,
lambda_bar_size=.1, lambda_buy_prob=.1):
tick = tick.sort_index(ascending=True)
tick = tick.reset_index()
_signed_tick = signed_tick(tick)
imbalance_tick_buy = _signed_tick.apply(lambda v: v if v > 0 else 0).cumsum()
imbalance_tick_sell = _signed_tick.apply(lambda v: -v if v < 0 else 0).cumsum()
group = []
expected_bar_size = initial_expected_bar_size
buy_prob = initial_buy_prob
expected_runs = expected_bar_size * max(buy_prob, 1 - buy_prob)
current_group = 1
previous_i = 0
for i in range(len(tick)):
group.append(current_group)
if max(imbalance_tick_buy[i], imbalance_tick_sell[i]) >= expected_runs:
expected_bar_size = (lambda_bar_size * (i - previous_i + 1) + (1 - lambda_bar_size) * expected_bar_size)
buy_prob = (lambda_buy_prob * imbalance_tick_buy[i] /
(i - previous_i + 1) + (1 - lambda_buy_prob) * buy_prob)
previous_i = i
imbalance_tick_buy -= imbalance_tick_buy[i]
imbalance_tick_sell -= imbalance_tick_sell[i]
current_group += 1
tick['group'] = group
groupby = tick.groupby('group')
bars = groupby['price'].ohlc()
bars[['volume', 'value']] = groupby[['volume', 'value']].sum()
bars['t'] = groupby['t'].first()
bars.set_index('t', inplace=True)
return bars
def volume_runs_bar(tick, initial_expected_bar_size, initial_buy_prob, initial_buy_volume,
initial_sell_volume, lambda_bar_size=.1, lambda_buy_prob=.1,
lambda_buy_volume=.1, lambda_sell_volume=.1):
tick = tick.sort_index(ascending=True)
tick = tick.reset_index()
_signed_tick = signed_tick(tick)
_signed_volume = _signed_tick * tick['volume']
imbalance_tick_buy = _signed_tick.apply(lambda v: v if v > 0 else 0).cumsum()
imbalance_volume_buy = _signed_volume.apply(lambda v: v if v > 0 else 0).cumsum()
imbalance_volume_sell = _signed_volume.apply(lambda v: v if -v < 0 else 0).cumsum()
group = []
expected_bar_size = initial_expected_bar_size
buy_prob = initial_buy_prob
buy_volume = initial_buy_volume
sell_volume = initial_sell_volume
expected_runs = expected_bar_size * max(buy_prob * buy_volume, (1 - buy_prob) * sell_volume)
current_group = 1
previous_i = 0
for i in range(len(tick)):
group.append(current_group)
if max(imbalance_volume_buy[i], imbalance_volume_sell[i]) >= expected_runs:
expected_bar_size = (lambda_bar_size * (i - previous_i + 1) + (1 - lambda_bar_size) * expected_bar_size)
buy_prob = (lambda_buy_prob * imbalance_tick_buy[i] /
(i - previous_i + 1) + (1 - lambda_buy_prob) * buy_prob)
buy_volume = (lambda_buy_volume * imbalance_volume_buy[i] + (1 - lambda_buy_volume) * buy_volume)
sell_volume = (lambda_sell_volume * imbalance_volume_sell[i] + (1 - lambda_sell_volume) * sell_volume)
previous_i = i
imbalance_tick_buy -= imbalance_tick_buy[i]
imbalance_volume_buy -= imbalance_volume_buy[i]
imbalance_volume_sell -= imbalance_volume_sell[i]
current_group += 1
tick['group'] = group
groupby = tick.groupby('group')
bars = groupby['price'].ohlc()
bars[['volume', 'value']] = groupby[['volume', 'value']].sum()
bars['t'] = groupby['t'].first()
bars.set_index('t', inplace=True)
return bars
def getRunBars(tick, initial_expected_bar_size, initial_buy_prob, initial_buy_volume, initial_sell_volume,
ticker = 'volume', lambda_bar_size=.1, lambda_buy_prob=.1, lambda_buy_volume=.1, lambda_sell_volume=.1):
tick = tick.sort_index(ascending=True)
tick = tick.reset_index()
_signed_tick = signed_tick(tick)
_signed_volume = _signed_tick * tick[ticker]
imbalance_tick_buy = _signed_tick.apply(lambda v: v if v > 0 else 0).cumsum()
imbalance_volume_buy = _signed_volume.apply(lambda v: v if v > 0 else 0).cumsum()
imbalance_volume_sell = _signed_volume.apply(lambda v: v if -v < 0 else 0).cumsum()
group = []
expected_bar_size = initial_expected_bar_size
buy_prob = initial_buy_prob
buy_volume = initial_buy_volume
sell_volume = initial_sell_volume
expected_runs = expected_bar_size * max(buy_prob * buy_volume, (1 - buy_prob) * sell_volume)
current_group = 1
previous_i = 0
for i in range(len(tick)):
group.append(current_group)
if max(imbalance_volume_buy[i], imbalance_volume_sell[i]) >= expected_runs:
expected_bar_size = (lambda_bar_size * (i - previous_i + 1) + (1 - lambda_bar_size) * expected_bar_size)
buy_prob = (lambda_buy_prob * imbalance_tick_buy[i] /
(i - previous_i + 1) + (1 - lambda_buy_prob) * buy_prob)
buy_volume = (lambda_buy_volume * imbalance_volume_buy[i] + (1 - lambda_buy_volume) * buy_volume)
sell_volume = (lambda_sell_volume * imbalance_volume_sell[i] + (1 - lambda_sell_volume) * sell_volume)
previous_i = i
imbalance_tick_buy -= imbalance_tick_buy[i]
imbalance_volume_buy -= imbalance_volume_buy[i]
imbalance_volume_sell -= imbalance_volume_sell[i]
current_group += 1
tick['group'] = group
groupby = tick.groupby('group')
bars = groupby['price'].ohlc()
bars[ticker] = groupby[ticker].sum()
bars['value'] = groupby['value'].sum()
#bars[['volume', 'value']] = groupby[['volume', 'value']].sum()
bars['t'] = groupby['t'].first()
bars.set_index('t', inplace=True)
return bars
@jit(nopython=True)
def getSequence(p0,p1,bs):
if numba_isclose((p1-p0),0.0,abs_tol=0.001):
return bs[-1]
else: return np.abs(p1-p0)/(p1-p0)
@jit(nopython=True)
def getImbalance(t):
"""Noted that this function return a list start from the 2nd obs"""
bs = np.zeros_like(t)
for i in np.arange(1,bs.shape[0]):
bs[i-1] = getSequence(t[i-1],t[i],bs[:i-1])
return bs[:-1] # remove the last value
def test_t_abs(absTheta, t, E_bs):
"""
Bool function to test inequality
* row is assumed to come from df.itertuples()
- absTheta: float(), row.absTheta
- t: pd.Timestamp
- E_bs: float, row.E_bs
"""
return (absTheta >= t * E_bs)
def getAggImalanceBar(df):
"""
Implements the accumulation logic
"""
start = df.index[0]
bars = []
for row in df.itertuples():
t_abs = row.absTheta
rowIdx = row.Index
E_bs = row.E_bs
t = df.loc[start:rowIdx].shape[0]
if t < 1: t = 1 # if t less than 1, set equal to 1
if test_t_abs(t_abs, t, E_bs):
bars.append((start, rowIdx, t))
start = rowIdx
return bars
def getRolledSeries(series, dictio):
gaps = rollGaps(series, dictio)
for field in ['Close', 'Volume']:
series[field] -= gaps
return series
def rollGaps(series, dictio, matchEnd=True):
# Compute gaps at each roll, between previous close and next open
rollDates = series[dictio['Instrument']].drop_duplicates(keep='first').index
gaps = series[dictio['Close']] * 0
iloc = list(series.index)
iloc = [iloc.index(i) - 1 for i in rollDates] # index of days prior to roll
gaps.loc[rollDates[1:]] = series[dictio['Open']].loc[rollDates[1:]] - series[dictio['Close']].iloc[iloc[1:]].values
gaps = gaps.cumsum()
if matchEnd:
gaps -= gaps.iloc[-1]
return gaps
def getBollingerRange(data: pd.Series, window: int = 21, width: float = 0.005):
"""
Bollinger Band를 구축하는 Parameter를 return으로 하는 함수입니다
:param data: pandas.Series 형태의 price Data를 input으로 합니다
:param window: Rolling할 기간을 지정하는 Hyper Parameter입니다
:param width:
:return:
"""
avg = data.ewm(span = window).mean()
std0 = avg * width
lower = avg - std0
upper = avg + std0
return avg, upper, lower, std0
def pcaWeights(cov, riskDist = None, risktarget = 1.0, valid = False):
"""
Rick Allocation Distribution을 따라서 Risk Target을 매치합니다
:param cov: pandas.DataFrame 형태의 Covariance Matrix를 input으로 합니다
:param riskDist: 사용자 지정 리스크 분포입니다. None이라면 코드는 모든 리스크가 최소 고유값을 갖는 주성분에 배분되는 것으로 가정합니다.
:param risktarget: riskDist에서의 비중을 조절할 수 있습니다. 기본값은 1.0입니다
:param valid: riskDist를 검증하고 싶으면 True로 지정합니다. 이 경우 결과값은 (wghts, ctr)의 형태로 출력됩니다
:return:
"""
eVal, eVec = np.linalg.eigh(cov) # Hermitian Matrix
indices = eVal.argsort()[::-1]
eVal, eVec = eVal[indices], eVec[:, indices]
if riskDist is None:
riskDist = np.zeros(cov.shape[0])
riskDist[-1] = 1.
loads = riskTarget * (riskDist / eVal) ** 0.5
wghts = np.dot(eVec, np.reshape(loads, (-1, 1)))
if vaild == True:
ctr = (loads / riskTarget) ** 2 * eVal # riskDist 검증
return (wghts, ctr)
else:
return wghts
def CusumEvents(df: pd.Series, limit: float):
"""
이벤트 기반의 표본 추출을 하는 함수입니다
:param df: pandas.Series 형태의 가격 데이터입니다
:param limit: Barrier를 지정하는 threshold입니다. numerical data이며, 높게 지정할 수록 label이 적게 추출됩니다
:return:
"""
idx, _up, _dn = [], 0, 0
diff = df.diff()
for i in range(len(diff)):
if _up + diff.iloc[i] > 0:
_up = _up + diff.iloc[i]
else:
_up = 0
if _dn + diff.iloc[i] < 0:
_dn = _dn + diff.iloc[i]
else:
_dn = 0
if _up > limit:
_up = 0;
idx.append(i)
elif _dn < - limit:
_dn = 0;
idx.append(i)
return idx
# ===============================================================================================================
# Labeling
# =================================================================================================================
def getDailyVolatility(close, span = 100):
"""
Daily Rolling Volatility를 추정하는 함수입니다
Argument
----------------------------
span(default = 100) : Rolling할 Number of Days를 지정
"""
# 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]:]))
try:
df0 = close.loc[df0.index] / close.loc[df0.values].values - 1 # daily rets
except Exception as e:
print(f'error: {e}\nplease confirm no duplicate indices')
df0 = df0.ewm(span = span).std().rename('dailyVol')
return df0
def addVerticalBarrier(tEvents, close, numDays=1):
"""
Position Holding 기간을 지정하여 Vertical Barrier를 구축합니다
Argument
----------------------------
tEvents : getTEvents 함수의 output
close : pandas Series 형태인 가격에 관한 Data
Hyper Parameter
----------------------------
numDays (default = 1) : 어느정도의 기간을 Rolling할 것인지 지정
"""
t1 = close.index.searchsorted(tEvents + pd.Timedelta(days=numDays))
t1 = t1[t1 < close.shape[0]]
t1 = (pd.Series(close.index[t1], index=tEvents[:t1.shape[0]]))
return t1
def tradableHour(i, start='09:40', end='15:50'):
"""
: param i: a datetimeIndex value
: param start: the start of the trading hour
: param end: the end of the trading hour
: return: bool, is tradable hour or not"""
time = i.strftime('%H:%M')
return (time < end and time > start)
def getTEvents(gRaw, h, symmetric=True, isReturn=False):
"""
Symmetric CUSUM Filter
Sample a bar t iff S_t >= h at which point S_t is reset
Multiple events are not triggered by gRaw hovering around a threshold level
It will require a full run of length h for gRaw to trigger an event
Two arguments:
gRaw: the raw time series we wish to filter (gRaw), e.g. return
h: threshold
Return:
pd.DatatimeIndex.append(tEvents):
"""
tEvents = []
if isReturn:
diff = gRaw
else:
diff = gRaw.diff()
if symmetric:
sPos, sNeg = 0, 0
if np.shape(h) == ():
for i in diff.index[1:]:
sPos, sNeg = max(0, sPos + diff.loc[i]), min(0, sNeg + diff.loc[i])
if sNeg < -h and tradableHour(i):
sNeg = 0;
tEvents.append(i)
elif sPos > h and tradableHour(i):
sPos = 0;
tEvents.append(i)
else:
for i in diff.index[1:]:
sPos, sNeg = max(0, sPos + diff.loc[i]), min(0, sNeg + diff.loc[i])
if sNeg < -h[i] and tradableHour(i):
sNeg = 0;
tEvents.append(i)
elif sPos > h[i] and tradableHour(i):
sPos = 0;
tEvents.append(i)
else:
sAbs = 0
if np.shape(h) == ():
for i in diff.index[1:]:
sAbs = sAbs + diff.loc[i]
if sAbs > h and tradableHour(i):
sAbs = 0;
tEvents.append(i)
else:
for i in diff.index[1:]:
sAbs = sAbs + diff.loc[i]
if sAbs > h[i] and tradableHour(i):
sAbs = 0;
tEvents.append(i)
return pd.DatetimeIndex(tEvents)
def getTripleBarrier(close, events, ptSl, molecule):
"""
Triple Barrier Method를 구현하는 함수입니다
Horizonal Barrier, Vertical Barrier 중 어느 하나라도 Touch를 하면 Labeling을 진행합니다
Argument
----------------------------
close : Price 정보가 담겨 있는 pandas.Series 계열의 데이터를 input으로 넣습니다
events : pandas.DataFrame으로서 다음의 열을 가집니다
- t1 : Vertical Barrier의 Time Stamp 값입니다. 이 값이 np.nan이라면 Vertical Barrier가 없습니다
- trgt : Horizonal Barrier의 단위 너비입니다
ptSl : 음이 아는 두 실수값의 리스트입니다
- ptSl[0] : trgt에 곱해서 Upper Barrier 너비를 설정하는 인수입니다. 값이 0이면 Upper Barrier가 존재하지 않습니다
- ptSl[1] : trgt에 곱해서 Lower Barrier 너비를 설정하는 인수입니다. 값이 0이면 Lower Barrier가 존재하지 않습니다
molecule : Single Thread에 의해 처리되는 Event Index의 부분 집합을 가진 리스트입니다
"""
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] # 가격 경로
df0 = (df0 / close[loc] - 1) * events_.at[loc, 'side'] # 수익률 경로
out.loc[loc, 'sl'] = df0[df0 < sl[loc]].index.min() # 가장 빠른 손절 시점
out.loc[loc, 'pt'] = df0[df0 > pt[loc]].index.min() # 가장 빠른 이익 실현 시점
return out
def _apply_df(args):
df, func, kwargs = args
return df.apply(func, **kwargs)
def getEvents(close, tEvents, ptSl, trgt, minRet, numThreads, t1=False, side=None):
"""
베팅의 방향과 크기를 파악할 수 있는 함수입니다
Argument
----------------------------
close : Price 정보가 담겨 있는 pandas.Series 계열의 데이터를 input으로 넣습니다
tEvents : 각 Triple Barrier Seed가 될 Time Stamp값을 가진 Pandas TimeIndex입니다
ptSl : 음이 아는 두 실수값의 리스트로, 두 Barrier의 너비를 설정합니다
trgt : 수익률의 절대값으로 표현한 목표 pandas.Series 객체의 데이터를 input으로 합니다향
minRet : Triple Barrier 검색을 진행할 때 필요한 최소 목표 수익률입니다
numThreads : 함수에서 현재 동시에 사용하고 있는 Thread의 수입니다
t1(default = False) : Vertical Barrier의 Time Stamp를 가진 pandas.Series 객체의 데이터를 input으로 합니다
side(default = None) : side 값을 input으로 넣습니다
"""
# 1) 목표 구하기
for i in tEvents:
if i not in trgt.index:
trgt[str(i)] = np.NaN
trgt = trgt.loc[tEvents]
trgt = trgt[trgt > minRet] # minRet
# 2) t1 구하기 (최대 보유 기간)
if t1 is False:
t1 = pd.Series(pd.NaT, index=tEvents)
# 3) t1에 손절을 적용해 이벤트 객체를 형성
if side is None:
side_, ptSl_ = pd.Series(1., index=trgt.index), [ptSl[0], ptSl[0]]
else:
side_, ptSl_ = side.loc[side.index & trgt.index], ptSl[:2]
events = pd.concat({'t1': t1, 'trgt': trgt, 'side': side_}, axis = 1).dropna(subset = ['trgt'])
df0 = mpPandasObj(func = getTripleBarrier, pdObj=('molecule', events.index),
numThreads = numThreads, close = close, events = events, ptSl = np.array(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):
"""
이벤트를 감지해 출력하는 함수입니다. 가능하다면 베팅 사이드에 대한 정보도 포함합니다.
Argument
----------------------------
events : 감지된 Events가 존재하는 pandas DataFrame형태의 input data입니다. 아래와 같은 column을 가집니다
- t1 : event의 마지막 시간을 의미합니다
- trgt : event의 Target을 의미합니다
- side : Position의 방향을 의미합니다 (상승, 하락)
- Case 1 ('side'가 이벤트에 없음) : bin in (-1, 1) 가격 변화에 의한 레이블
- Case 2 ('side'가 이벤트에 있음) : bin in (0, 1) 손익(pnl)에 의한 레이블 (meta labeling)
"""
# 1) 가격과 이벤트를 일치
events_ = events.dropna(subset=['t1'])
px = events_.index.union(events_['t1'].values).drop_duplicates()
px = close.reindex(px, method='bfill')
# 2) OUT 객체 생성
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-labeling
out['bin'] = np.sign(out['ret'])
if 'side' in events_: out.loc[out['ret'] <= 0, 'bin'] = 0 # meta-labeling
return out
def dropLabels(events, minPct=0.05):
# 예제가 부족할 경우 가중치를 적용해 레이블을 제거한다.
while True:
df0 = events['bin'].value_counts(normalize=True)
if df0.min() > minPct or df0.shape[0] < 3:
break
print('dropped label', df0.idxmin(), df0.min())
events = events[events['bin'] != df0.idxmin()]
return events
def getBinsNew(events, close, t1=None):
'''
Compute event's outcome (including side information, if provided).
events is a DataFrame where:
-events.index is event's starttime
-events['t1'] is event's endtime
-events['trgt'] is event's target
-events['side'] (optional) implies the algo's position side
-t1 is original vertical barrier series
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-labeling)
'''
# 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-labeling
out['bin'] = np.sign(out['ret'])
if 'side' not in events_:
# only applies when not meta-labeling
# to update bin to 0 when vertical barrier is touched, we need the original
# vertical barrier series since the events['t1'] is the time of first
# touch of any barrier and not the vertical barrier specifically.
# The index of the intersection of the vertical barrier values and the
# events['t1'] values indicate which bin labels needs to be turned to 0
vtouch_first_idx = events[events['t1'].isin(t1.values)].index
out.loc[vtouch_first_idx, 'bin'] = 0.
if 'side' in events_: out.loc[out['ret'] <= 0, 'bin'] = 0 # meta-labeling
return out
def get_up_cross(df):
"""
이익 실현 구간을 지정하는 함수입니다
"""
crit1 = df.fast.shift(1) < df.slow.shift(1)
crit2 = df.fast > df.slow
return df.fast[(crit1) & (crit2)]
def get_down_cross(df):
"""
손실 한도 구간을 지정하는 함수입니다
"""
crit1 = df.fast.shift(1) > df.slow.shift(1)
crit2 = df.fast < df.slow
return df.fast[(crit1) & (crit2)]
def getUpCross(df, col):
# col is price column
crit1 = df[col].shift(1) < df.upper.shift(1)
crit2 = df[col] > df.upper
return df[col][(crit1) & (crit2)]
def getDownCross(df, col):
# col is price column
crit1 = df[col].shift(1) > df.lower.shift(1)
crit2 = df[col] < df.lower
return df[col][(crit1) & (crit2)]
# ===============================================================================================================
# Sample Weights
# =================================================================================================================
def getConcurrentBar(closeIdx, t1, molecule):
"""
Bar별로 공존하는 Event의 개수를 계산하여 Label의 고유도를 계산하는 함수입니다
:param closeIdx : 가격 계열의 data를 Value로 가지는 Index를 input으로 합니다
:param t1 : pandas.Series형태의 데이터로, Vertical Barrier를 형성하는 timestamp 정보를 input으로 합니다
:param molecule : 가중값이 계산될 이벤트의 시간 정보를 input으로 합니다. t1[molecule].max()이전에 발생하는 모든 이벤트는 개수에 영향을 미치게 됩니다
molecule[0]은 가중값이 계산될 첫 이벤트 시간입니다
molecule[-1]은 가중값이 계산될 마지막 이벤트 시간입니다
:return count : pandas.Series 형태로 Concurrent Bar의 개수가 Bar마다 출력되어 나옵니다
"""
# 1) [molecule[0], molecule[-1]]에서 Event를 탐색합니다
# fill the unclosed events with the last available (index) date
t1 = t1.fillna(closeIdx[-1]) # 드러난 이벤트들은 다른 가중값에 영향을 미쳐야 합니다
t1 = t1[t1 >= molecule[0]] # molecule[0]의 마지막이나 이후에 발생하는 이벤트입니다
# t1[molecule].max() 이전이나 시작 시에 발생하는 이벤트입니다
t1 = t1.loc[: t1[molecule].max()]
# 2) 바에서 발생하는 이벤트의 개수를 알아보는 과정입니다
# find the indices begining start date ([t1.index[0]) and the furthest stop date (t1.max())
iloc = closeIdx.searchsorted(np.array([t1.index[0], t1.max()]))
# form a 0-array, index: from the begining start date to the furthest stop date
count = pd.Series(0, index=closeIdx[iloc[0]: iloc[1] + 1])
# for each signal t1 (index: eventStart, value: eventEnd)
for tIn, tOut in t1.iteritems():
# add 1 if and only if [t_(i,0), t_(i.1)] overlaps with [t-1,t]
count.loc[tIn: tOut] += 1 # every timestamp between tIn and tOut
# compute the number of labels concurrents at t
return count.loc[molecule[0]: t1[molecule].max()] # only return the timespan of the molecule
def getAvgLabelUniq(t1, numCoEvents, molecule):
"""
:param t1: pd series, timestamps of the vertical barriers. (index: eventStart, value: eventEnd).
:param numCoEvent:
:param molecule: the date of the event on which the weight will be computed
+ molecule[0] is the date of the first event on which the weight will be computed
+ molecule[-1] is the date of the last event on which the weight will be computed
:return
wght: pd.Series, the sample weight of each (volume) bar
"""
# derive average uniqueness over the event's lifespan
wght = pd.Series(index=molecule)
# for each events
for tIn, tOut in t1.loc[wght.index].iteritems():
# tIn, starts of the events, tOut, ends of the events
# the more the coEvents, the lower the weights
wght.loc[tIn] = (1. / numCoEvents.loc[tIn: tOut]).mean()
return wght
def mpSampleWeights(close, events, numThreads):
"""
:param close: A pd series of prices
:param events: A Pd dataframe
- t1: the timestamp of vertical barrier. if the value is np.nan, no vertical barrier
- trgr: the unit width of the horizontal barriers, e.g. standard deviation
:param numThreads: constant, The no. of threads concurrently used by the function
:return
wght: pd.Series, the sample weight of each (volume) bar
"""
out = events[['t1']].copy(deep=True)
out['t1'] = out['t1'].fillna(close.index[-1])
events['t1'] = events['t1'].fillna(close.index[-1])
numCoEvents = mpPandasObj(getConcurrentBar, ('molecule', events.index), numThreads, closeIdx=close.index,
t1=out['t1'])
numCoEvents = numCoEvents.loc[~numCoEvents.index.duplicated(keep='last')]
numCoEvents = numCoEvents.reindex(close.index).fillna(0)
out['tW'] = mpPandasObj(getAvgLabelUniq, ('molecule', events.index), numThreads, t1=out['t1'],
numCoEvents = numCoEvents)
return out
def getBollingerBand(price, window = None, width = None, numsd = None):
"""
Bollinger Band를 구축해주는 함수입니다
:param price : pandas.Series 형태의 가격을 input으로 합니다
:param window : rolling할 days의 값을 numerical input data로 지정합니다(default = 0)
:param width : Bollinger Band 구축 시 상한 하한을 지정해주는 parameter입니다(default = 0)
:param numsd : Bollinger Band 구축 시 상한 하한을 변동성으로 지정해주는 parameter입니다(default = 0)
"""
ave = price.rolling(window).mean()
sd = price.rolling(window).std(ddof=0)
if width:
upband = ave * (1 + width)
dnband = ave * (1 - width)
return price, np.round(ave, 3), np.round(upband, 3), np.round(dnband, 3)
if numsd:
upband = ave + (sd * numsd)
dnband = ave - (sd * numsd)
return price, np.round(ave, 3), np.round(upband, 3), np.round(dnband, 3)
def getSampleWeights(close, events, numThreads):
"""
:param close: A pd series of prices
:param events: A Pd dataframe
- t1: the timestamp of vertical barrier. if the value is np.nan, no vertical barrier
- trgr: the unit width of the horizontal barriers, e.g. standard deviation
:param numThreads: constant, The no. of threads concurrently used by the function
:return wght: pd.Series, the sample weight of each (volume) bar
"""
out = events[['t1']].copy(deep=True)
out['t1'] = out['t1'].fillna(close.index[-1])
events['t1'] = events['t1'].fillna(close.index[-1])
numCoEvents = mpPandasObj(getConcurrentBar, ('molecule', events.index), numThreads, closeIdx=close.index, t1=out['t1'])
numCoEvents = numCoEvents.loc[~numCoEvents.index.duplicated(keep='last')]
numCoEvents = numCoEvents.reindex(close.index).fillna(0)
out['tW'] = mpPandasObj(mpSampleWeights, ('molecule', events.index), numThreads, t1=out['t1'], numCoEvents=numCoEvents)
return out
def getIndMatrix(barIx, t1):
"""
지표 행렬을 구축하는 함수입니다
:param barIx: Bar의 index를 input으로 합니다
:param t1: pandas.Series 형태의 Vertical Barrier의 timestamps를 input으로 합니다 (index: eventStart, value: eventEnd)
:return indM: binary matrix, 각 관측치의 Label에 price Bar가 미치는 영향을 보여줍니다
"""
indM = pd.DataFrame(0, index = barIx, columns=range(t1.shape[0]))
for i, (t0, t1) in enumerate(t1.iteritems()): # signal = obs
indM.loc[t0: t1, i] = 1. # each obs each column, you can see how many bars are related to an obs/
return indM
def getAvgUniqueness(indM):
"""
각 측성 관측값의 고유도(Uniuqeness) 평균을 반환합니다
:param indM: getIndMatrix에 의해 구성된 Indicator Matrix를 input으로 합니다
:return avgU: average uniqueness of each observed feature
"""
# 지표 행렬로부터의 평균 고유도
c = indM.sum(axis=1) # concurrency, how many obs share the same bar
u = indM.div(c, axis=0) # uniqueness, the more obs share the same bar, the less important the bar is
avgU = u[u > 0].mean() # average uniquenessn
return avgU
def seqBootstrap(indM, sLength=None):
"""
Give the index of the features sampled by the sequential bootstrap
:param indM: binary matrix, indicate what (price) bars influence the label for each observation
:param sLength: optional, sample length, default: as many draws as rows in indM
"""
# Generate a sample via sequential bootstrap
if sLength is None: # default
sLength = indM.shape[1] # sample length = # of rows in indM
# Create an empty list to store the sequence of the draws
phi = []
while len(phi) < sLength:
avgU = pd.Series() # store the average uniqueness of the draw
for i in indM: # for every obs
indM_ = indM[phi + [i]] # add the obs to the existing bootstrapped sample
# get the average uniqueness of the draw after adding to the new phi
avgU.loc[i] = getAvgUniqueness(indM_).iloc[
-1] # only the last is the obs concerned, others are not important
prob = avgU / avgU.sum() # cal prob <- normalise the average uniqueness
phi += [np.random.choice(indM.columns, p=prob)] # add a random sample from indM.columns with prob. = prob
return phi
def main():
# t0: t1.index; t1: t1.values
t1 = pd.Series([2, 3, 5], index=[0, 2, 4])
# index of bars
barIx = range(t1.max() + 1)
# get indicator matrix
indM = getIndMatrix(barIx, t1)