-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_features.py
More file actions
1030 lines (883 loc) · 30.8 KB
/
Copy pathmodel_features.py
File metadata and controls
1030 lines (883 loc) · 30.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
from typing import Literal
import warnings
import logging
import time
import numpy as np
import pandas as pd
import tradingview_indicators as ta
from utils import DynamicTimeWarping
def feature_binning(
feature: pd.Series,
test_index: str | int,
bins: int = 10,
) -> pd.Series:
"""
Perform feature binning using quantiles.
Parameters:
-----------
feature : pd.Series
The input feature series to be binned.
test_index : str or int
The index or label up to which the training data is considered.
bins : int, optional
The number of bins to use for binning the feature.
(default: 10)
Returns:
--------
pd.Series
The binned feature series.
Raises:
-------
ValueError
If the feature contains NaN or infinite values.
"""
has_inf = np.sum(np.isinf(feature.dropna().to_numpy())) >= 1
has_na = np.sum(np.isnan(feature.dropna().to_numpy())) >= 1
if has_inf or has_na:
raise ValueError(
"Feature contains NaN or infinite values. "
"Please clean the data before binning."
)
train_series = (
feature.iloc[:test_index].copy()
if isinstance(test_index, int)
else feature.loc[:test_index].copy()
)
intervals = (
pd.qcut(train_series, bins, duplicates='drop')
.value_counts()
.index
.to_list()
)
lows = pd.Series([interval.left for interval in intervals])
highs = pd.Series([interval.right for interval in intervals])
lows.iloc[0] = -np.inf
highs.iloc[-1] = np.inf
intervals_range = (
pd.concat([lows.rename("lowest"), highs.rename("highest")], axis=1)
.sort_values("highest")
.reset_index(drop=True)
)
return feature.dropna().apply(
lambda x: intervals_range[
(x >= intervals_range["lowest"])
& (x <= intervals_range["highest"])
].index[0]
)
class ModelFeatures:
"""
Class for creating and manipulating features for a machine learning
model.
Parameters:
-----------
dataset : pd.DataFrame
The dataset containing the features.
test_index : int
The index or label up to which the training data is considered.
bins : int, optional
The number of bins to use for binning the features.
(default: 10)
Attributes:
-----------
dataset : pd.DataFrame
The dataset containing the features.
test_index : int
The index or label up to which the training data is considered.
bins : int
The number of bins to use for binning the features.
logger : logging.Logger
The logger for the ModelFeatures class.
"""
def __init__(
self,
dataset: pd.DataFrame,
test_index: int,
bins: int = 10,
verbose: bool = False,
normalize: bool = False,
):
self.dataset = dataset.copy()
self.test_index = test_index
self.bins = bins
self.normalize = normalize
self.logger = logging.getLogger("Model_Features")
formatter = logging.Formatter(
"%(levelname)s %(asctime)s: %(message)s", datefmt="%H:%M:%S"
)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
if self.logger.hasHandlers():
self.logger.handlers.clear()
self.logger.addHandler(handler)
self.logger.propagate = False
if verbose:
self.logger.setLevel(logging.INFO)
else:
self.logger.setLevel(logging.WARNING)
def set_normalize(self, normalize: bool):
"""
Set value of normalize attribute.
Parameters
----------
normalize : bool
The value to set the normalize attribute to.
"""
self.normalize: bool = normalize
return self
def set_bins(self, bins: int):
"""
Set the number of bins to use for binning the features.
Parameters
----------
bins : int
The number of bins to use for binning the features.
"""
self.bins: int = bins
return self
def create_rsi_feature(
self,
source: pd.Series,
length: int,
ma_method: Literal["sma", "ema", "dema", "tema", "rma"] = "sma",
):
"""
Create the RSI (Relative Strength Index) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating RSI.
length : int
The length of the RSI calculation.
Returns:
--------
pd.DataFrame
The dataset with the RSI feature added.
"""
self.logger.info("Calculating RSI...")
start = time.perf_counter()
self.dataset["RSI"] = ta.RSI(source, length, ma_method)
if self.normalize:
self.dataset["RSI"] = self.dataset["RSI"].rolling(2).std().diff()
self.dataset.loc[:, "RSI_feat"] = feature_binning(
self.dataset["RSI"],
self.test_index,
self.bins,
)
self.logger.info(
"RSI calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_slow_stoch_feature(
self,
source_column: str,
k_length: int = 14,
k_smoothing: int = 1,
d_smoothing: int = 3,
ma_method: Literal["sma", "ema", "dema", "tema", "rma"] = "sma",
):
"""
Create the slow stochastic feature.
Parameters:
-----------
source_column : str
The column name of the source data.
k_length : int, optional
The length of the %K calculation. (default: 14)
k_smoothing : int, optional
The smoothing factor for %K. (default: 1)
d_smoothing : int, optional
The smoothing factor for %D. (default: 3)
Returns:
--------
pd.DataFrame
The dataset with the slow stochastic feature added.
"""
self.logger.info("Calculating slow stochastic...")
start = time.perf_counter()
stoch_k, stoch_d = ta.slow_stoch(
self.dataset[source_column],
self.dataset["high"],
self.dataset["low"],
k_length,
k_smoothing,
d_smoothing,
ma_method,
)
if self.normalize:
stoch_k = stoch_k.rolling(2).std().diff()
stoch_d = stoch_d.rolling(2).std().diff()
self.dataset["stoch_k"] = stoch_k
self.dataset.loc[:, "stoch_k_feat"] = feature_binning(
self.dataset["stoch_k"],
self.test_index,
self.bins,
)
self.dataset["stoch_d"] = stoch_d
self.dataset.loc[:, "stoch_d_feat"] = feature_binning(
self.dataset["stoch_d"],
self.test_index,
self.bins,
)
self.logger.info(
"Slow stochastic calculated in %.2f seconds.",
time.perf_counter() - start,
)
return self.dataset
def create_dtw_distance_feature(
self,
source: pd.Series,
feats: Literal["sma", "ema", "dema", "tema", "rma", "all"] | list,
length: int,
) -> pd.DataFrame:
"""
Create the DTW distance feature.
Parameters
----------
source : pd.Series
The source series for calculating the DTW distance.
feats : Literal["sma", "ema", "dema", "tema", "rma", "all"]
| list
The list of features to calculate the DTW distance for.
length : int
The length of the moving average calculation.
Returns
-------
pd.DataFrame
The dataset with the DTW distance features added.
"""
if self.normalize:
source = source.copy().pct_change().rolling(2).std().iloc[2:]
if feats == "all":
feats = ["sma", "ema", "rma", "dema", "tema"]
self.logger.info("Calculating DTW distance for moving averages...\n")
start_time_dtw: float = time.perf_counter()
for ma in feats:
dtw_distance_params = [source, length]
MA = ma.upper()
if ma == "dema":
dtw_distance_params.append(2)
ma = "sema"
elif ma == "tema":
dtw_distance_params.append(3)
ma = "sema"
self.logger.info("Calculating DTW distance for %s...", MA)
start = time.perf_counter()
method = getattr(ta, ma)
moving_average = method(*dtw_distance_params)
if self.normalize:
self.dataset[f"{MA}_DTW"] = (
DynamicTimeWarping(source.dropna(), moving_average)
.calculate_dtw_distance("ratio", True)
.rolling(2)
.std()
.diff()
)
else:
self.dataset[f"{MA}_DTW"] = (
DynamicTimeWarping(source, moving_average)
.calculate_dtw_distance("absolute", True)
)
self.dataset.loc[:, f"{MA}_DTW_feat"] = feature_binning(
self.dataset[f"{MA}_DTW"],
self.test_index,
self.bins,
)
self.logger.info(
"DTW distance for %s calculated in %.2f seconds.",
MA,
time.perf_counter() - start,
)
self.logger.info(
"\nDTW distance for moving averages calculated in %.2f seconds.\n",
time.perf_counter() - start_time_dtw,
)
return self.dataset
def create_cci_feature(
self,
source: pd.Series,
length: int = 20,
method: Literal["sma", "ema", "dema", "tema", "rma"] = "sma",
):
"""
Create the CCI (Commodity Channel Index) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating CCI.
length : int, optional
The length of the CCI calculation.
(default: 20)
method : Literal['sma', 'ema', 'dema', 'tema', 'rma'], optional
The moving average method to use for CCI calculation.
(default: 'sma')
Returns:
--------
pd.DataFrame
The dataset with the CCI feature added.
"""
self.logger.info("Calculating CCI...")
start = time.perf_counter()
self.dataset["CCI"] = ta.CCI(source, length, method=method)["CCI"]
self.dataset.loc[:, "CCI_feat"] = feature_binning(
self.dataset["CCI"],
self.test_index,
self.bins,
)
self.logger.info(
"CCI calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_didi_index_feature(
self,
source: pd.Series,
short_length: int = 3,
medium_length: int = 18,
long_length: int = 20,
ma_type: Literal["sma", "ema", "dema", "tema", "rma"] = "sma",
method: Literal["absolute", "ratio", "dtw"] = "absolute",
):
"""
Create the Didi Index feature.
Parameters:
-----------
source : pd.Series
The source series for calculating the DIDI index.
short_length : int, optional
The length of the short EMA.
(default: 3)
medium_length : int, optional
The length of the medium EMA.
(default: 18)
long_length : int, optional
The length of the long EMA.
(default: 20)
Returns:
--------
pd.DataFrame
The dataset with the DIDI index feature added.
"""
if method not in ["absolute", "ratio", "dtw"]:
raise ValueError(
"Invalid method provided. Use 'absolute', 'ratio', or 'dtw'."
)
self.logger.info("Calculating new DIDI index...")
start = time.perf_counter()
if self.normalize:
source = source.copy().pct_change().rolling(2).std().iloc[2:]
self.dataset["DIDI"] = (
ta.didi_index(
source,
short_length,
medium_length,
long_length,
ma_type,
"ratio",
False,
)
.rolling(2)
.std()
.diff()
)
else:
is_dtw_distance = False
if method == "dtw":
method = "absolute"
is_dtw_distance = True
self.dataset["DIDI"] = ta.didi_index(
source,
short_length,
medium_length,
long_length,
ma_type,
method,
is_dtw_distance,
)
self.dataset.loc[:, "DIDI_feat"] = feature_binning(
self.dataset["DIDI"],
self.test_index,
self.bins,
)
self.logger.info(
"DIDI index calculated in %.2f seconds.",
time.perf_counter() - start,
)
return self.dataset
def create_macd_feature(
self,
source: pd.Series,
fast_length: int = 12,
slow_length: int = 26,
signal_length: int = 9,
diff_method: Literal["absolute", "ratio", "dtw"] = "absolute",
ma_method: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
signal_method: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
column: Literal["macd", "signal", "histogram"] = "histogram",
):
"""
Create the MACD index feature.
Parameters
----------
source : pd.Series
The source series for calculating the MACD index.
short_length : int, optional
The length of the short EMA.
(default: 12)
long_length : int, optional
The length of the long EMA.
(default: 26)
signal_length : int, optional
The length of the signal line.
(default: 9)
diff_method : Literal['absolute', 'ratio', 'dtw'], optional
The method to use for calculating the MACD index.
(default: 'absolute')
ma_method : Literal['sma', 'ema','dema','tema', 'rma'], optional
The moving average method to use for MACD calculation.
(default: 'ema')
signal_method : Literal['sma', 'ema','dema','tema', 'rma'], optional
The moving average method to use for signal line calculation.
(default: 'ema')
column : Literal['macd', 'signal', 'histogram'], optional
The column to return from the MACD calculation.
(default: 'histogram')
Returns
-------
pd.DataFrame
The dataset with the MACD index feature added.
"""
self.logger.info("Calculating MACD index...")
start = time.perf_counter()
if self.normalize:
if ma_method not in ['sma', 'ema','dema', 'rma']:
raise ValueError(
"Invalid moving average method provided."
" Use 'sma', 'ema', 'dema', or 'rma'."
)
if column != "histogram":
warnings.warn(
f"{column} isn't compatible with normalization"
+ " and will be set to 'histogram'."
)
if diff_method != "ratio":
warnings.warn(
f"{diff_method} isn't compatible with normalization"
+ " and will be set to 'ratio'."
)
column = "histogram"
diff_method = "ratio"
source = source.copy().pct_change().rolling(2).std().iloc[2:]
self.dataset["MACD"] = ta.MACD(
source=source,
fast_length=fast_length,
slow_length=slow_length,
signal_length=signal_length,
diff_method=diff_method,
ma_method=ma_method,
signal_method=signal_method,
)[column]
if self.normalize:
self.dataset["MACD"] = self.dataset["MACD"].rolling(2).std().diff()
self.dataset.loc[:, "MACD_feat"] = feature_binning(
self.dataset["MACD"],
self.test_index,
self.bins,
)
self.logger.info(
"MACD index calculated in %.2f seconds.",
time.perf_counter() - start,
)
return self.dataset
def create_trix_feature(
self,
source: pd.Series,
length: int = 15,
signal_length: int = 1,
method: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
):
"""
Create the TRIX (Triple Exponential Moving Average) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating the TRIX.
length : int, optional
The length of the TRIX calculation.
(default: 15)
signal_length : int, optional
The length of the signal line.
(default: 1)
method : Literal['sma', 'ema', 'dema', 'tema', 'rma'], optional
The moving average method to use for TRIX calculation.
(default: 'ema')
Returns:
--------
pd.DataFrame
The dataset with the TRIX feature added.
"""
self.logger.info("Calculating TRIX...")
start = time.perf_counter()
if self.normalize:
source = source.copy().pct_change().rolling(2).std().iloc[2:]
self.dataset["TRIX"] = (
ta.TRIX(source, length, signal_length, method)
.rolling(2)
.std()
.diff()
)
else:
self.dataset["TRIX"] = ta.TRIX(
source,
length,
signal_length,
method,
)
self.dataset.loc[:, "TRIX_feat"] = feature_binning(
self.dataset["TRIX"],
self.test_index,
self.bins,
)
self.logger.info(
"TRIX calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_smio_feature(
self,
source: pd.Series,
short_length: int = 20,
long_length: int = 5,
signal_length: int = 5,
ma_type: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
):
"""
Create the SMIO (SMI Ergotic Oscillator) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating the SMIO.
short_length : int, optional
The length of the faster moving average. (default: 3)
long_length : int, optional
The length of the slower moving average. (default: 18)
ma_type : Literal['sma', 'ema', 'dema', 'tema', 'rma'], optional
The moving average method to use for SMIO calculation.
(default: 'ema')
Returns:
--------
pd.DataFrame
The dataset with the SMIO feature added.
"""
self.logger.info("Calculating SMIO...")
start = time.perf_counter()
self.dataset["SMIO"] = ta.SMIO(
source=source,
long_length=long_length,
short_length=short_length,
signal_length=signal_length,
ma_method=ma_type,
)
if self.normalize:
self.dataset["SMIO"] = self.dataset["SMIO"].rolling(2).std().diff()
self.dataset.loc[:, "SMIO_feat"] = feature_binning(
self.dataset["SMIO"],
self.test_index,
self.bins,
)
self.logger.info(
"SMIO calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_tsi_feature(
self,
source: pd.Series,
short_length: int = 13,
long_length: int = 25,
ma_type: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
):
"""
Create the TSI (True Strength Index) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating the TSI.
short_length : int, optional
The length of the faster MA.
(default: 13)
long_length : int, optional
The length of the slower MA.
(default: 25)
ma_type : Literal['sma', 'ema', 'dema', 'tema', 'rma'], optional
The moving average method to use for TSI calculation.
(default: 'ema')
Returns:
--------
pd.DataFrame
The dataset with the TSI feature added.
"""
self.logger.info("Calculating TSI...")
start = time.perf_counter()
self.dataset["TSI"] = ta.tsi(
source=source,
short_length=short_length,
long_length=long_length,
ma_method=ma_type,
)
if self.normalize:
self.dataset["TSI"] = self.dataset["TSI"].rolling(2).std().diff()
self.dataset.loc[:, "TSI_feat"] = feature_binning(
self.dataset["TSI"],
self.test_index,
self.bins,
)
self.logger.info(
"TSI calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_ichimoku_feature(
self,
conversion_periods: int,
base_periods: int,
lagging_span_2_periods: int,
displacement: int,
based_on: Literal["lead_line", "leading_span"] = "leading_span",
method: Literal["absolute", "ratio", "dtw"] = "absolute",
):
"""
Create the Ichimoku Clouds feature.
Parameters:
-----------
conversion_periods : int
The conversion line period.
base_periods : int
The base line period.
lagging_span_2_periods : int
The lagging span 2 period.
displacement : int
The displacement period.
based_on : Literal["lead_line", "lagging_span"], optional
The line to base the distance calculation on.
(default: "lagging_span")
method : Literal["absolute", "ratio", "dtw"], optional
The method to use for calculating the distance.
(default: "absolute")
"""
self.logger.info("Calculating Ichimoku Clouds...")
start = time.perf_counter()
ichimoku = ta.Ichimoku(
dataframe=self.dataset,
conversion_periods=conversion_periods,
base_periods=base_periods,
lagging_span_2_periods=lagging_span_2_periods,
displacement=displacement,
)[
[
"lead_line1",
"lead_line2",
"leading_span_a",
"leading_span_b",
]
]
if method == "absolute":
lead_line_distance = (
ichimoku["lead_line1"] - ichimoku["lead_line2"]
)
leading_span_distance = (
ichimoku["leading_span_a"] - ichimoku["leading_span_b"]
)
elif method == "ratio":
lead_line_distance = (
ichimoku["lead_line1"] / ichimoku["lead_line2"]
)
leading_span_distance = (
ichimoku["leading_span_a"] / ichimoku["leading_span_b"]
)
elif method == "dtw":
lead_line_distance = DynamicTimeWarping(
ichimoku["lead_line1"].dropna(),
ichimoku["lead_line2"].dropna(),
).calculate_dtw_distance(method="absolute", align_sequences=True)
leading_span_distance = DynamicTimeWarping(
ichimoku["leading_span_a"].dropna(),
ichimoku["leading_span_b"].dropna(),
).calculate_dtw_distance(method="absolute", align_sequences=True)
else:
raise ValueError(f"method '{method}' not found.")
if based_on == "lead_line":
self.dataset["ichimoku_distance"] = lead_line_distance
elif based_on == "leading_span":
self.dataset["ichimoku_distance"] = leading_span_distance
else:
raise ValueError(f"'{based_on}' is a invalid parameter.")
self.dataset.loc[:, "ichimoku_feat"] = feature_binning(
self.dataset["ichimoku_distance"],
self.test_index,
self.bins,
)
self.logger.info(
"Ichimoku calculated in %.2f seconds.", time.perf_counter() - start
)
return self.dataset
def create_ichimoku_price_distance_feature(
self,
source: pd.Series,
conversion_periods: int,
base_periods: int,
lagging_span_2_periods: int,
displacement: int,
based_on: Literal["lead_line", "leading_span"] = "leading_span",
method: Literal["absolute", "ratio", "dtw"] = "absolute",
use_pct_change: bool = True,
):
"""
Create the Ichimoku Clouds feature.
Parameters:
-----------
conversion_periods : int
The conversion line period.
base_periods : int
The base line period.
lagging_span_2_periods : int
The lagging span 2 period.
displacement : int
The displacement period.
based_on : Literal["lead_line", "lagging_span"], optional
The line to base the distance calculation on.
(default: "lagging_span")
method : Literal["absolute", "ratio", "dtw"], optional
The method to use for calculating the distance.
(default: "absolute")
"""
self.logger.info("Calculating Ichimoku Clouds...")
start = time.perf_counter()
if not isinstance(source, pd.Series):
raise ValueError("source must be a pandas Series.")
dataset = self.dataset.copy()
if use_pct_change:
dataset = dataset.copy().pct_change().iloc[1:]
source = source.copy().pct_change().iloc[1:]
ichimoku = ta.Ichimoku(
dataframe=dataset,
conversion_periods=conversion_periods,
base_periods=base_periods,
lagging_span_2_periods=lagging_span_2_periods,
displacement=displacement,
)[
[
"lead_line1",
"lead_line2",
"leading_span_a",
"leading_span_b",
]
]
ichimoku["source"] = source
if based_on == "leading_span":
line1 = ichimoku["leading_span_a"]
line2 = ichimoku["leading_span_b"]
elif based_on == "lead_line":
line1 = ichimoku["lead_line1"]
line2 = ichimoku["lead_line2"]
else:
raise ValueError(
"based_on parameter must be 'lead_line' or 'leading_span'"
)
if method == "absolute":
line1_distance = abs(ichimoku["source"] - line1)
line2_distance = abs(ichimoku["source"] - line2)
elif method == "ratio":
line1_distance = abs(ichimoku["source"] / line1)
line2_distance = abs(ichimoku["source"] / line2)
elif method == "dtw":
line1_distance = abs(
DynamicTimeWarping(
ichimoku["source"], line1.fillna(ichimoku["source"])
).calculate_dtw_distance(
method="absolute", align_sequences=True
)
)
line2_distance = abs(
DynamicTimeWarping(
ichimoku["source"], line2.fillna(ichimoku["source"])
).calculate_dtw_distance(
method="absolute", align_sequences=True
)
)
else:
raise ValueError(
"method parameter must be 'absolute', 'ratio', or 'dtw'"
)
line1_distance = line1_distance.rename("diff_line1")
line2_distance = line2_distance.rename("diff_line2")
ichimoku_df = pd.concat([line1_distance, line2_distance], axis=1)
ichimoku_df["minimum_distance"] = np.where(
ichimoku_df["diff_line1"] < ichimoku_df["diff_line2"], line1, line2
)
self.dataset["ichimoku_distance"] = (
ichimoku["source"] - ichimoku_df["minimum_distance"]
)
self.dataset.loc[:, "ichimoku_distance_feat"] = feature_binning(
self.dataset["ichimoku_distance"],
self.test_index,
self.bins,
)
self.logger.info(
"Ichimoku distance calculated in %.2f seconds.",
time.perf_counter() - start,
)
return self.dataset
def create_bb_trend_feature(
self,
source: pd.Series,
short_length: int = 13,
long_length: int = 25,
stdev_multiplier: float = 2.0,
ma_type: Literal["sma", "ema", "dema", "tema", "rma"] = "ema",
stdev_method: Literal["absolute", "ratio", "dtw"] = "absolute",
diff_method: Literal["absolute", "ratio", "normal"] = "normal",
based_on: Literal["short_length", "long_length"] = "long_length",
):
"""
Create the BB Trend (Bollinger Bands Trend) feature.
Parameters:
-----------
source : pd.Series
The source series for calculating the BB Trend.
short_length : int, optional
The length of the faster MA.
(default: 13)
long_length : int, optional
The length of the slower MA.
(default: 25)
ma_type : Literal['sma', 'ema', 'dema', 'tema', 'rma'], optional
The moving average method to use for BB Trend calculation.
(default: 'ema')
Returns:
--------
pd.DataFrame
The dataset with the BB Trend feature added.
"""
self.logger.info("Calculating BB Trend...")
start = time.perf_counter()