-
Notifications
You must be signed in to change notification settings - Fork 299
/
stockstats.py
2010 lines (1643 loc) · 65.5 KB
/
stockstats.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
# Copyright (c) 2016, Cedric Zhuang
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of disclaimer nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
import functools
import itertools
import re
from typing import Optional, Callable, Union
import numpy as np
import pandas as pd
__author__ = 'Cedric Zhuang'
from numpy.lib.stride_tricks import as_strided
class StockStatsError(Exception):
pass
_dft_windows = {
# sort alphabetically
'ao': (5, 34),
'aroon': 25,
'atr': 14,
'boll': 20,
'cci': 14,
'change': 1,
'chop': 14,
'cmo': 14,
'coppock': (10, 11, 14),
'cr': 26,
'cti': 12,
'dma': (10, 50),
'eri': 13,
'eribear': 13,
'eribull': 13,
'ichimoku': (9, 26, 52),
'inertia': (20, 14),
'ftr': 9,
'kama': (10, 5, 34), # window, fast, slow
'kdjd': 9,
'kdjj': 9,
'kdjk': 9,
'ker': 10,
'macd': (12, 26, 9), # short, long, signal
'mfi': 14,
'ndi': 14,
'pdi': 14,
'pgo': 14,
'ppo': (12, 26, 9), # short, long, signal
'pvo': (12, 26, 9), # short, long, signal
'psl': 12,
'qqe': (14, 5), # rsi, rsi ema
'rsi': 14,
'rsv': 9,
'rvgi': 14,
'stochrsi': 14,
'supertrend': 14,
'tema': 5,
'trix': 12,
'wr': 14,
'wt': (10, 21),
'vr': 26,
'vwma': 14,
'num': 0,
}
def set_dft_window(name: str, windows: Union[int, tuple[int, ...]]):
ret = _dft_windows.get(name)
_dft_windows[name] = windows
return ret
_dft_column = {
# sort alphabetically
'cti': 'close',
'dma': 'close',
'kama': 'close',
'ker': 'close',
'psl': 'close',
'tema': 'close',
'trix': 'close',
}
def dft_windows(name: str) -> Optional[str]:
if name not in _dft_windows:
return None
dft = _dft_windows[name]
if isinstance(dft, int):
return str(dft)
return ','.join(map(str, dft))
def dft_column(name: str) -> Optional[str]:
if name not in _dft_column:
return None
return _dft_column[name]
class _Meta:
def __init__(self,
name,
*,
column=None,
windows=None):
self._name = name
self._column = column
self._windows = windows
self._dft_column = dft_column(name)
self._dft_windows = dft_windows(name)
@staticmethod
def _process_segment(windows):
if '~' in windows:
start, end = windows.split('~')
shifts = range(int(start), int(end) + 1)
else:
shifts = [int(windows)]
return shifts
@property
def ints(self) -> list[int]:
items = map(self._process_segment, self.windows.split(','))
return list(itertools.chain(*items))
@property
def int(self) -> int:
numbers = self.ints
if len(numbers) != 1:
raise StockStatsError('only accept 1 number')
return numbers[0]
def _get_int(self, i):
numbers = self.ints
if len(numbers) < i + 1:
# try the defaults
dft_numbers = _dft_windows[self._name]
if len(dft_numbers) > i:
return dft_numbers[i]
raise StockStatsError(f'not enough ints, need {i + 1}')
return self.ints[i]
@property
def int0(self) -> int:
return self._get_int(0)
@property
def int1(self) -> int:
return self._get_int(1)
@property
def int2(self) -> int:
return self._get_int(2)
@property
def positive_int(self) -> int:
ret = self.int
if ret <= 0:
raise StockStatsError('window must be greater than 0')
return ret
@property
def windows(self):
if self._windows is None:
return self._dft_windows
return self._windows
@property
def column(self):
if self._column is None:
return self._dft_column
return self._column
@property
def name(self):
if self._windows is None and self._column is None:
return self._name
if self._column is None:
return f'{self._name}_{self._windows}'
return f'{self.column}_{self.windows}_{self._name}'
def set_name(self, name: str):
self._name = name
return self
def name_ex(self, ex):
ret = f'{self._name}{ex}'
if self._windows is None:
return ret
return f'{ret}_{self.windows}'
def _call_handler(handler: Callable):
meta = _Meta(handler.__name__[5:])
return handler(meta)
def wrap(df, index_column=None):
""" wraps a pandas DataFrame to StockDataFrame
:param df: pandas DataFrame
:param index_column: the name of the index column, default to ``date``
:return: an object of StockDataFrame
"""
return StockDataFrame.retype(df, index_column)
def unwrap(sdf):
""" convert a StockDataFrame back to a pandas DataFrame """
return pd.DataFrame(sdf)
class StockDataFrame(pd.DataFrame):
# Start of options.
KDJ_PARAM = (2.0 / 3.0, 1.0 / 3.0)
BOLL_STD_TIMES = 2
DX_SMMA = 14
ADX_EMA = 6
ADXR_EMA = 6
CR_MA = (5, 10, 20)
SUPERTREND_MUL = 3
# End of options
@property
def high(self) -> pd.Series:
return self['high']
@property
def low(self) -> pd.Series:
return self['low']
@property
def close(self) -> pd.Series:
return self['close']
@property
def open(self) -> pd.Series:
return self['open']
def _get_change(self, meta: _Meta):
""" Get the percentage change column
It's an alias for ROC
:return: result series
"""
self[meta.name] = self.roc(self['close'], meta.int)
def _get_p(self, meta: _Meta):
""" get the permutation of specified range
example:
index x x_-2,-1_p
0 1 NaN
1 -1 NaN
2 3 2 (0.x > 0, and assigned to weight 2)
3 5 1 (2.x > 0, and assigned to weight 1)
4 1 3
"""
# initialize the column if not
_ = self.get(meta.column)
shifts = meta.ints[::-1]
indices: Optional[pd.Series] = None
count = 0
for shift in shifts:
shifted = self.shift(-shift)
index = (shifted[meta.column] > 0) * (2 ** count)
if indices is None:
indices = index
else:
indices += index
count += 1
if indices is not None:
cp = indices.copy()
self.set_nan(cp, shifts)
self[meta.name] = cp
@classmethod
def to_ints(cls, shifts):
items = map(cls._process_shifts_segment, shifts.split(','))
return sorted(list(set(itertools.chain(*items))))
@classmethod
def to_int(cls, shifts):
numbers = cls.to_ints(shifts)
if len(numbers) != 1:
raise IndexError("only accept 1 number.")
return numbers[0]
@staticmethod
def _process_shifts_segment(shift_segment):
if '~' in shift_segment:
start, end = shift_segment.split('~')
shifts = range(int(start), int(end) + 1)
else:
shifts = [int(shift_segment)]
return shifts
@classmethod
def set_nan(cls, pd_obj, shift):
try:
iter(shift)
max_shift = max(shift)
min_shift = min(shift)
cls._set_nan_of_single_shift(pd_obj, max_shift)
cls._set_nan_of_single_shift(pd_obj, min_shift)
except TypeError:
# shift is not iterable
cls._set_nan_of_single_shift(pd_obj, shift)
@staticmethod
def _set_nan_of_single_shift(pd_obj, shift):
val = np.nan
if shift > 0:
pd_obj.iloc[-shift:] = val
elif shift < 0:
pd_obj.iloc[:-shift] = val
def _get_r(self, meta: _Meta):
""" Get rate of change of column
Note this function is different to the roc function.
negative values meaning data in the past,
positive values meaning data in the future.
"""
shift = -meta.int
self[meta.name] = self.roc(self[meta.column], shift)
@staticmethod
def s_shift(series: pd.Series, window: int):
""" Shift the series
When window is negative, shift the past period to current.
Fill the gap with the first data available.
When window is positive, shift the future period to current.
Fill the gap with last data available.
:param series: the series to shift
:param window: number of periods to shift
:return: the shifted series with filled gap
"""
ret = series.shift(-window)
if window < 0:
ret.iloc[:-window] = series.iloc[0]
elif window > 0:
ret.iloc[-window:] = series.iloc[-1]
return ret
def _get_s(self, meta: _Meta):
""" Get the column shifted by periods
Note this method is different to the shift method of pandas.
negative values meaning data in the past,
positive values meaning data in the future.
"""
self[meta.name] = self.s_shift(self[meta.column], meta.int)
def _get_log_ret(self, _: _Meta):
close = self['close']
self['log-ret'] = np.log(close / self.s_shift(close, -1))
def _get_c(self, meta: _Meta) -> pd.Series:
""" get the count of column in range (shifts)
example: change_20_c
:return: result series
"""
rolled = self._rolling(self[meta.column], meta.int)
counts = rolled.apply(np.count_nonzero, raw=True)
self[meta.name] = counts
return counts
def _get_fc(self, meta: _Meta) -> pd.Series:
""" get the count of column in range of future (shifts)
example: change_20_fc
:return: result series
"""
shift = meta.int
reversed_series = self[meta.column][::-1]
rolled = self._rolling(reversed_series, shift)
reversed_counts = rolled.apply(np.count_nonzero, raw=True)
counts = reversed_counts[::-1]
self[meta.name] = counts
return counts
def _shifted_columns(self,
column: pd.Series,
shifts: list[int]) -> pd.DataFrame:
# initialize the column if not
col = self.get(column)
res = pd.DataFrame()
for i in shifts:
res[int(i)] = self.s_shift(col, i).values
return res
def _get_max(self, meta: _Meta):
column = meta.column
shifts = meta.ints
cols = self._shifted_columns(column, shifts)
self[meta.name] = cols.max(axis=1).values
def _get_min(self, meta: _Meta):
column = meta.column
shifts = meta.ints
cols = self._shifted_columns(column, shifts)
self[meta.name] = cols.min(axis=1).values
def _rsv(self, window):
low_min = self.mov_min(self['low'], window)
high_max = self.mov_max(self['high'], window)
cv = (self['close'] - low_min) / (high_max - low_min)
cv.fillna(0.0, inplace=True)
return cv * 100
def _get_rsv(self, meta: _Meta):
""" Calculate the RSV (Raw Stochastic Value) within N periods
This value is essential for calculating KDJs
Current day is included in N
"""
self[meta.name] = self._rsv(meta.int)
def _rsi(self, window) -> pd.Series:
change = self.close.diff()
change.iloc[0] = 0
close_pm = (change + change.abs()) / 2
close_nm = (-change + change.abs()) / 2
p_ema = self.smma(close_pm, window)
n_ema = self.smma(close_nm, window)
rs = p_ema / n_ema
return 100 - 100 / (1.0 + rs)
def _get_rsi(self, meta: _Meta):
""" Calculate the RSI (Relative Strength Index) within N periods
calculated based on the formula at:
https://en.wikipedia.org/wiki/Relative_strength_index
"""
self[meta.name] = self._rsi(meta.int)
def _get_stochrsi(self, meta: _Meta):
""" Calculate the Stochastic RSI
calculated based on the formula at:
https://www.investopedia.com/terms/s/stochrsi.asp
"""
window = meta.int
rsi = self._rsi(window)
rsi_min = self.mov_min(rsi, window)
rsi_max = self.mov_max(rsi, window)
cv = (rsi - rsi_min) / (rsi_max - rsi_min)
self[meta.name] = cv * 100
def _wt1(self, n1: int, n2: int) -> pd.Series:
""" wave trand 1
n1: period of EMA on typical price
n2: period of EMA
"""
tp = self._tp()
esa = self.ema(tp, n1)
d = self.ema((tp - esa).abs(), n1)
ci = (tp - esa) / (0.015 * d)
return self.ema(ci, n2)
def _get_wt1(self, meta: _Meta):
self[meta.name] = self._wt1(meta.int0, meta.int1)
def _get_wt2(self, meta: _Meta):
wt1 = self._wt1(meta.int0, meta.int1)
self[meta.name] = self.sma(wt1, 4)
def _get_wt(self, meta: _Meta):
""" Calculate LazyBear's Wavetrend
Check the algorithm described below:
https://medium.com/@samuel.mcculloch/lets-take-a-look-at-wavetrend-with-crosses-lazybear-s-indicator-2ece1737f72f
"""
tci = self._wt1(meta.int0, meta.int1)
self[meta.name_ex('1')] = tci
self[meta.name_ex('2')] = self.sma(tci, 4)
@staticmethod
def smma(series, window):
return series.ewm(
ignore_na=False,
alpha=1.0 / window,
min_periods=0,
adjust=True).mean()
def _get_smma(self, meta: _Meta):
""" get smoothed moving average """
self[meta.name] = self.smma(self[meta.column], meta.int)
def _get_trix(self, meta: _Meta):
""" Triple Exponential Average
https://www.investopedia.com/articles/technical/02/092402.asp
"""
window = meta.int
single = self.ema(self[meta.column], window)
double = self.ema(single, window)
triple = self.ema(double, window)
prev_triple = self.s_shift(triple, -1)
triple_change = self._delta(triple, -1)
self[meta.name] = triple_change * 100 / prev_triple
def _get_tema(self, meta: _Meta):
""" Another implementation for triple ema
Check the algorithm described below:
https://www.forextraders.com/forex-education/forex-technical-analysis/triple-exponential-moving-average-the-tema-indicator/
"""
window = meta.int
single = self.ema(self[meta.column], window)
double = self.ema(single, window)
triple = self.ema(double, window)
self[meta.name] = 3.0 * single - 3.0 * double + triple
def _get_wr(self, meta: _Meta):
""" Williams Overbought/Oversold Index
Definition: https://www.investopedia.com/terms/w/williamsr.asp
WMS=[(Hn—Ct)/(Hn—Ln)] × -100
Ct - the close price
Hn - N periods high
Ln - N periods low
"""
window = meta.int
ln = self.mov_min(self['low'], window)
hn = self.mov_max(self['high'], window)
self[meta.name] = (hn - self['close']) / (hn - ln) * -100
def _get_cci(self, meta: _Meta):
""" Commodity Channel Index
CCI = (Typical Price - 20-period SMA of TP) / (.015 x Mean Deviation)
* when amount is not available:
Typical Price (TP) = (High + Low + Close)/3
* when amount is available:
Typical Price (TP) = Amount / Volume
TP is also implemented as 'middle'.
"""
window = meta.int
tp = self._tp()
tp_sma = self.sma(tp, window)
mad = self._mad(tp, window)
self[meta.name] = (tp - tp_sma) / (.015 * mad)
def _tr(self):
prev_close = self.s_shift(self['close'], -1)
high = self['high']
low = self['low']
c1 = high - low
c2 = (high - prev_close).abs()
c3 = (low - prev_close).abs()
return pd.concat((c1, c2, c3), axis=1).max(axis=1)
def _get_tr(self, meta: _Meta):
""" True Range of the trading
TR is a measure of volatility of a High-Low-Close series
tr = max[(high - low), abs(high - close_prev), abs(low - close_prev)]
:return: None
"""
self[meta.name] = self._tr()
def _get_supertrend(self, meta: _Meta):
""" Supertrend
Supertrend indicator shows trend direction.
It provides buy or sell indicators.
https://medium.com/codex/step-by-step-implementation-of-the-supertrend-indicator-in-python-656aa678c111
"""
window = meta.int
high = self['high']
low = self['low']
close = self['close']
m_atr = self.SUPERTREND_MUL * self._atr(window)
hl_avg = (high + low) / 2.0
# basic upper band
b_ub = list(hl_avg + m_atr)
# basic lower band
b_lb = list(hl_avg - m_atr)
size = len(close)
ub = np.empty(size, dtype=np.float64)
lb = np.empty(size, dtype=np.float64)
st = np.empty(size, dtype=np.float64)
close = list(close)
for i in range(size):
if i == 0:
ub[i] = b_ub[i]
lb[i] = b_lb[i]
if close[i] <= ub[i]:
st[i] = ub[i]
else:
st[i] = lb[i]
continue
last_close = close[i - 1]
curr_close = close[i]
last_ub = ub[i - 1]
last_lb = lb[i - 1]
last_st = st[i - 1]
curr_b_ub = b_ub[i]
curr_b_lb = b_lb[i]
# calculate current upper band
if curr_b_ub < last_ub or last_close > last_ub:
ub[i] = curr_b_ub
else:
ub[i] = last_ub
# calculate current lower band
if curr_b_lb > last_lb or last_close < last_lb:
lb[i] = curr_b_lb
else:
lb[i] = last_lb
# calculate supertrend
if last_st == last_ub:
if curr_close <= ub[i]:
st[i] = ub[i]
else:
st[i] = lb[i]
elif last_st == last_lb:
if curr_close > lb[i]:
st[i] = lb[i]
else:
st[i] = ub[i]
self[f'{meta.name}_ub'] = ub
self[f'{meta.name}_lb'] = lb
self[f'{meta.name}'] = st
def _get_aroon(self, meta: _Meta):
""" Aroon Oscillator
The Aroon Oscillator measures the strength of a trend and
the likelihood that it will continue.
The default window is 25.
* Aroon Oscillator = Aroon Up - Aroon Down
* Aroon Up = 100 * (n - periods since n-period high) / n
* Aroon Down = 100 * (n - periods since n-period low) / n
* n = window size
"""
window = meta.int
def _window_pct(s):
n = float(window)
return (n - (n - (s + 1))) / n * 100
high_since = self._rolling(
self['high'], window).apply(np.argmax, raw=True)
low_since = self._rolling(
self['low'], window).apply(np.argmin, raw=True)
aroon_up = _window_pct(high_since)
aroon_down = _window_pct(low_since)
self[meta.name] = aroon_up - aroon_down
def _get_z(self, meta: _Meta):
""" Z score
Z-score is a statistical measurement that describes a value's
relationship to the mean of a group of values.
The statistical formula for a value's z-score is calculated using
the following formula:
z = ( x - μ ) / σ
Where:
* z = Z-score
* x = the value being evaluated
* μ = the mean
* σ = the standard deviation
"""
window = meta.int
col = self[meta.column]
mean = self.sma(col, window)
std = self.mov_std(col, window)
value = (col - mean) / std
if len(value) > 1:
value.iloc[0] = value.iloc[1]
self[meta.name] = value
def _atr(self, window):
tr = self._tr()
return self.smma(tr, window)
def _get_atr(self, meta: _Meta):
""" Average True Range
The average true range is an N-day smoothed moving average (SMMA) of
the true range values. Default to 14 periods.
https://en.wikipedia.org/wiki/Average_true_range
"""
window = meta.int
self[meta.name] = self._atr(window)
def _get_dma(self, meta: _Meta):
""" Difference of Moving Average
default to 10 and 50.
:return: None
"""
fast = meta.int0
slow = meta.int1
col = self[meta.column]
diff = self.sma(col, fast) - self.sma(col, slow)
self[meta.name] = diff
def _get_dmi(self, _: _Meta):
""" get the default setting for DMI
including:
+DI: 14 periods SMMA of +DM,
-DI: 14 periods SMMA of -DM,
DX: based on +DI and -DI
ADX: 6 periods SMMA of DX
:return:
"""
self['dx'] = self._dx(self.DX_SMMA)
self['adx'] = self.ema(self['dx'], self.ADX_EMA)
self['adxr'] = self.ema(self['adx'], self.ADXR_EMA)
def _get_pdm_ndm(self, window):
hd = self._col_diff('high')
ld = -self._col_diff('low')
p = ((hd > 0) & (hd > ld)) * hd
n = ((ld > 0) & (ld > hd)) * ld
if window > 1:
p = self.smma(p, window)
n = self.smma(n, window)
return p, n
def _pdm(self, window):
ret, _ = self._get_pdm_ndm(window)
return ret
def _ndm(self, window):
_, ret = self._get_pdm_ndm(window)
return ret
def _get_pdm(self, meta: _Meta):
""" +DM, positive directional moving
If window is not 1, calculate the SMMA of +DM
"""
self[meta.name] = self._pdm(meta.int)
def _get_ndm(self, meta: _Meta):
""" -DM, negative directional moving accumulation
If window is not 1, return the SMA of -DM.
"""
self[meta.name] = self._ndm(meta.int)
def _get_vr(self, meta: _Meta):
""" VR - Volume Variation Index """
window = meta.int
idx = self.index
gt_zero = np.where(self['change'] > 0, self['volume'], 0)
av = pd.Series(gt_zero, index=idx)
avs = self.mov_sum(av, window)
lt_zero = np.where(self['change'] < 0, self['volume'], 0)
bv = pd.Series(lt_zero, index=idx)
bvs = self.mov_sum(bv, window)
eq_zero = np.where(self['change'] == 0, self['volume'], 0)
cv = pd.Series(eq_zero, index=idx)
cvs = self.mov_sum(cv, window)
self[meta.name] = (avs + cvs / 2) / (bvs + cvs / 2) * 100
def _get_pdi_ndi(self, window):
pdm, ndm = self._get_pdm_ndm(window)
atr = self._atr(window)
pdi = pdm / atr * 100
ndi = ndm / atr * 100
return pdi, ndi
def _get_pdi(self, meta: _Meta):
""" +DI, positive directional moving index """
pdi, _ = self._get_pdi_ndi(meta.int)
self[meta.name] = pdi
return pdi
def _get_ndi(self, meta: _Meta):
""" -DI, negative directional moving index """
_, ndi = self._get_pdi_ndi(meta.int)
self[meta.name] = ndi
return ndi
def _dx(self, window):
pdi, mdi = self._get_pdi_ndi(window)
return abs(pdi - mdi) / (pdi + mdi) * 100
def _get_dx(self, meta: _Meta):
self[meta.name] = self._dx(meta.int)
def _get_cr(self, meta: _Meta):
""" Energy Index (Intermediate Willingness Index)
https://support.futunn.com/en/topic167/?lang=en-us
Use the relationship between the highest price, the lowest price and
yesterday's middle price to reflect the market's willingness to buy
and sell.
"""
window = meta.int
middle = self._tp()
last_middle = self.s_shift(middle, -1)
ym = self.s_shift(middle, -1)
high = self['high']
low = self['low']
p1_m = pd.concat((last_middle, high), axis=1).min(axis=1)
p2_m = pd.concat((last_middle, low), axis=1).min(axis=1)
p1 = self.mov_sum(high - p1_m, window)
p2 = self.mov_sum(ym - p2_m, window)
name = meta.name
self[name] = cr = p1 / p2 * 100
self[f'{name}-ma1'] = self._shifted_cr_sma(cr, self.CR_MA[0])
self[f'{name}-ma2'] = self._shifted_cr_sma(cr, self.CR_MA[1])
self[f'{name}-ma3'] = self._shifted_cr_sma(cr, self.CR_MA[2])
def _shifted_cr_sma(self, cr, window):
cr_sma = self.sma(cr, window)
return self.s_shift(cr_sma, -int(window / 2.5 + 1))
def _tp(self):
if 'amount' in self:
return self['amount'] / self['volume']
return (self['close'] + self['high'] + self['low']).divide(3.0)
def _get_tp(self, meta: _Meta):
self[meta.name] = self._tp()
def _get_middle(self, meta: _Meta):
self[meta.name] = self._tp()
def _calc_kd(self, column):
param0, param1 = self.KDJ_PARAM
k = 50.0
# noinspection PyTypeChecker
for i in param1 * column:
k = param0 * k + i
yield k
def _get_kdjk(self, meta: _Meta):
""" Get the K of KDJ
K = 2/3 × (prev. K) +1/3 × (curr. RSV)
2/3 and 1/3 are the smooth parameters.
"""
window = meta.int
rsv = self._rsv(window)
self[meta.name] = list(self._calc_kd(rsv))
def _get_kdjd(self, meta: _Meta):
""" Get the D of KDJ
D = 2/3 × (prev. D) +1/3 × (curr. K)
2/3 and 1/3 are the smooth parameters.
"""
k_column = meta.name.replace('kdjd', 'kdjk')
self[meta.name] = list(self._calc_kd(self.get(k_column)))
def _get_kdjj(self, meta: _Meta):
""" Get the J of KDJ
J = 3K-2D
"""
k_column = meta.name.replace('kdjj', 'kdjk')
d_column = meta.name.replace('kdjj', 'kdjd')
self[meta.name] = 3 * self[k_column] - 2 * self[d_column]
@staticmethod
def _delta(series, window):
return series.diff(-window).fillna(0.0)
def _get_d(self, meta: _Meta):
self[meta.name] = self._delta(self[meta.column], meta.int)
@classmethod
def mov_min(cls, series, size):
return cls._rolling(series, size).min()
@classmethod
def mov_max(cls, series, size):
return cls._rolling(series, size).max()
@classmethod
def mov_sum(cls, series, size):
return cls._rolling(series, size).sum()
@classmethod
def sma(cls, series, size):
return cls._rolling(series, size).mean()
@staticmethod
def roc(series, size):
ret = series.diff(size) / series.shift(size)
if size < 0:
ret.iloc[size:] = 0
else:
ret.iloc[:size] = 0
return ret * 100
@classmethod
def _mad(cls, series, window):
""" Mean Absolute Deviation
:param series: Series
:param window: number of periods
:return: Series
"""
def f(x):
return np.fabs(x - x.mean()).mean()
return cls._rolling(series, window).apply(f, raw=True)
def _get_mad(self, meta: _Meta):
""" get mean absolute deviation """
window = meta.int
self[meta.name] = self._mad(self[meta.column], window)
def _get_sma(self, meta: _Meta):
""" get simple moving average """
window = meta.int
self[meta.name] = self.sma(self[meta.column], window)
def _get_lrma(self, meta: _Meta):
""" get linear regression moving average """
window = meta.int
self[meta.name] = self.linear_reg(self[meta.column], window)
def _get_roc(self, meta: _Meta):
"""get Rate of Change (ROC) of a column
The Price Rate of Change (ROC) is a momentum-based technical indicator
that measures the percentage change in price between the current price
and the price a certain number of periods ago.
https://www.investopedia.com/terms/p/pricerateofchange.asp
Formular:
ROC = (PriceP - PricePn) / PricePn * 100