-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_ts_function.py
1227 lines (939 loc) · 42.7 KB
/
add_ts_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
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 copy
from copy import deepcopy
import numpy as np
import pandas as pd
import numba as nb
from numba import jit, prange
import talib as ta
from functions import _Function
def rolling_window(a, window, axis=0):
"""
返回2D array的滑窗array的array
"""
if axis == 0:
shape = (a.shape[0] - window + 1, window, a.shape[-1])
strides = (a.strides[0],) + a.strides
a_rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
elif axis == 1:
shape = (a.shape[-1] - window + 1,) + (a.shape[0], window)
strides = (a.strides[-1],) + a.strides
a_rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
return a_rolling
@jit(nopython=True,nogil=True,parallel=True)
def calc_zscore_2d(series,rolling_window=180):
res=series.copy()#初始填充原始值,不是nan
symbol_num=len(series[0,:])
for i in prange(rolling_window,len(series)):
temp=series[i+1-rolling_window:i+1,:]
# s_mean=np.nanmean(temp,axis=0)
# s_std=np.nanstd(temp,axis=0)
for j in prange(symbol_num):
s_mean=np.nanmean(temp[:,j])
s_std=np.nanstd(temp[:,j])
res[i,j] = (series[i,j]-s_mean)/max(s_std,10e-9)
return res
def rolling_nanmean(A, window=None):
ret = pd.DataFrame(A)
factor_table = copy.deepcopy(ret)
for col in ret.columns:
current_data = copy.deepcopy(ret[col])
current_data.dropna(inplace=True)
current_factor = current_data.rolling(window).mean().values
number = 0
for index, data in enumerate(ret[col]):
if ret[col][index] != ret[col][index]:
factor_table[col][index] = np.nan
else:
factor_table[col][index] = current_factor[number]
number += 1
factor = factor_table.to_numpy(dtype=np.double)
return factor
def rolling_max(A, window=None):
# ret = np.full(A.shape, np.nan)
# A_rolling = rolling_window(A, window=window, axis=0)
# Atmp = np.stack(map(lambda x:np.max(x, axis=0), A_rolling))
# ret[window-1:,:] = Atmp
ret = pd.DataFrame(A)
factor = ret.rolling(window).max()
factor = factor.to_numpy(dtype=np.double)
return factor
def rolling_nanstd(A, window=None):
ret = pd.DataFrame(A)
factor_table = copy.deepcopy(ret)
for col in ret.columns:
current_data = copy.deepcopy(ret[col])
current_data.dropna(inplace=True)
current_factor = current_data.rolling(window).std().values
number = 0
for index, data in enumerate(ret[col]):
if ret[col][index] != ret[col][index]:
factor_table[col][index] = np.nan
else:
factor_table[col][index] = current_factor[number]
number += 1
factor = factor_table.to_numpy(dtype=np.double)
return factor
"""
def _ts_corr(X: pd.DataFrame, t):
return (pd.Series(X.iloc[:, 0]).rolling(t).corr(pd.Series(X.iloc[:, 1]))).to_numpy(dtype=np.double)
"""
def _ts_delay(x1, t):
return pd.DataFrame(x1).shift(t).values
def _ts_delta(x1, t):
return x1 - _ts_delay(x1, t)
def _sigmoid(x1):
"""Special case of logistic function to transform to probabilities."""
with np.errstate(over='ignore', under='ignore'):
return 1 / (1 + np.exp(-x1))
def _ts_std(x1, t):
with np.errstate(over='ignore', under='ignore'):
return rolling_nanstd(x1, t)
def _ts_mean(x1, t):
with np.errstate(over='ignore', under='ignore'):
return rolling_nanmean(x1, t)
def _ts_max(x1, t):
with np.errstate(over='ignore', under='ignore'):
return rolling_max(x1, t)
def _ts_normalize_180(x1):
with np.errstate(over='ignore', under='ignore'):
return calc_zscore_2d(x1, 180)
"""---------------------------------------------Ta-lib Integration---------------------------------------------"""
"""------Overlap Studies Functions------"""
def _BBANDS(x1: np.ndarray, t) -> np.ndarray:
"""
Calculate the Bollinger Bands for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
- t: Time period for calculating Bollinger Bands.
Returns:
- 2D Numpy array with the upper Bollinger Band values. (Can be adjusted for middle and lower bands)
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
upper, middle, lower = ta.BBANDS(x1[:, col], timeperiod=t)
factor_table[:, col] = (upper - middle) / (middle - lower)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_bbands = _Function(function=_BBANDS, name='ts_bbands', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _DEMA(x1, t):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.DEMA(x1[:, col], t)
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_dema = _Function(function=_DEMA, name='ts_dema', arity=1, isRandom=(True, [7, 14, 21, 28]))
def _HT_TRENDMODE(x1: np.ndarray) -> np.ndarray:
"""
Calculate the Hilbert Transform - Trend vs Cycle Mode for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Trend vs Cycle Mode values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.HT_TRENDMODE(x1[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ht_trendmode = _Function(function=_HT_TRENDMODE, name='ts_ht_trendmode', arity=0, isRandom=(False, []), need_param=['close'])
def _KAMA(x1, t):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.KAMA(x1[:, col], t)
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_kama = _Function(function=_KAMA, name='ts_kama', arity=1, isRandom=(True, [7, 14, 21, 28]))
def _MIDPOINT(x1, t):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MIDPOINT(x1[:, col], t)
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_midpoint = _Function(function=_MIDPOINT, name='ts_midpoint', arity=1, isRandom=(True, [7, 14, 21, 28]))
def _MIDPRICE(x1: np.ndarray, x2: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MIDPRICE(x1[:, col], x2[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_midprice = _Function(function=_MIDPRICE, name='ts_midprice', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low'])
def _SAR(x1: np.ndarray, x2: np.ndarray, acceleration=0.02, maximum=0.2) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.SAR(x1[:, col], x2[:, col], acceleration=acceleration, maximum=maximum)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_sar = _Function(function=_SAR, name='ts_sar', arity=0, isRandom=(False, []), need_param=['high', 'low'])
def _SMA(x1: np.ndarray, t) -> np.ndarray:
"""
Calculate the SMA for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
- t: Period for the moving average.
Returns:
- 2D Numpy array with the SMA values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.SMA(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_sma = _Function(function=_SMA, name='ts_sma', arity=1, isRandom=(True, [7, 14, 21, 28]))
def _TEMA(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.TEMA(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_tema = _Function(function=_TEMA, name='ts_tema', arity=1, isRandom=(True, [7, 14, 21, 28]))
def _TRIMA(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.TRIMA(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_trima = _Function(function=_TRIMA, name='ts_trima', arity=1, isRandom=(True, [7, 14, 21, 28]))
"""-------Momentum Indicator Functions-------"""
def _ADX(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t=14) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ADX(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_adx = _Function(function=_ADX, name='ts_adx', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _ADXR(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ADXR(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_adxr = _Function(function=_ADXR, name='ts_adxr', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _APO(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.APO(x1[:, col], fastperiod=t, slowperiod=2*(t+1))
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_apo = _Function(function=_APO, name='ts_apo', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _STOCHRSI(x1: np.ndarray, t, fastk_period=5, fastd_period=3, fastd_matype=0) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
fastk, fastd = ta.STOCHRSI(x1[:, col], timeperiod=t, fastk_period=fastk_period, fastd_period=fastd_period, fastd_matype=fastd_matype)
factor_table[:, col] = fastk/fastd # You can also choose to return fastd or both
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_stochrsi = _Function(function=_STOCHRSI, name='ts_stochrsi', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _AROONOSC(x1: np.ndarray, x2: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.AROONOSC(x1[:, col], x2[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_aroonosc = _Function(function=_AROONOSC, name='ts_aroonosc', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low'])
def _BOP(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, x4: np.ndarray) -> np.ndarray:
"""
Calculate the Balance of Power (BOP) for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents open prices).
- x2: 2D Numpy array (represents high prices).
- x3: 2D Numpy array (represents low prices).
- x4: 2D Numpy array (represents close prices).
Returns:
- 2D Numpy array with the BOP values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.BOP(x1[:, col], x2[:, col], x3[:, col], x4[:, col])
return factor_table
except Exception as e:
# Ideally, you'd log the exception here for debugging
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
# Assuming the `_Function` class/factory is defined somewhere:
ts_bop = _Function(function=_BOP, name='ts_bop', arity=0, isRandom=(False, []), need_param=['open', 'high', 'low', 'close'])
def _CCI(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t: int = 14) -> np.ndarray:
"""
Calculate the CCI for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
- x3: 2D Numpy array (represents close prices).
- t: Time period for calculating CCI.
Returns:
- 2D Numpy array with the CCI values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.CCI(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_cci = _Function(function=_CCI, name='ts_cci', arity=0, isRandom=(True, [7, 14, 21]), need_param=['high', 'low', 'close'])
def _CMO(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.CMO(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_cmo = _Function(function=_CMO, name='ts_cmo', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _DX(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.DX(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_dx = _Function(function=_DX, name='ts_dx', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _MACD(x1: np.ndarray, t) -> np.ndarray:
"""
Calculate the MACD for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the MACD values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
macd_line, signal_line, hist = ta.MACD(x1[:, col], fastperiod=t, slowperiod=2*(t+1), signalperiod=t-4)
factor_table[:, col] = macd_line
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_macd = _Function(function=_MACD, name='ts_macd', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _MFI(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, x4: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MFI(x1[:, col], x2[:, col], x3[:, col], x4[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_mfi = _Function(function=_MFI, name='ts_mfi', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close', 'volume'])
def _MINUS_DI(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MINUS_DI(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_minus_di = _Function(function=_MINUS_DI, name='ts_minus_di', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _MINUS_DM(x1: np.ndarray, x2: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MINUS_DM(x1[:, col], x2[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_minus_dm = _Function(function=_MINUS_DM, name='ts_minus_dm', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low'])
def _MOM(x1: np.ndarray, t) -> np.ndarray:
"""
Calculate the Momentum for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
- t: Time period for calculating Momentum.
Returns:
- 2D Numpy array with the Momentum values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MOM(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_mom = _Function(function=_MOM, name='ts_mom', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _PLUS_DI(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.PLUS_DI(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_plus_di = _Function(function=_PLUS_DI, name='ts_plus_di', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _PLUS_DM(x1: np.ndarray, x2: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.PLUS_DM(x1[:, col], x2[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_plus_dm = _Function(function=_PLUS_DM, name='ts_plus_dm', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low'])
def _PPO(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.PPO(x1[:, col], fastperiod=t, slowperiod=2*(t+1))
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ppo = _Function(function=_PPO, name='ts_ppo', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _ROC(x1: np.ndarray, t: int = 10) -> np.ndarray:
"""
Calculate the Rate of Change for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
- t: Time period for calculating ROC.
Returns:
- 2D Numpy array with the ROC values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ROC(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_roc = _Function(function=_ROC, name='ts_roc', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _RSI(x1: np.ndarray, t) -> np.ndarray:
"""
Calculate the RSI for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the RSI values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.RSI(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_rsi = _Function(function=_RSI, name='ts_rsi', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _STOCH(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray) -> np.ndarray:
"""
Calculate the Stochastic Oscillator for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
- x3: 2D Numpy array (represents close prices).
Returns:
- 2D Numpy array with the Stochastic Oscillator K values. (Can be adjusted for D values)
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
slowk, slowd = ta.STOCH(x1[:, col], x2[:, col], x3[:, col])
factor_table[:, col] = slowk / slowd
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_stoch = _Function(function=_STOCH, name='ts_stoch', arity=0, isRandom=(False, []), need_param=['high', 'low', 'close'])
def _TRIX(x1: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.TRIX(x1[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_trix = _Function(function=_TRIX, name='ts_trix', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['close'])
def _ULTOSC(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ULTOSC(x1[:, col], x2[:, col], x3[:, col], timeperiod1=t, timeperiod2=2*t, timeperiod3=4*t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ultosc = _Function(function=_ULTOSC, name='ts_ultosc', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _WILLR(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, t: int = 14) -> np.ndarray:
"""
Calculate the Williams %R for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
- x3: 2D Numpy array (represents close prices).
- t: Time period for calculating Williams %R.
Returns:
- 2D Numpy array with the Williams %R values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.WILLR(x1[:, col], x2[:, col], x3[:, col], timeperiod=t)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_willr = _Function(function=_WILLR, name='ts_willr', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
"""------Volume Indicator Functions------"""
def _AD(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, x4: np.ndarray) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.AD(x1[:, col], x2[:, col], x3[:, col], x4[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ad = _Function(function=_AD, name='ts_ad', arity=0, need_param=['high', 'low', 'close', 'volume'])
def _ADOSC(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, x4: np.ndarray, fastperiod=3, slowperiod=10) -> np.ndarray:
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ADOSC(x1[:, col], x2[:, col], x3[:, col], x4[:, col], fastperiod=fastperiod, slowperiod=slowperiod)
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_adosc = _Function(function=_ADOSC, name='ts_adosc', arity=0, need_param=['high', 'low', 'close', 'volume'])
def _OBV(x1: np.ndarray, x2: np.ndarray) -> np.ndarray:
"""
Calculate the OBV for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
- x2: 2D Numpy array (represents volume).
Returns:
- 2D Numpy array with the OBV values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.OBV(x1[:, col], x2[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_obv = _Function(function=_OBV, name='ts_obv', arity=0, isRandom=(False, []), need_param=['close', 'volume'])
"""------Volatility Indicator Functions------"""
def _NATR(x1, x2, x3, t):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.NATR(x1[:, col], x2[:, col], x3[:, col], t)
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_natr = _Function(function=_NATR, name='ts_natr', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _ATR(x1, x2, x3, t):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.ATR(x1[:, col], x2[:, col], x3[:, col], t)
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_atr = _Function(function=_ATR, name='ts_atr', arity=0, isRandom=(True, [7, 14, 21, 28]), need_param=['high', 'low', 'close'])
def _TRANGE(x1, x2, x3):
try:
with np.errstate(divide='ignore', invalid='ignore'):
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.TRANGE(x1[:, col], x2[:, col], x3[:, col])
return factor_table
except:
return np.full(x1.shape, np.nan)
ts_trange = _Function(function=_TRANGE, name='ts_trange', arity=0, need_param=['high', 'low', 'close'])
"""-----Price Transform Functions-----"""
def _AVGPRICE(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray, x4: np.ndarray) -> np.ndarray:
"""
Calculate the Average Price for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents opening prices).
- x2: 2D Numpy array (represents high prices).
- x3: 2D Numpy array (represents low prices).
- x4: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Average Price values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.AVGPRICE(x1[:, col], x2[:, col], x3[:, col], x4[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_avgprice = _Function(function=_AVGPRICE, name='ts_avgprice', arity=0, isRandom=(False, []), need_param=['open', 'high', 'low', 'close'])
def _MEDPRICE(x1: np.ndarray, x2: np.ndarray) -> np.ndarray:
"""
Calculate the Median Price for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
Returns:
- 2D Numpy array with the Median Price values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.MEDPRICE(x1[:, col], x2[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_medprice = _Function(function=_MEDPRICE, name='ts_medprice', arity=0, isRandom=(False, []), need_param=['high', 'low'])
def _TYPPRICE(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray) -> np.ndarray:
"""
Calculate the Typical Price for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
- x3: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Typical Price values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.TYPPRICE(x1[:, col], x2[:, col], x3[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_typprice = _Function(function=_TYPPRICE, name='ts_typprice', arity=0, isRandom=(False, []), need_param=['high', 'low', 'close'])
def _WCLPRICE(x1: np.ndarray, x2: np.ndarray, x3: np.ndarray) -> np.ndarray:
"""
Calculate the Weighted Close Price for each column of the input 2D arrays.
Parameters:
- x1: 2D Numpy array (represents high prices).
- x2: 2D Numpy array (represents low prices).
- x3: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Weighted Close Price values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.WCLPRICE(x1[:, col], x2[:, col], x3[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_wclprice = _Function(function=_WCLPRICE, name='ts_wclprice', arity=0, isRandom=(False, []), need_param=['high', 'low', 'close'])
"""------Cycle indicators-------"""
def _HT_DCPERIOD(x1: np.ndarray) -> np.ndarray:
"""
Calculate the Hilbert Transform - Dominant Cycle Period for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Dominant Cycle Period values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.HT_DCPERIOD(x1[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ht_dcperiod = _Function(function=_HT_DCPERIOD, name='ts_ht_dcperiod', arity=0, isRandom=(False, []), need_param=['close'])
def _HT_DCPHASE(x1: np.ndarray) -> np.ndarray:
"""
Calculate the Hilbert Transform - Dominant Cycle Phase for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Dominant Cycle Phase values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
factor_table[:, col] = ta.HT_DCPHASE(x1[:, col])
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ht_dcphase = _Function(function=_HT_DCPHASE, name='ts_ht_dcphase', arity=0, isRandom=(False, []), need_param=['close'])
def _HT_PHASOR(x1: np.ndarray) -> np.ndarray:
"""
Calculate the Hilbert Transform - Phasor Components for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the Phasor Components values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
inPhase, quadrature = ta.HT_PHASOR(x1[:, col])
factor_table[:, col] = inPhase # Using inPhase component. Adjust if needed.
return factor_table
except Exception as e:
print(f"An error occurred: {e}")
return np.full(x1.shape, np.nan)
ts_ht_phasor = _Function(function=_HT_PHASOR, name='ts_ht_phasor', arity=0, isRandom=(False, []), need_param=['close'])
def _HT_SINE(x1: np.ndarray) -> np.ndarray:
"""
Calculate the Hilbert Transform - SineWave for each column of the input 2D array.
Parameters:
- x1: 2D Numpy array (represents closing prices).
Returns:
- 2D Numpy array with the SineWave values.
"""
try:
factor_table = copy.deepcopy(x1)
for col in range(x1.shape[1]):
sine, leadsine = ta.HT_SINE(x1[:, col])
factor_table[:, col] = sine # Using sine component. Adjust if needed.
return factor_table
except Exception as e:
print(f"An error occurred: {e}")