-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathfinta.py
2379 lines (1959 loc) · 90.3 KB
/
finta.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
from functools import wraps
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
def inputvalidator(input_="ohlc"):
def dfcheck(func):
@wraps(func)
def wrap(*args, **kwargs):
args = list(args)
i = 0 if isinstance(args[0], pd.DataFrame) else 1
args[i] = args[i].rename(columns={c: c.lower() for c in args[i].columns})
inputs = {
"o": "open",
"h": "high",
"l": "low",
"c": kwargs.get("column", "close").lower(),
"v": "volume",
}
if inputs["c"] != "close":
kwargs["column"] = inputs["c"]
for l in input_:
if inputs[l] not in args[i].columns:
raise LookupError(
'Must have a dataframe column named "{0}"'.format(inputs[l])
)
return func(*args, **kwargs)
return wrap
return dfcheck
def apply(decorator):
def decorate(cls):
for attr in cls.__dict__:
if callable(getattr(cls, attr)):
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate
@apply(inputvalidator(input_="ohlc"))
class TA:
__version__ = "1.3"
@classmethod
def SMA(cls, ohlc: DataFrame, period: int = 41, column: str = "close") -> Series:
"""
Simple moving average - rolling mean in pandas lingo. Also known as 'MA'.
The simple moving average (SMA) is the most basic of the moving averages used for trading.
"""
return pd.Series(
ohlc[column].rolling(window=period).mean(),
name="{0} period SMA".format(period),
)
@classmethod
def SMM(cls, ohlc: DataFrame, period: int = 9, column: str = "close") -> Series:
"""
Simple moving median, an alternative to moving average. SMA, when used to estimate the underlying trend in a time series,
is susceptible to rare events such as rapid shocks or other anomalies. A more robust estimate of the trend is the simple moving median over n time periods.
"""
return pd.Series(
ohlc[column].rolling(window=period).median(),
name="{0} period SMM".format(period),
)
@classmethod
def SSMA(
cls,
ohlc: DataFrame,
period: int = 9,
column: str = "close",
adjust: bool = True,
) -> Series:
"""
Smoothed simple moving average.
:param ohlc: data
:param period: range
:param column: open/close/high/low column of the DataFrame
:return: result Series
"""
return pd.Series(
ohlc[column]
.ewm(ignore_na=False, alpha=1.0 / period, min_periods=0, adjust=adjust)
.mean(),
name="{0} period SSMA".format(period),
)
@classmethod
def EMA(
cls,
ohlc: DataFrame,
period: int = 9,
column: str = "close",
adjust: bool = True,
) -> Series:
"""
Exponential Weighted Moving Average - Like all moving average indicators, they are much better suited for trending markets.
When the market is in a strong and sustained uptrend, the EMA indicator line will also show an uptrend and vice-versa for a down trend.
EMAs are commonly used in conjunction with other indicators to confirm significant market moves and to gauge their validity.
"""
return pd.Series(
ohlc[column].ewm(span=period, adjust=adjust).mean(),
name="{0} period EMA".format(period),
)
@classmethod
def DEMA(
cls,
ohlc: DataFrame,
period: int = 9,
column: str = "close",
adjust: bool = True,
) -> Series:
"""
Double Exponential Moving Average - attempts to remove the inherent lag associated to Moving Averages
by placing more weight on recent values. The name suggests this is achieved by applying a double exponential
smoothing which is not the case. The name double comes from the fact that the value of an EMA (Exponential Moving Average) is doubled.
To keep it in line with the actual data and to remove the lag the value 'EMA of EMA' is subtracted from the previously doubled EMA.
Because EMA(EMA) is used in the calculation, DEMA needs 2 * period -1 samples to start producing values in contrast to the period
samples needed by a regular EMA
"""
DEMA = (
2 * cls.EMA(ohlc, period)
- cls.EMA(ohlc, period).ewm(span=period, adjust=adjust).mean()
)
return pd.Series(DEMA, name="{0} period DEMA".format(period))
@classmethod
def TEMA(cls, ohlc: DataFrame, period: int = 9, adjust: bool = True) -> Series:
"""
Triple exponential moving average - attempts to remove the inherent lag associated to Moving Averages by placing more weight on recent values.
The name suggests this is achieved by applying a triple exponential smoothing which is not the case. The name triple comes from the fact that the
value of an EMA (Exponential Moving Average) is triple.
To keep it in line with the actual data and to remove the lag the value 'EMA of EMA' is subtracted 3 times from the previously tripled EMA.
Finally 'EMA of EMA of EMA' is added.
Because EMA(EMA(EMA)) is used in the calculation, TEMA needs 3 * period - 2 samples to start producing values in contrast to the period samples
needed by a regular EMA.
"""
triple_ema = 3 * cls.EMA(ohlc, period)
ema_ema_ema = (
cls.EMA(ohlc, period)
.ewm(ignore_na=False, span=period, adjust=adjust)
.mean()
.ewm(ignore_na=False, span=period, adjust=adjust)
.mean()
)
TEMA = (
triple_ema
- 3 * cls.EMA(ohlc, period).ewm(span=period, adjust=adjust).mean()
+ ema_ema_ema
)
return pd.Series(TEMA, name="{0} period TEMA".format(period))
@classmethod
def TRIMA(cls, ohlc: DataFrame, period: int = 18) -> Series:
"""
The Triangular Moving Average (TRIMA) [also known as TMA] represents an average of prices,
but places weight on the middle prices of the time period.
The calculations double-smooth the data using a window width that is one-half the length of the series.
source: https://www.thebalance.com/triangular-moving-average-tma-description-and-uses-1031203
"""
SMA = cls.SMA(ohlc, period).rolling(window=period).sum()
return pd.Series(SMA / period, name="{0} period TRIMA".format(period))
@classmethod
def TRIX(
cls,
ohlc: DataFrame,
period: int = 20,
column: str = "close",
adjust: bool = True,
) -> Series:
"""
The TRIX indicator calculates the rate of change of a triple exponential moving average.
The values oscillate around zero. Buy/sell signals are generated when the TRIX crosses above/below zero.
A (typically) 9 period exponential moving average of the TRIX can be used as a signal line.
A buy/sell signals are generated when the TRIX crosses above/below the signal line and is also above/below zero.
The TRIX was developed by Jack K. Hutson, publisher of Technical Analysis of Stocks & Commodities magazine,
and was introduced in Volume 1, Number 5 of that magazine.
"""
data = ohlc[column]
def _ema(data, period, adjust):
return pd.Series(data.ewm(span=period, adjust=adjust).mean())
m = _ema(_ema(_ema(data, period, adjust), period, adjust), period, adjust)
return pd.Series(100 * (m.diff() / m), name="{0} period TRIX".format(period))
@classmethod
def LWMA(cls, ohlc: DataFrame, period: int, column: str = "close") -> Series:
"""
Linear Weighted Moving Average
"""
raise NotImplementedError
@classmethod
@inputvalidator(input_="ohlcv")
def VAMA(cls, ohlcv: DataFrame, period: int = 8, column: str = "close") -> Series:
"""
Volume Adjusted Moving Average
"""
vp = ohlcv["volume"] * ohlcv[column]
volsum = ohlcv["volume"].rolling(window=period).mean()
volRatio = pd.Series(vp / volsum, name="VAMA")
cumSum = (volRatio * ohlcv[column]).rolling(window=period).sum()
cumDiv = volRatio.rolling(window=period).sum()
return pd.Series(cumSum / cumDiv, name="{0} period VAMA".format(period))
@classmethod
@inputvalidator(input_="ohlcv")
def VIDYA(
cls,
ohlcv: DataFrame,
period: int = 9,
smoothing_period: int = 12,
column: str = "close",
) -> Series:
"""Vidya (variable index dynamic average) indicator is a modification of the traditional Exponential Moving Average (EMA) indicator.
The main difference between EMA and Vidya is in the way the smoothing factor F is calculated.
In EMA the smoothing factor is a constant value F=2/(period+1);
in Vidya the smoothing factor is variable and depends on bar-to-bar price movements.
"""
raise NotImplementedError
@classmethod
def ER(cls, ohlc: DataFrame, period: int = 10, column: str = "close") -> Series:
"""The Kaufman Efficiency indicator is an oscillator indicator that oscillates between +100 and -100, where zero is the center point.
+100 is upward forex trending market and -100 is downwards trending markets."""
change = ohlc[column].diff(period).abs()
volatility = ohlc[column].diff().abs().rolling(window=period).sum()
return pd.Series(change / volatility, name="{0} period ER".format(period))
@classmethod
def KAMA(
cls,
ohlc: DataFrame,
er: int = 10,
ema_fast: int = 2,
ema_slow: int = 30,
period: int = 20,
column: str = "close",
) -> Series:
"""Developed by Perry Kaufman, Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to account for market noise or volatility.
Its main advantage is that it takes into consideration not just the direction, but the market volatility as well.
"""
er = cls.ER(ohlc, er)
fast_alpha = 2 / (ema_fast + 1)
slow_alpha = 2 / (ema_slow + 1)
sc = pd.Series(
(er * (fast_alpha - slow_alpha) + slow_alpha) ** 2,
name="smoothing_constant",
) ## smoothing constant
sma = pd.Series(
ohlc[column].rolling(period).mean(), name="SMA"
) ## first KAMA is SMA
kama = []
# Current KAMA = Prior KAMA + smoothing_constant * (Price - Prior KAMA)
for s, ma, price in zip(
sc.iteritems(), sma.shift().iteritems(), ohlc[column].iteritems()
):
try:
kama.append(kama[-1] + s[1] * (price[1] - kama[-1]))
except (IndexError, TypeError):
if pd.notnull(ma[1]):
kama.append(ma[1] + s[1] * (price[1] - ma[1]))
else:
kama.append(None)
sma["KAMA"] = pd.Series(
kama, index=sma.index, name="{0} period KAMA.".format(period)
) ## apply the kama list to existing index
return sma["KAMA"]
@classmethod
def ZLEMA(
cls,
ohlc: DataFrame,
period: int = 26,
adjust: bool = True,
column: str = "close",
) -> Series:
"""ZLEMA is an abbreviation of Zero Lag Exponential Moving Average. It was developed by John Ehlers and Rick Way.
ZLEMA is a kind of Exponential moving average but its main idea is to eliminate the lag arising from the very nature of the moving averages
and other trend following indicators. As it follows price closer, it also provides better price averaging and responds better to price swings.
"""
lag = (period - 1) / 2
ema = pd.Series(
(ohlc[column] + (ohlc[column].diff(lag))),
name="{0} period ZLEMA.".format(period),
)
zlema = pd.Series(
ema.ewm(span=period, adjust=adjust).mean(),
name="{0} period ZLEMA".format(period),
)
return zlema
@classmethod
def WMA(cls, ohlc: DataFrame, period: int = 9, column: str = "close") -> Series:
"""
WMA stands for weighted moving average. It helps to smooth the price curve for better trend identification.
It places even greater importance on recent data than the EMA does.
:period: Specifies the number of Periods used for WMA calculation
"""
d = (period * (period + 1)) / 2 # denominator
weights = np.arange(1, period + 1)
def linear(w):
def _compute(x):
return (w * x).sum() / d
return _compute
_close = ohlc[column].rolling(period, min_periods=period)
wma = _close.apply(linear(weights), raw=True)
return pd.Series(wma, name="{0} period WMA.".format(period))
@classmethod
def HMA(cls, ohlc: DataFrame, period: int = 16) -> Series:
"""
HMA indicator is a common abbreviation of Hull Moving Average.
The average was developed by Allan Hull and is used mainly to identify the current market trend.
Unlike SMA (simple moving average) the curve of Hull moving average is considerably smoother.
Moreover, because its aim is to minimize the lag between HMA and price it does follow the price activity much closer.
It is used especially for middle-term and long-term trading.
:period: Specifies the number of Periods used for WMA calculation
"""
import math
half_length = int(period / 2)
sqrt_length = int(math.sqrt(period))
wmaf = cls.WMA(ohlc, period=half_length)
wmas = cls.WMA(ohlc, period=period)
ohlc["deltawma"] = 2 * wmaf - wmas
hma = cls.WMA(ohlc, column="deltawma", period=sqrt_length)
return pd.Series(hma, name="{0} period HMA.".format(period))
@classmethod
@inputvalidator(input_="ohlcv")
def EVWMA(cls, ohlcv: DataFrame, period: int = 20) -> Series:
"""
The eVWMA can be looked at as an approximation to the
average price paid per share in the last n periods.
:period: Specifies the number of Periods used for eVWMA calculation
"""
vol_sum = (
ohlcv["volume"].rolling(window=period).sum()
) # floating shares in last N periods
x = (vol_sum - ohlcv["volume"]) / vol_sum
y = (ohlcv["volume"] * ohlcv["close"]) / vol_sum
evwma = [0]
# evwma = (evma[-1] * (vol_sum - volume)/vol_sum) + (volume * price / vol_sum)
for x, y in zip(x.fillna(0).iteritems(), y.iteritems()):
if x[1] == 0 or y[1] == 0:
evwma.append(0)
else:
evwma.append(evwma[-1] * x[1] + y[1])
return pd.Series(
evwma[1:],
index=ohlcv.index,
name="{0} period EVWMA.".format(period),
)
@classmethod
@inputvalidator(input_="ohlcv")
def VWAP(cls, ohlcv: DataFrame) -> Series:
"""
The volume weighted average price (VWAP) is a trading benchmark used especially in pension plans.
VWAP is calculated by adding up the dollars traded for every transaction (price multiplied by number of shares traded) and then dividing
by the total shares traded for the day.
"""
return pd.Series(
((ohlcv["volume"] * cls.TP(ohlcv)).cumsum()) / ohlcv["volume"].cumsum(),
name="VWAP.",
)
@classmethod
def SMMA(
cls,
ohlc: DataFrame,
period: int = 42,
column: str = "close",
adjust: bool = True,
) -> Series:
"""The SMMA (Smoothed Moving Average) gives recent prices an equal weighting to historic prices."""
return pd.Series(
ohlc[column].ewm(alpha=1 / period, adjust=adjust).mean(), name="SMMA"
)
@classmethod
def ALMA(
cls, ohlc: DataFrame, period: int = 9, sigma: int = 6, offset: int = 0.85
) -> Series:
"""Arnaud Legoux Moving Average."""
"""dataWindow = _.last(data, period)
size = _.size(dataWindow)
m = offset * (size - 1)
s = size / sigma
sum = 0
norm = 0
for i in [size-1..0] by -1
coeff = Math.exp(-1 * (i - m) * (i - m) / 2 * s * s)
sum = sum + dataWindow[i] * coeff
norm = norm + coeff
return sum / norm"""
raise NotImplementedError
@classmethod
def MAMA(cls, ohlc: DataFrame, period: int = 16) -> Series:
"""MESA Adaptive Moving Average"""
raise NotImplementedError
@classmethod
def FRAMA(cls, ohlc: DataFrame, period: int = 16, batch: int = 10) -> Series:
"""Fractal Adaptive Moving Average
Source: http://www.stockspotter.com/Files/frama.pdf
Adopted from: https://www.quantopian.com/posts/frama-fractal-adaptive-moving-average-in-python
:period: Specifies the number of periods used for FRANA calculation
:batch: Specifies the size of batches used for FRAMA calculation
"""
assert period % 2 == 0, print("FRAMA period must be even")
c = ohlc.close.copy()
window = batch * 2
hh = c.rolling(batch).max()
ll = c.rolling(batch).min()
n1 = (hh - ll) / batch
n2 = n1.shift(batch)
hh2 = c.rolling(window).max()
ll2 = c.rolling(window).min()
n3 = (hh2 - ll2) / window
# calculate fractal dimension
D = (np.log(n1 + n2) - np.log(n3)) / np.log(2)
alp = np.exp(-4.6 * (D - 1))
alp = np.clip(alp, 0.01, 1).values
filt = c.values
for i, x in enumerate(alp):
cl = c.values[i]
if i < window:
continue
filt[i] = cl * x + (1 - x) * filt[i - 1]
return pd.Series(
filt, index=ohlc.index, name="{0} period FRAMA.".format(period)
)
@classmethod
def MACD(
cls,
ohlc: DataFrame,
period_fast: int = 12,
period_slow: int = 26,
signal: int = 9,
column: str = "close",
adjust: bool = True,
) -> DataFrame:
"""
MACD, MACD Signal and MACD difference.
The MACD Line oscillates above and below the zero line, which is also known as the centerline.
These crossovers signal that the 12-day EMA has crossed the 26-day EMA. The direction, of course, depends on the direction of the moving average cross.
Positive MACD indicates that the 12-day EMA is above the 26-day EMA. Positive values increase as the shorter EMA diverges further from the longer EMA.
This means upside momentum is increasing. Negative MACD values indicates that the 12-day EMA is below the 26-day EMA.
Negative values increase as the shorter EMA diverges further below the longer EMA. This means downside momentum is increasing.
Signal line crossovers are the most common MACD signals. The signal line is a 9-day EMA of the MACD Line.
As a moving average of the indicator, it trails the MACD and makes it easier to spot MACD turns.
A bullish crossover occurs when the MACD turns up and crosses above the signal line.
A bearish crossover occurs when the MACD turns down and crosses below the signal line.
"""
EMA_fast = pd.Series(
ohlc[column].ewm(ignore_na=False, span=period_fast, adjust=adjust).mean(),
name="EMA_fast",
)
EMA_slow = pd.Series(
ohlc[column].ewm(ignore_na=False, span=period_slow, adjust=adjust).mean(),
name="EMA_slow",
)
MACD = pd.Series(EMA_fast - EMA_slow, name="MACD")
MACD_signal = pd.Series(
MACD.ewm(ignore_na=False, span=signal, adjust=adjust).mean(), name="SIGNAL"
)
return pd.concat([MACD, MACD_signal], axis=1)
@classmethod
def PPO(
cls,
ohlc: DataFrame,
period_fast: int = 12,
period_slow: int = 26,
signal: int = 9,
column: str = "close",
adjust: bool = True,
) -> DataFrame:
"""
Percentage Price Oscillator
PPO, PPO Signal and PPO difference.
As with MACD, the PPO reflects the convergence and divergence of two moving averages.
While MACD measures the absolute difference between two moving averages, PPO makes this a relative value by dividing the difference by the slower moving average
"""
EMA_fast = pd.Series(
ohlc[column].ewm(ignore_na=False, span=period_fast, adjust=adjust).mean(),
name="EMA_fast",
)
EMA_slow = pd.Series(
ohlc[column].ewm(ignore_na=False, span=period_slow, adjust=adjust).mean(),
name="EMA_slow",
)
PPO = pd.Series(((EMA_fast - EMA_slow) / EMA_slow) * 100, name="PPO")
PPO_signal = pd.Series(
PPO.ewm(ignore_na=False, span=signal, adjust=adjust).mean(), name="SIGNAL"
)
PPO_histo = pd.Series(PPO - PPO_signal, name="HISTO")
return pd.concat([PPO, PPO_signal, PPO_histo], axis=1)
@classmethod
@inputvalidator(input_="ohlcv")
def VW_MACD(
cls,
ohlcv: DataFrame,
period_fast: int = 12,
period_slow: int = 26,
signal: int = 9,
column: str = "close",
adjust: bool = True,
) -> DataFrame:
""" "Volume-Weighted MACD" is an indicator that shows how a volume-weighted moving average can be used to calculate moving average convergence/divergence (MACD).
This technique was first used by Buff Dormeier, CMT, and has been written about since at least 2002.
"""
vp = ohlcv["volume"] * ohlcv[column]
_fast = pd.Series(
(vp.ewm(ignore_na=False, span=period_fast, adjust=adjust).mean())
/ (
ohlcv["volume"]
.ewm(ignore_na=False, span=period_fast, adjust=adjust)
.mean()
),
name="_fast",
)
_slow = pd.Series(
(vp.ewm(ignore_na=False, span=period_slow, adjust=adjust).mean())
/ (
ohlcv["volume"]
.ewm(ignore_na=False, span=period_slow, adjust=adjust)
.mean()
),
name="_slow",
)
MACD = pd.Series(_fast - _slow, name="MACD")
MACD_signal = pd.Series(
MACD.ewm(ignore_na=False, span=signal, adjust=adjust).mean(), name="SIGNAL"
)
return pd.concat([MACD, MACD_signal], axis=1)
@classmethod
@inputvalidator(input_="ohlcv")
def EV_MACD(
cls,
ohlcv: DataFrame,
period_fast: int = 20,
period_slow: int = 40,
signal: int = 9,
adjust: bool = True,
) -> DataFrame:
"""
Elastic Volume Weighted MACD is a variation of standard MACD,
calculated using two EVWMA's.
:period_slow: Specifies the number of Periods used for the slow EVWMA calculation
:period_fast: Specifies the number of Periods used for the fast EVWMA calculation
:signal: Specifies the number of Periods used for the signal calculation
"""
evwma_slow = cls.EVWMA(ohlcv, period_slow)
evwma_fast = cls.EVWMA(ohlcv, period_fast)
MACD = pd.Series(evwma_fast - evwma_slow, name="MACD")
MACD_signal = pd.Series(
MACD.ewm(ignore_na=False, span=signal, adjust=adjust).mean(), name="SIGNAL"
)
return pd.concat([MACD, MACD_signal], axis=1)
@classmethod
def MOM(cls, ohlc: DataFrame, period: int = 10, column: str = "close") -> Series:
"""Market momentum is measured by continually taking price differences for a fixed time interval.
To construct a 10-day momentum line, simply subtract the closing price 10 days ago from the last closing price.
This positive or negative value is then plotted around a zero line."""
return pd.Series(ohlc[column].diff(period), name="MOM".format(period))
@classmethod
def ROC(cls, ohlc: DataFrame, period: int = 12, column: str = "close") -> Series:
"""The Rate-of-Change (ROC) indicator, which is also referred to as simply Momentum,
is a pure momentum oscillator that measures the percent change in price from one period to the next.
The ROC calculation compares the current price with the price “n” periods ago.
"""
return pd.Series(
(ohlc[column].diff(period) / ohlc[column].shift(period)) * 100, name="ROC"
)
@classmethod
def VBM(
cls,
ohlc: DataFrame,
roc_period: int = 12,
atr_period: int = 26,
column: str = "close",
) -> Series:
"""The Volatility-Based-Momentum (VBM) indicator, The calculation for a volatility based momentum (VBM)
indicator is very similar to ROC, but divides by the security’s historical volatility instead.
The average true range indicator (ATR) is used to compute historical volatility.
VBM(n,v) = (Close — Close n periods ago) / ATR(v periods)
"""
return pd.Series(
(
(ohlc[column].diff(roc_period) - ohlc[column].shift(roc_period))
/ cls.ATR(ohlc, atr_period)
),
name="VBM",
)
@classmethod
def RSI(
cls,
ohlc: DataFrame,
period: int = 14,
column: str = "close",
adjust: bool = True,
) -> Series:
"""Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements.
RSI oscillates between zero and 100. Traditionally, and according to Wilder, RSI is considered overbought when above 70 and oversold when below 30.
Signals can also be generated by looking for divergences, failure swings and centerline crossovers.
RSI can also be used to identify the general trend."""
## get the price diff
delta = ohlc[column].diff()
## positive gains (up) and negative gains (down) Series
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
# EMAs of ups and downs
_gain = up.ewm(alpha=1.0 / period, adjust=adjust).mean()
_loss = down.abs().ewm(alpha=1.0 / period, adjust=adjust).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="{0} period RSI".format(period))
@classmethod
def IFT_RSI(
cls,
ohlc: DataFrame,
column: str = "close",
rsi_period: int = 5,
wma_period: int = 9,
) -> Series:
"""Modified Inverse Fisher Transform applied on RSI.
Suggested method to use any IFT indicator is to buy when the indicator crosses over –0.5 or crosses over +0.5
if it has not previously crossed over –0.5 and to sell short when the indicators crosses under +0.5 or crosses under –0.5
if it has not previously crossed under +0.5."""
# v1 = .1 * (rsi - 50)
v1 = pd.Series(0.1 * (cls.RSI(ohlc, rsi_period) - 50), name="v1")
# v2 = WMA(wma_period) of v1
d = (wma_period * (wma_period + 1)) / 2 # denominator
weights = np.arange(1, wma_period + 1)
def linear(w):
def _compute(x):
return (w * x).sum() / d
return _compute
_wma = v1.rolling(wma_period, min_periods=wma_period)
v2 = _wma.apply(linear(weights), raw=True)
ift = pd.Series(((v2**2 - 1) / (v2**2 + 1)), name="IFT_RSI")
return ift
@classmethod
def SWI(cls, ohlc: DataFrame, period: int = 16) -> Series:
"""Sine Wave indicator"""
raise NotImplementedError
@classmethod
def DYMI(
cls, ohlc: DataFrame, column: str = "close", adjust: bool = True
) -> Series:
"""
The Dynamic Momentum Index is a variable term RSI. The RSI term varies from 3 to 30. The variable
time period makes the RSI more responsive to short-term moves. The more volatile the price is,
the shorter the time period is. It is interpreted in the same way as the RSI, but provides signals earlier.
Readings below 30 are considered oversold, and levels over 70 are considered overbought. The indicator
oscillates between 0 and 100.
https://www.investopedia.com/terms/d/dynamicmomentumindex.asp
"""
def _get_time(close):
# Value available from 14th period
sd = close.rolling(5).std()
asd = sd.rolling(10).mean()
v = sd / asd
t = 14 / v.round()
t[t.isna()] = 0
t = t.map(lambda x: int(min(max(x, 5), 30)))
return t
def _dmi(index):
time = t.iloc[index]
if (index - time) < 0:
subset = ohlc.iloc[0:index]
else:
subset = ohlc.iloc[(index - time) : index]
return cls.RSI(subset, period=time, adjust=adjust).values[-1]
dates = Series(ohlc.index)
periods = Series(range(14, len(dates)), index=ohlc.index[14:].values)
t = _get_time(ohlc[column])
return periods.map(lambda x: _dmi(x))
@classmethod
def TR(cls, ohlc: DataFrame) -> Series:
"""True Range is the maximum of three price ranges.
Most recent period's high minus the most recent period's low.
Absolute value of the most recent period's high minus the previous close.
Absolute value of the most recent period's low minus the previous close."""
TR1 = pd.Series(ohlc["high"] - ohlc["low"]).abs() # True Range = High less Low
TR2 = pd.Series(
ohlc["high"] - ohlc["close"].shift()
).abs() # True Range = High less Previous Close
TR3 = pd.Series(
ohlc["close"].shift() - ohlc["low"]
).abs() # True Range = Previous Close less Low
_TR = pd.concat([TR1, TR2, TR3], axis=1)
_TR["TR"] = _TR.max(axis=1)
return pd.Series(_TR["TR"], name="TR")
@classmethod
def ATR(cls, ohlc: DataFrame, period: int = 14) -> Series:
"""Average True Range is moving average of True Range."""
TR = cls.TR(ohlc)
return pd.Series(
TR.rolling(center=False, window=period).mean(),
name="{0} period ATR".format(period),
)
@classmethod
def SAR(cls, ohlc: DataFrame, af: int = 0.02, amax: int = 0.2) -> Series:
"""SAR stands for “stop and reverse,” which is the actual indicator used in the system.
SAR trails price as the trend extends over time. The indicator is below prices when prices are rising and above prices when prices are falling.
In this regard, the indicator stops and reverses when the price trend reverses and breaks above or below the indicator.
"""
high, low = ohlc.high, ohlc.low
# Starting values
sig0, xpt0, af0 = True, high[0], af
_sar = [low[0] - (high - low).std()]
for i in range(1, len(ohlc)):
sig1, xpt1, af1 = sig0, xpt0, af0
lmin = min(low[i - 1], low[i])
lmax = max(high[i - 1], high[i])
if sig1:
sig0 = low[i] > _sar[-1]
xpt0 = max(lmax, xpt1)
else:
sig0 = high[i] >= _sar[-1]
xpt0 = min(lmin, xpt1)
if sig0 == sig1:
sari = _sar[-1] + (xpt1 - _sar[-1]) * af1
af0 = min(amax, af1 + af)
if sig0:
af0 = af0 if xpt0 > xpt1 else af1
sari = min(sari, lmin)
else:
af0 = af0 if xpt0 < xpt1 else af1
sari = max(sari, lmax)
else:
af0 = af
sari = xpt0
_sar.append(sari)
return pd.Series(_sar, index=ohlc.index)
@classmethod
def PSAR(cls, ohlc: DataFrame, iaf: int = 0.02, maxaf: int = 0.2) -> DataFrame:
"""
The parabolic SAR indicator, developed by J. Wells Wilder, is used by traders to determine trend direction and potential reversals in price.
The indicator uses a trailing stop and reverse method called "SAR," or stop and reverse, to identify suitable exit and entry points.
Traders also refer to the indicator as the parabolic stop and reverse, parabolic SAR, or PSAR.
https://www.investopedia.com/terms/p/parabolicindicator.asp
https://virtualizedfrog.wordpress.com/2014/12/09/parabolic-sar-implementation-in-python/
"""
length = len(ohlc)
high, low, close = ohlc.high, ohlc.low, ohlc.close
psar = close[0 : len(close)]
psarbull = [None] * length
psarbear = [None] * length
bull = True
af = iaf
hp = high[0]
lp = low[0]
for i in range(2, length):
if bull:
psar[i] = psar[i - 1] + af * (hp - psar[i - 1])
else:
psar[i] = psar[i - 1] + af * (lp - psar[i - 1])
reverse = False
if bull:
if low[i] < psar[i]:
bull = False
reverse = True
psar[i] = hp
lp = low[i]
af = iaf
else:
if high[i] > psar[i]:
bull = True
reverse = True
psar[i] = lp
hp = high[i]
af = iaf
if not reverse:
if bull:
if high[i] > hp:
hp = high[i]
af = min(af + iaf, maxaf)
if low[i - 1] < psar[i]:
psar[i] = low[i - 1]
if low[i - 2] < psar[i]:
psar[i] = low[i - 2]
else:
if low[i] < lp:
lp = low[i]
af = min(af + iaf, maxaf)
if high[i - 1] > psar[i]:
psar[i] = high[i - 1]
if high[i - 2] > psar[i]:
psar[i] = high[i - 2]
if bull:
psarbull[i] = psar[i]
else:
psarbear[i] = psar[i]
psar = pd.Series(psar, name="psar", index=ohlc.index)
psarbear = pd.Series(psarbull, name="psarbear", index=ohlc.index)
psarbull = pd.Series(psarbear, name="psarbull", index=ohlc.index)
return pd.concat([psar, psarbull, psarbear], axis=1)
@classmethod
def BBANDS(
cls,
ohlc: DataFrame,
period: int = 20,
MA: Series = None,
column: str = "close",
std_multiplier: float = 2,
) -> DataFrame:
"""
Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average.
Volatility is based on the standard deviation, which changes as volatility increases and decreases.
The bands automatically widen when volatility increases and narrow when volatility decreases.
This method allows input of some other form of moving average like EMA or KAMA around which BBAND will be formed.
Pass desired moving average as <MA> argument. For example BBANDS(MA=TA.KAMA(20)).
"""
std = ohlc[column].rolling(window=period).std()
if not isinstance(MA, pd.core.series.Series):
middle_band = pd.Series(cls.SMA(ohlc, period), name="BB_MIDDLE")
else:
middle_band = pd.Series(MA, name="BB_MIDDLE")
upper_bb = pd.Series(middle_band + (std_multiplier * std), name="BB_UPPER")
lower_bb = pd.Series(middle_band - (std_multiplier * std), name="BB_LOWER")
return pd.concat([upper_bb, middle_band, lower_bb], axis=1)
@classmethod
def MOBO(
cls,
ohlc: DataFrame,
period: int = 10,
std_multiplier: float = 0.8,
column: str = "close",
) -> DataFrame:
"""
"MOBO bands are based on a zone of 0.80 standard deviation with a 10 period look-back"
If the price breaks out of the MOBO band it can signify a trend move or price spike
Contains 42% of price movements(noise) within bands.
"""
BB = TA.BBANDS(ohlc, period=10, std_multiplier=0.8, column=column)
return BB
@classmethod
def BBWIDTH(
cls, ohlc: DataFrame, period: int = 20, MA: Series = None, column: str = "close"
) -> Series:
"""Bandwidth tells how wide the Bollinger Bands are on a normalized basis."""
BB = TA.BBANDS(ohlc, period, MA, column)
return pd.Series(
(BB["BB_UPPER"] - BB["BB_LOWER"]) / BB["BB_MIDDLE"],