-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcore.py
1746 lines (1468 loc) · 82.3 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from dataclasses import dataclass, field
from multiprocessing import cpu_count, Pool
from pathlib import Path
from time import perf_counter
from typing import List, Tuple
import pandas as pd
from numpy import log10 as npLog10
from numpy import ndarray as npNdarray
from pandas.core.base import PandasObject
from pandas_ta import Category, Imports, version
from pandas_ta.candles.cdl_pattern import ALL_PATTERNS
from pandas_ta.candles import *
from pandas_ta.cycles import *
from pandas_ta.momentum import *
from pandas_ta.overlap import *
from pandas_ta.performance import *
from pandas_ta.statistics import *
from pandas_ta.trend import *
from pandas_ta.volatility import *
from pandas_ta.volume import *
from pandas_ta.utils import *
df = pd.DataFrame()
# Strategy DataClass
@dataclass
class Strategy:
"""Strategy DataClass
A way to name and group your favorite indicators
Args:
name (str): Some short memorable string. Note: Case-insensitive "All" is reserved.
ta (list of dicts): A list of dicts containing keyword arguments where "kind" is the indicator.
description (str): A more detailed description of what the Strategy tries to capture. Default: None
created (str): At datetime string of when it was created. Default: Automatically generated. *Subject to change*
Example TA:
ta = [
{"kind": "sma", "length": 200},
{"kind": "sma", "close": "volume", "length": 50},
{"kind": "bbands", "length": 20},
{"kind": "rsi"},
{"kind": "macd", "fast": 8, "slow": 21},
{"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
]
"""
name: str # = None # Required.
ta: List = field(default_factory=list) # Required.
# Helpful. More descriptive version or notes or w/e.
description: str = "TA Description"
# Optional. Gets Exchange Time and Local Time execution time
created: str = get_time(to_string=True)
def __post_init__(self):
has_name = True
is_ta = False
required_args = ["[X] Strategy requires the following argument(s):"]
name_is_str = isinstance(self.name, str)
ta_is_list = isinstance(self.ta, list)
if self.name is None or not name_is_str:
required_args.append(' - name. Must be a string. Example: "My TA". Note: "all" is reserved.')
has_name != has_name
if self.ta is None:
self.ta = None
elif self.ta is not None and ta_is_list and self.total_ta() > 0:
# Check that all elements of the list are dicts.
# Does not check if the dicts values are valid indicator kwargs
# User must check indicator documentation for all indicators args.
is_ta = all([isinstance(_, dict) and len(_.keys()) > 0 for _ in self.ta])
else:
s = " - ta. Format is a list of dicts. Example: [{'kind': 'sma', 'length': 10}]"
s += "\n Check the indicator for the correct arguments if you receive this error."
required_args.append(s)
if len(required_args) > 1:
[print(_) for _ in required_args]
return None
def total_ta(self):
return len(self.ta) if self.ta is not None else 0
# All Default Strategy
AllStrategy = Strategy(
name="All",
description="All the indicators with their default settings. Pandas TA default.",
ta=None,
)
# Default (Example) Strategy.
CommonStrategy = Strategy(
name="Common Price and Volume SMAs",
description="Common Price SMAs: 10, 20, 50, 200 and Volume SMA: 20.",
ta=[
{"kind": "sma", "length": 10},
{"kind": "sma", "length": 20},
{"kind": "sma", "length": 50},
{"kind": "sma", "length": 200},
{"kind": "sma", "close": "volume", "length": 20, "prefix": "VOL"}
]
)
# Base Class for extending a Pandas DataFrame
class BasePandasObject(PandasObject):
"""Simple PandasObject Extension
Ensures the DataFrame is not empty and has columns.
It would be a sad Panda otherwise.
Args:
df (pd.DataFrame): Extends Pandas DataFrame
"""
def __init__(self, df, **kwargs):
if df.empty: return
if len(df.columns) > 0:
common_names = {
"Date": "date",
"Time": "time",
"Timestamp": "timestamp",
"Datetime": "datetime",
"Open": "open",
"High": "high",
"Low": "low",
"Close": "close",
"Adj Close": "adj_close",
"Volume": "volume",
"Dividends": "dividends",
"Stock Splits": "split",
}
# Preemptively drop the rows that are all NaNs
# Might need to be moved to AnalysisIndicators.__call__() to be
# toggleable via kwargs.
# df.dropna(axis=0, inplace=True)
# Preemptively rename columns to lowercase
df.rename(columns=common_names, errors="ignore", inplace=True)
# Preemptively lowercase the index
index_name = df.index.name
if index_name is not None:
df.index.rename(index_name.lower(), inplace=True)
self._df = df
else:
raise AttributeError(f"[X] No columns!")
def __call__(self, kind, *args, **kwargs):
raise NotImplementedError()
# Pandas TA - DataFrame Analysis Indicators
@pd.api.extensions.register_dataframe_accessor("ta")
class AnalysisIndicators(BasePandasObject):
"""
This Pandas Extension is named 'ta' for Technical Analysis. In other words,
it is a Numerical Time Series Feature Generator where the Time Series data
is biased towards Financial Market data; typical data includes columns
named :"open", "high", "low", "close", "volume".
This TA Library hopefully allows you to apply familiar and unique Technical
Analysis Indicators easily with the DataFrame Extension named 'ta'. Even
though 'ta' is a Pandas DataFrame Extension, you can still call Technical
Analysis indicators individually if you are more comfortable with that
approach or it allows you to easily and automatically apply the indicators
with the strategy method. See: help(ta.strategy).
By default, the 'ta' extension uses lower case column names: open, high,
low, close, and volume. You can override the defaults by providing the it's
replacement name when calling the indicator. For example, to call the
indicator hl2().
With 'default' columns: open, high, low, close, and volume.
>>> df.ta.hl2()
>>> df.ta(kind="hl2")
With DataFrame columns: Open, High, Low, Close, and Volume.
>>> df.ta.hl2(high="High", low="Low")
>>> df.ta(kind="hl2", high="High", low="Low")
If you do not want to use a DataFrame Extension, just call it normally.
>>> sma10 = ta.sma(df["Close"]) # Default length=10
>>> sma50 = ta.sma(df["Close"], length=50)
>>> ichimoku, span = ta.ichimoku(df["High"], df["Low"], df["Close"])
Args:
kind (str, optional): Default: None. Kind is the 'name' of the indicator.
It converts kind to lowercase before calling.
timed (bool, optional): Default: False. Curious about the execution
speed?
kwargs: Extension specific modifiers.
append (bool, optional): Default: False. When True, it appends the
resultant column(s) to the DataFrame.
Returns:
Most Indicators will return a Pandas Series. Others like MACD, BBANDS,
KC, et al will return a Pandas DataFrame. Ichimoku on the other hand
will return two DataFrames, the Ichimoku DataFrame for the known period
and a Span DataFrame for the future of the Span values.
Let's get started!
1. Loading the 'ta' module:
>>> import pandas as pd
>>> import ta as ta
2. Load some data:
>>> df = pd.read_csv("AAPL.csv", index_col="date", parse_dates=True)
3. Help!
3a. General Help:
>>> help(df.ta)
>>> df.ta()
3b. Indicator Help:
>>> help(ta.apo)
3c. Indicator Extension Help:
>>> help(df.ta.apo)
4. Ways of calling an indicator.
4a. Standard: Calling just the APO indicator without "ta" DataFrame extension.
>>> ta.apo(df["close"])
4b. DataFrame Extension: Calling just the APO indicator with "ta" DataFrame extension.
>>> df.ta.apo()
4c. DataFrame Extension (kind): Calling APO using 'kind'
>>> df.ta(kind="apo")
4d. Strategy:
>>> df.ta.strategy("All") # Default
>>> df.ta.strategy(ta.Strategy("My Strat", ta=[{"kind": "apo"}])) # Custom
5. Working with kwargs
5a. Append the result to the working df.
>>> df.ta.apo(append=True)
5b. Timing an indicator.
>>> apo = df.ta(kind="apo", timed=True)
>>> print(apo.timed)
"""
_adjusted = None
_cores = cpu_count()
_df = DataFrame()
_exchange = "NYSE"
_time_range = "years"
_last_run = get_time(_exchange, to_string=True)
# def __init__(self, pandas_obj):
# # self._validate(pandas_obj)
# self._df = pandas_obj
# self._last_run = get_time(self._exchange, to_string=True)
# @staticmethod
# def _validate(df: Tuple[pd.DataFrame, pd.Series]):
# if isinstance(df, pd.Series) or isinstance(df, pd.DataFrame):
# raise AttributeError("[X] Must be either a Pandas Series or DataFrame.")
# DataFrame Behavioral Methods
def __call__(
self, kind: str = None,
timed: bool = False, version: bool = False, **kwargs
):
if version: print(f"Pandas TA - Technical Analysis Indicators - v{self.version}")
try:
if isinstance(kind, str):
kind = kind.lower()
fn = getattr(self, kind)
if timed:
stime = perf_counter()
# Run the indicator
result = fn(**kwargs) # = getattr(self, kind)(**kwargs)
self._last_run = get_time(self.exchange, to_string=True) # Save when it completed it's run
if timed:
result.timed = final_time(stime)
print(f"[+] {kind}: {result.timed}")
return result
else:
self.help()
except BaseException:
pass
# Public Get/Set DataFrame Properties
@property
def adjusted(self) -> str:
"""property: df.ta.adjusted"""
return self._adjusted
@adjusted.setter
def adjusted(self, value: str) -> None:
"""property: df.ta.adjusted = 'adj_close'"""
if value is not None and isinstance(value, str):
self._adjusted = value
else:
self._adjusted = None
@property
def cores(self) -> str:
"""Returns the categories."""
return self._cores
@cores.setter
def cores(self, value: int) -> None:
"""property: df.ta.cores = integer"""
cpus = cpu_count()
if value is not None and isinstance(value, int):
self._cores = int(value) if 0 <= value <= cpus else cpus
else:
self._cores = cpus
@property
def exchange(self) -> str:
"""Returns the current Exchange. Default: "NYSE"."""
return self._exchange
@exchange.setter
def exchange(self, value: str) -> None:
"""property: df.ta.exchange = "LSE" """
if value is not None and isinstance(value, str) and value in EXCHANGE_TZ.keys():
self._exchange = value
@property
def last_run(self) -> str:
"""Returns the time when the DataFrame was last run."""
return self._last_run
# Public Get DataFrame Properties
@property
def categories(self) -> str:
"""Returns the categories."""
return list(Category.keys())
@property
def datetime_ordered(self) -> bool:
"""Returns True if the index is a datetime and ordered."""
hasdf = hasattr(self, "_df")
if hasdf:
return is_datetime_ordered(self._df)
return hasdf
@property
def reverse(self) -> pd.DataFrame:
"""Reverses the DataFrame. Simply: df.iloc[::-1]"""
return self._df.iloc[::-1]
@property
def time_range(self) -> float:
"""Returns the time ranges of the DataFrame as a float. Default is in "years". help(ta.toal_time)"""
return total_time(self._df, self._time_range)
@time_range.setter
def time_range(self, value: str) -> None:
"""property: df.ta.time_range = "years" (Default)"""
if value is not None and isinstance(value, str):
self._time_range = value
else:
self._time_range = "years"
@property
def to_utc(self) -> None:
"""Sets the DataFrame index to UTC format"""
self._df = to_utc(self._df)
@property
def version(self) -> str:
"""Returns the version."""
return version
# Private DataFrame Methods
def _add_prefix_suffix(self, result=None, **kwargs) -> None:
"""Add prefix and/or suffix to the result columns"""
if result is None:
return
else:
prefix = suffix = ""
delimiter = kwargs.setdefault("delimiter", "_")
if "prefix" in kwargs:
prefix = f"{kwargs['prefix']}{delimiter}"
if "suffix" in kwargs:
suffix = f"{delimiter}{kwargs['suffix']}"
if isinstance(result, pd.Series):
result.name = prefix + result.name + suffix
else:
result.columns = [prefix + column + suffix for column in result.columns]
def _append(self, result=None, **kwargs) -> None:
"""Appends a Pandas Series or DataFrame columns to self._df."""
if "append" in kwargs and kwargs["append"]:
df = self._df
if df is None or result is None: return
else:
if "col_names" in kwargs and not isinstance(kwargs["col_names"], tuple):
kwargs["col_names"] = (kwargs["col_names"],)
if isinstance(result, pd.DataFrame):
# If specified in kwargs, rename the columns.
# If not, use the default names.
if "col_names" in kwargs and isinstance(kwargs["col_names"], tuple):
if len(kwargs["col_names"]) >= len(result.columns):
for col, ind_name in zip(result.columns, kwargs["col_names"]):
df[ind_name] = result.loc[:, col]
else:
print(f"Not enough col_names were specified : got {len(kwargs['col_names'])}, expected {len(result.columns)}.")
return
else:
for i, column in enumerate(result.columns):
df[column] = result.iloc[:, i]
else:
ind_name = (
kwargs["col_names"][0] if "col_names" in kwargs and
isinstance(kwargs["col_names"], tuple) else result.name
)
df[ind_name] = result
def _check_na_columns(self, stdout: bool = True):
"""Returns the columns in which all it's values are na."""
return [x for x in self._df.columns if all(self._df[x].isna())]
def _get_column(self, series):
"""Attempts to get the correct series or 'column' and return it."""
df = self._df
if df is None: return
# Explicitly passing a pd.Series to override default.
if isinstance(series, pd.Series):
return series
# Apply default if no series nor a default.
elif series is None:
return df[self.adjusted] if self.adjusted is not None else None
# Ok. So it's a str.
elif isinstance(series, str):
# Return the df column since it's in there.
if series in df.columns:
return df[series]
else:
# Attempt to match the 'series' because it was likely
# misspelled.
matches = df.columns.str.match(series, case=False)
match = [i for i, x in enumerate(matches) if x]
# If found, awesome. Return it or return the 'series'.
cols = ", ".join(list(df.columns))
NOT_FOUND = f"[X] Ooops!!! It's {series not in df.columns}, the series '{series}' was not found in {cols}"
return df.iloc[:, match[0]] if len(match) else print(NOT_FOUND)
def _indicators_by_category(self, name: str) -> list:
"""Returns indicators by Categorical name."""
return Category[name] if name in self.categories else None
def _mp_worker(self, arguments: tuple):
"""Multiprocessing Worker to handle different Methods."""
method, args, kwargs = arguments
if method != "ichimoku":
return getattr(self, method)(*args, **kwargs)
else:
return getattr(self, method)(*args, **kwargs)[0]
def _post_process(self, result, **kwargs) -> Tuple[pd.Series, pd.DataFrame]:
"""Applies any additional modifications to the DataFrame
* Applies prefixes and/or suffixes
* Appends the result to main DataFrame
"""
verbose = kwargs.pop("verbose", False)
if not isinstance(result, (pd.Series, pd.DataFrame)):
if verbose:
print(f"[X] Oops! The result was not a Series or DataFrame.")
return self._df
else:
# Append only specific columns to the dataframe (via
# 'col_numbers':(0,1,3) for example)
result = (result.iloc[:, [int(n) for n in kwargs["col_numbers"]]]
if isinstance(result, pd.DataFrame) and
"col_numbers" in kwargs and
kwargs["col_numbers"] is not None else result)
# Add prefix/suffix and append to the dataframe
self._add_prefix_suffix(result=result, **kwargs)
self._append(result=result, **kwargs)
return result
def _strategy_mode(self, *args) -> tuple:
"""Helper method to determine the mode and name of the strategy. Returns tuple: (name:str, mode:dict)"""
name = "All"
mode = {"all": False, "category": False, "custom": False}
if len(args) == 0:
mode["all"] = True
else:
if isinstance(args[0], str):
if args[0].lower() == "all":
name, mode["all"] = name, True
if args[0].lower() in self.categories:
name, mode["category"] = args[0], True
if isinstance(args[0], Strategy):
strategy_ = args[0]
if strategy_.ta is None or strategy_.name.lower() == "all":
name, mode["all"] = name, True
elif strategy_.name.lower() in self.categories:
name, mode["category"] = strategy_.name, True
else:
name, mode["custom"] = strategy_.name, True
return name, mode
# Public DataFrame Methods
def constants(self, append: bool, values: list):
"""Constants
Add or remove constants to the DataFrame easily with Numpy's arrays or
lists. Useful when you need easily accessible horizontal lines for
charting.
Add constant '1' to the DataFrame
>>> df.ta.constants(True, [1])
Remove constant '1' to the DataFrame
>>> df.ta.constants(False, [1])
Adding constants for charting
>>> import numpy as np
>>> chart_lines = np.append(np.arange(-4, 5, 1), np.arange(-100, 110, 10))
>>> df.ta.constants(True, chart_lines)
Removing some constants from the DataFrame
>>> df.ta.constants(False, np.array([-60, -40, 40, 60]))
Args:
append (bool): If True, appends a Numpy range of constants to the
working DataFrame. If False, it removes the constant range from
the working DataFrame. Default: None.
Returns:
Returns the appended constants
Returns nothing to the user. Either adds or removes constant ranges
from the working DataFrame.
"""
if isinstance(values, npNdarray) or isinstance(values, list):
if append:
for x in values:
self._df[f"{x}"] = x
return self._df[self._df.columns[-len(values):]]
else:
for x in values:
del self._df[f"{x}"]
def indicators(self, **kwargs):
"""List of Indicators
kwargs:
as_list (bool, optional): When True, it returns a list of the
indicators. Default: False.
exclude (list, optional): The passed in list will be excluded
from the indicators list. Default: None.
Returns:
Prints the list of indicators. If as_list=True, then a list.
"""
as_list = kwargs.setdefault("as_list", False)
# Public non-indicator methods
helper_methods = ["constants", "indicators", "strategy"]
# Public df.ta.properties
ta_properties = [
"adjusted",
"categories",
"cores",
"datetime_ordered",
"exchange",
"last_run",
"reverse",
"ticker",
"time_range",
"to_utc",
"version",
]
# Public non-indicator methods
ta_indicators = list((x for x in dir(pd.DataFrame().ta) if not x.startswith("_") and not x.endswith("_")))
# Add Pandas TA methods and properties to be removed
removed = helper_methods + ta_properties
# Add user excluded methods to be removed
user_excluded = kwargs.setdefault("exclude", [])
if isinstance(user_excluded, list) and len(user_excluded) > 0:
removed += user_excluded
# Remove the unwanted indicators
[ta_indicators.remove(x) for x in removed]
# If as a list, immediately return
if as_list:
return ta_indicators
total_indicators = len(ta_indicators)
header = f"Pandas TA - Technical Analysis Indicators - v{self.version}"
s = f"{header}\nTotal Indicators & Utilities: {total_indicators + len(ALL_PATTERNS)}\n"
if total_indicators > 0:
print(f"{s}Abbreviations:\n {', '.join(ta_indicators)}\n\nCandle Patterns:\n {', '.join(ALL_PATTERNS)}")
else:
print(s)
def strategy(self, *args, **kwargs):
"""Strategy Method
An experimental method that by default runs all applicable indicators.
Future implementations will allow more specific indicator generation
with possibly as json, yaml config file or an sqlite3 table.
Kwargs:
chunksize (bool): Adjust the chunksize for the Multiprocessing Pool.
Default: Number of cores of the OS
exclude (list): List of indicator names to exclude. Some are
excluded by default for various reasons; they require additional
sources, performance (td_seq), not a ohlcv chart (vp) etc.
name (str): Select all indicators or indicators by
Category such as: "candles", "cycles", "momentum", "overlap",
"performance", "statistics", "trend", "volatility", "volume", or
"all". Default: "all"
ordered (bool): Whether to run "all" in order. Default: True
timed (bool): Show the process time of the strategy().
Default: False
verbose (bool): Provide some additional insight on the progress of
the strategy() execution. Default: False
"""
# If True, it returns the resultant DataFrame. Default: False
returns = kwargs.pop("returns", False)
# cpus = cpu_count()
# Ensure indicators are appended to the DataFrame
kwargs["append"] = True
all_ordered = kwargs.pop("ordered", True)
mp_chunksize = kwargs.pop("chunksize", self.cores)
# Initialize
initial_column_count = len(self._df.columns)
excluded = [
"above",
"above_value",
"below",
"below_value",
"cross",
"cross_value",
# "data", # reserved
"long_run",
"short_run",
"td_seq", # Performance exclusion
"tsignals",
"vp",
"xsignals",
]
# Get the Strategy Name and mode
name, mode = self._strategy_mode(*args)
# If All or a Category, exclude user list if any
user_excluded = kwargs.pop("exclude", [])
if mode["all"] or mode["category"]:
excluded += user_excluded
# Collect the indicators, remove excluded or include kwarg["append"]
if mode["category"]:
ta = self._indicators_by_category(name.lower())
[ta.remove(x) for x in excluded if x in ta]
elif mode["custom"]:
ta = args[0].ta
for kwds in ta:
kwds["append"] = True
elif mode["all"]:
ta = self.indicators(as_list=True, exclude=excluded)
else:
print(f"[X] Not an available strategy.")
return None
# Remove Custom indicators with "length" keyword when larger than the DataFrame
# Possible to have other indicator main window lengths to be included
removal = []
for kwds in ta:
_ = False
if "length" in kwds and kwds["length"] > self._df.shape[0]: _ = True
if _: removal.append(kwds)
if len(removal) > 0: [ta.remove(x) for x in removal]
verbose = kwargs.pop("verbose", False)
if verbose:
print(f"[+] Strategy: {name}\n[i] Indicator arguments: {kwargs}")
if mode["all"] or mode["category"]:
excluded_str = ", ".join(excluded)
print(f"[i] Excluded[{len(excluded)}]: {excluded_str}")
timed = kwargs.pop("timed", False)
results = []
use_multiprocessing = True if self.cores > 0 else False
has_col_names = False
if timed:
stime = perf_counter()
if use_multiprocessing and mode["custom"]:
# Determine if the Custom Model has 'col_names' parameter
has_col_names = (True if len([
True for x in ta
if "col_names" in x and isinstance(x["col_names"], tuple)
]) else False)
if has_col_names:
use_multiprocessing = False
if Imports["tqdm"]:
# from tqdm import tqdm
from tqdm import tqdm
if use_multiprocessing:
_total_ta = len(ta)
with Pool(self.cores) as pool:
# Some magic to optimize chunksize for speed based on total ta indicators
_chunksize = mp_chunksize - 1 if mp_chunksize > _total_ta else int(npLog10(_total_ta)) + 1
if verbose:
print(f"[i] Multiprocessing {_total_ta} indicators with {_chunksize} chunks and {self.cores}/{cpu_count()} cpus.")
results = None
if mode["custom"]:
# Create a list of all the custom indicators into a list
custom_ta = [(
ind["kind"],
ind["params"] if "params" in ind and isinstance(ind["params"], tuple) else (),
{**ind, **kwargs},
) for ind in ta]
# Custom multiprocessing pool. Must be ordered for Chained Strategies
# May fix this to cpus if Chaining/Composition if it remains
results = pool.imap(self._mp_worker, custom_ta, _chunksize)
else:
default_ta = [(ind, tuple(), kwargs) for ind in ta]
# All and Categorical multiprocessing pool.
if all_ordered:
if Imports["tqdm"]:
results = tqdm(pool.imap(self._mp_worker, default_ta, _chunksize)) # Order over Speed
else:
results = pool.imap(self._mp_worker, default_ta, _chunksize) # Order over Speed
else:
if Imports["tqdm"]:
results = tqdm(pool.imap_unordered(self._mp_worker, default_ta, _chunksize)) # Speed over Order
else:
results = pool.imap_unordered(self._mp_worker, default_ta, _chunksize) # Speed over Order
if results is None:
print(f"[X] ta.strategy('{name}') has no results.")
return
pool.close()
pool.join()
self._last_run = get_time(self.exchange, to_string=True)
else:
# Without multiprocessing:
if verbose:
if has_col_names:
print(f"[i] No mulitproccessing support for 'col_names' option.")
else:
print(f"[i] No mulitproccessing (cores = 0).")
if mode["custom"]:
if Imports["tqdm"] and verbose:
pbar = tqdm(ta, f"[i] Progress")
for ind in pbar:
params = ind["params"] if "params" in ind and isinstance(ind["params"], tuple) else tuple()
getattr(self, ind["kind"])(*params, **{**ind, **kwargs})
else:
for ind in ta:
params = ind["params"] if "params" in ind and isinstance(ind["params"], tuple) else tuple()
getattr(self, ind["kind"])(*params, **{**ind, **kwargs})
else:
if Imports["tqdm"] and verbose:
pbar = tqdm(ta, f"[i] Progress")
for ind in pbar:
getattr(self, ind)(*tuple(), **kwargs)
else:
for ind in ta:
getattr(self, ind)(*tuple(), **kwargs)
# Apply prefixes/suffixes and appends indicator results to the DataFrame
[self._post_process(r, **kwargs) for r in results]
if verbose:
print(f"[i] Total indicators: {len(ta)}")
print(f"[i] Columns added: {len(self._df.columns) - initial_column_count}")
print(f"[i] Last Run: {self._last_run}")
if timed:
print(f"[i] Runtime: {final_time(stime)}")
if returns: return self._df
def ticker(self, ticker: str, **kwargs):
"""ticker
This method downloads Historical Data if the package yfinance is installed.
Additionally it can run a ta.Strategy; Builtin or Custom. It returns a
DataFrame if there the DataFrame is not empty, otherwise it exits. For
additional yfinance arguments, use help(ta.yf).
Historical Data
>>> df = df.ta.ticker("aapl")
More specifically
>>> df = df.ta.ticker("aapl", period="max", interval="1d", kind=None)
Changing the period of Historical Data
Period is used instead of start/end
>>> df = df.ta.ticker("aapl", period="1y")
Changing the period and interval of Historical Data
Retrieves the past year in weeks
>>> df = df.ta.ticker("aapl", period="1y", interval="1wk")
Retrieves the past month in hours
>>> df = df.ta.ticker("aapl", period="1mo", interval="1h")
Show everything
>>> df = df.ta.ticker("aapl", kind="all")
Args:
ticker (str): Any string for a ticker you would use with yfinance.
Default: "SPY"
Kwargs:
kind (str): Options see above. Default: "history"
ds (str): Data Source to use. Default: "yahoo"
strategy (str | ta.Strategy): Which strategy to apply after
downloading chart history. Default: None
See help(ta.yf) for additional kwargs
Returns:
Exits if the DataFrame is empty or None
Otherwise it returns a DataFrame
"""
ds = kwargs.pop("ds", "yahoo")
strategy = kwargs.pop("strategy", None)
# Fetch the Data
ds = ds.lower() is not None and isinstance(ds, str)
# df = av(ticker, **kwargs) if ds and ds == "av" else yf(ticker, **kwargs)
df = yf(ticker, **kwargs)
if df is None: return
elif df.empty:
print(f"[X] DataFrame is empty: {df.shape}")
return
else:
if kwargs.pop("lc_cols", False):
df.index.name = df.index.name.lower()
df.columns = df.columns.str.lower()
self._df = df
if strategy is not None: self.strategy(strategy, **kwargs)
return df
# Public DataFrame Methods: Indicators and Utilities
# Candles
def cdl_pattern(self, name="all", offset=None, **kwargs):
open_ = self._get_column(kwargs.pop("open", "open"))
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = cdl_pattern(open_=open_, high=high, low=low, close=close, name=name, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cdl_z(self, full=None, offset=None, **kwargs):
open_ = self._get_column(kwargs.pop("open", "open"))
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = cdl_z(open_=open_, high=high, low=low, close=close, full=full, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def ha(self, offset=None, **kwargs):
open_ = self._get_column(kwargs.pop("open", "open"))
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = ha(open_=open_, high=high, low=low, close=close, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
# Cycles
def ebsw(self, close=None, length=None, bars=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = ebsw(close=close, length=length, bars=bars, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
# Momentum
def ao(self, fast=None, slow=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
result = ao(high=high, low=low, fast=fast, slow=slow, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def apo(self, fast=None, slow=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = apo(close=close, fast=fast, slow=slow, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def bias(self, length=None, mamode=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = bias(close=close, length=length, mamode=mamode, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def bop(self, percentage=False, offset=None, **kwargs):
open_ = self._get_column(kwargs.pop("open", "open"))
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = bop(open_=open_, high=high, low=low, close=close, percentage=percentage, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def brar(self, length=None, scalar=None, drift=None, offset=None, **kwargs):
open_ = self._get_column(kwargs.pop("open", "open"))
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = brar(open_=open_, high=high, low=low, close=close, length=length, scalar=scalar, drift=drift, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cci(self, length=None, c=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = cci(high=high, low=low, close=close, length=length, c=c, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cfo(self, length=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = cfo(close=close, length=length, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cg(self, length=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = cg(close=close, length=length, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cmo(self, length=None, scalar=None, drift=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = cmo(close=close, length=length, scalar=scalar, drift=drift, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def coppock(self, length=None, fast=None, slow=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = coppock(close=close, length=length, fast=fast, slow=slow, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def cti(self, length=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = cti(close=close, length=length, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def dm(self, drift=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
result = dm(high=high, low=low, drift=drift, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def er(self, length=None, drift=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
result = er(close=close, length=length, drift=drift, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def eri(self, length=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = eri(high=high, low=low, close=close, length=length, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def fisher(self, length=None, signal=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
result = fisher(high=high, low=low, length=length, signal=signal, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def inertia(self, length=None, rvi_length=None, scalar=None, refined=None, thirds=None, mamode=None, drift=None, offset=None, **kwargs):
close = self._get_column(kwargs.pop("close", "close"))
if refined is not None or thirds is not None:
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
result = inertia(close=close, high=high, low=low, length=length, rvi_length=rvi_length, scalar=scalar, refined=refined, thirds=thirds, mamode=mamode, drift=drift, offset=offset, **kwargs)
else:
result = inertia(close=close, length=length, rvi_length=rvi_length, scalar=scalar, refined=refined, thirds=thirds, mamode=mamode, drift=drift, offset=offset, **kwargs)
return self._post_process(result, **kwargs)
def kdj(self, length=None, signal=None, offset=None, **kwargs):
high = self._get_column(kwargs.pop("high", "high"))
low = self._get_column(kwargs.pop("low", "low"))
close = self._get_column(kwargs.pop("close", "close"))
result = kdj(high=high, low=low, close=close, length=length, signal=signal, offset=offset, **kwargs)