forked from jealous/stockstats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stockstats.py
1782 lines (1456 loc) · 57.6 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 itertools
import re
import numpy as np
import pandas as pd
__author__ = 'Cedric Zhuang'
from numpy.lib.stride_tricks import as_strided
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)
KDJ_WINDOW = 9
BOLL_PERIOD = 20
BOLL_STD_TIMES = 2
MACD_EMA_SHORT = 12
MACD_EMA_LONG = 26
MACD_EMA_SIGNAL = 9
PPO_EMA_SHORT = 12
PPO_EMA_LONG = 26
PPO_EMA_SIGNAL = 9
PDI_SMMA = 14
MDI_SMMA = 14
DX_SMMA = 14
ADX_EMA = 6
ADXR_EMA = 6
CR_MA1 = 5
CR_MA2 = 10
CR_MA3 = 20
TRIX_EMA_WINDOW = 12
TEMA_EMA_WINDOW = 5
ATR_SMMA = 14
SUPERTREND_MUL = 3
SUPERTREND_WINDOW = 14
VWMA = 14
CHOP = 14
MFI = 14
CCI = 14
RSI = 14
VR = 26
WR = 14
CMO = 14
WAVE_TREND_1 = 10
WAVE_TREND_2 = 21
KAMA_SLOW = 34
KAMA_FAST = 5
AO_SLOW = 34
AO_FAST = 5
COPPOCK = (10, 11, 14)
ICHIMOKU = (9, 26, 52)
CTI = 12
MULTI_SPLIT_INDICATORS = ("kama",)
# End of options
@staticmethod
def _change(series, window):
return series.pct_change(periods=-window).fillna(0.0) * 100
def _get_change(self):
""" Get the percentage change column
:return: result series
"""
self['change'] = self._change(self['close'], -1)
def _get_p(self, column, shifts):
""" 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
:param column: the column to calculate p from
:param shifts: the range to consider
:return:
"""
column_name = '{}_{}_p'.format(column, shifts)
# initialize the column if not
self.get(column)
shifts = self.to_ints(shifts)[::-1]
indices = None
count = 0
for shift in shifts:
shifted = self.shift(-shift)
index = (shifted[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[column_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
@staticmethod
def set_nan(pd_obj, shift):
try:
iter(shift)
max_shift = max(shift)
min_shift = min(shift)
StockDataFrame._set_nan_of_single_shift(pd_obj, max_shift)
StockDataFrame._set_nan_of_single_shift(pd_obj, min_shift)
except TypeError:
# shift is not iterable
StockDataFrame._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, column, shifts):
""" Get rate of change of column
:param column: column name of the rate to calculate
:param shifts: periods to shift, accept one shift only
:return: None
"""
shift = self.to_int(shifts)
rate_key = '{}_{}_r'.format(column, shift)
self[rate_key] = self._change(self[column], shift)
@staticmethod
def _shift(series, window):
""" 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, column, shifts):
""" Get the column shifted by periods
:param column: name of the column to shift
:param shifts: periods to shift, accept one shift only
:return: None
"""
shift = self.to_int(shifts)
shifted_key = "{}_{}_s".format(column, shift)
self[shifted_key] = self._shift(self[column], shift)
def _get_log_ret(self):
close = self['close']
self['log-ret'] = np.log(close / self._shift(close, -1))
def _get_c(self, column, window):
""" get the count of column in range (shifts)
example: change_20_c
:param column: column name
:param window: range to count, only to previous
:return: result series
"""
column_name = '{}_{}_c'.format(column, window)
window = self.get_int_positive(window)
self[column_name] = self._rolling(
self[column], window).apply(np.count_nonzero, raw=True)
return self[column_name]
def _get_fc(self, column, shifts):
""" get the count of column in range of future (shifts)
example: change_20_fc
:param column: column name
:param shifts: range to count, only to future
:return: result series
"""
column_name = '{}_{}_fc'.format(column, shifts)
shift = self.get_int_positive(shifts)
reversed_series = self[column][::-1]
reversed_counts = self._rolling(
reversed_series, shift).apply(np.count_nonzero, raw=True)
counts = reversed_counts[::-1]
self[column_name] = counts
return counts
def _init_shifted_columns(self, column, shifts):
# initialize the column if not
self.get(column)
shifts = self.to_ints(shifts)
shift_column_names = ['{}_{}_s'.format(column, shift) for shift in
shifts]
[self.get(name) for name in shift_column_names]
return shift_column_names
def _get_max(self, column, shifts):
column_name = '{}_{}_max'.format(column, shifts)
shift_column_names = self._init_shifted_columns(column, shifts)
self[column_name] = np.max(self[shift_column_names], axis=1)
def _get_min(self, column, shifts):
column_name = '{}_{}_min'.format(column, shifts)
shift_column_names = self._init_shifted_columns(column, shifts)
self[column_name] = np.min(self[shift_column_names], axis=1)
def _get_rsv(self, window):
""" Calculate the RSV (Raw Stochastic Value) within N periods
This value is essential for calculating KDJs
Current day is included in N
:param window: number of periods
:return: None
"""
window = self.get_int_positive(window)
column_name = 'rsv_{}'.format(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)
self[column_name] = cv.fillna(0.0) * 100
def _get_rsi(self, window=None):
""" Calculate the RSI (Relative Strength Index) within N periods
calculated based on the formula at:
https://en.wikipedia.org/wiki/Relative_strength_index
:param window: number of periods
:return: None
"""
if window is None:
window = self.RSI
column_name = 'rsi'
else:
column_name = 'rsi_{}'.format(window)
window = self.get_int_positive(window)
change = self._delta(self['close'], -1)
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_column_name = 'rs_{}'.format(window)
self[rs_column_name] = rs = p_ema / n_ema
self[column_name] = 100 - 100 / (1.0 + rs)
def _get_stochrsi(self, window=None):
""" Calculate the Stochastic RSI
calculated based on the formula at:
https://www.investopedia.com/terms/s/stochrsi.asp
:param window: number of periods
:return: None
"""
if window is None:
window = self.RSI
column_name = 'stochrsi'
else:
column_name = 'stochrsi_{}'.format(window)
window = self.get_int_positive(window)
rsi = self['rsi_{}'.format(window)]
rsi_min = self.mov_min(rsi, window)
rsi_max = self.mov_max(rsi, window)
cv = (rsi - rsi_min) / (rsi_max - rsi_min)
self[column_name] = cv * 100
def _get_wave_trend(self):
""" 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
n1: period of EMA on typical price
n2: period of EMA
:return: None
"""
n1 = self.WAVE_TREND_1
n2 = self.WAVE_TREND_2
tp = self._tp()
esa = self.ema(tp, n1)
d = self.ema((tp - esa).abs(), n1)
ci = (tp - esa) / (0.015 * d)
tci = self.ema(ci, n2)
self["wt1"] = tci
self["wt2"] = 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, column, windows):
""" get smoothed moving average.
:param column: the column to calculate
:param windows: range
:return: result series
"""
window = self.get_int_positive(windows)
column_name = '{}_{}_smma'.format(column, window)
self[column_name] = self.smma(self[column], window)
def _get_trix(self, column=None, windows=None):
""" Triple Exponential Average
https://www.investopedia.com/articles/technical/02/092402.asp
:param column: the column to calculate
:param windows: range
:return: result series
"""
column_name = ""
if column is None and windows is None:
column_name = 'trix'
if column is None:
column = 'close'
if windows is None:
windows = self.TRIX_EMA_WINDOW
if column_name == "":
column_name = '{}_{}_trix'.format(column, windows)
window = self.get_int_positive(windows)
single = self.ema(self[column], window)
double = self.ema(single, window)
triple = self.ema(double, window)
prev_triple = self._shift(triple, -1)
triple_change = self._delta(triple, -1)
self[column_name] = triple_change * 100 / prev_triple
def _get_tema(self, column=None, windows=None):
""" 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/
:param column: column to calculate ema
:param windows: window of the calculation
:return: result series
"""
column_name = ""
if column is None and windows is None:
column_name = 'tema'
if column is None:
column = 'close'
if windows is None:
windows = self.TEMA_EMA_WINDOW
if column_name == "":
column_name = '{}_{}_tema'.format(column, windows)
window = self.get_int_positive(windows)
single = self.ema(self[column], window)
double = self.ema(single, window)
triple = self.ema(double, window)
self[column_name] = 3 * single - 3 * double + triple
def _get_wr(self, window=None):
""" 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
:param window: number of periods
:return: None
"""
if window is None:
window = self.WR
column_name = 'wr'
else:
column_name = 'wr_{}'.format(window)
window = self.get_int_positive(window)
ln = self.mov_min(self['low'], window)
hn = self.mov_max(self['high'], window)
self[column_name] = (hn - self['close']) / (hn - ln) * -100
def _get_cci(self, window=None):
""" 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'.
:param window: number of periods
:return: None
"""
if window is None:
window = self.CCI
column_name = 'cci'
else:
column_name = 'cci_{}'.format(window)
window = self.get_int_positive(window)
tp = self._tp()
tp_sma = self.sma(tp, window)
mad = self._mad(tp, window)
self[column_name] = (tp - tp_sma) / (.015 * mad)
def _tr(self):
prev_close = self._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):
""" 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['tr'] = self._tr()
def _get_supertrend(self, window=None):
""" 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
:param window: number of periods
:return: None
"""
if window is None:
window = self.SUPERTREND_WINDOW
window = self.get_int_positive(window)
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['supertrend_ub'] = ub
self['supertrend_lb'] = lb
self['supertrend'] = st
def _get_aroon(self, window=None):
""" 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
"""
if window is None:
window = 25
column_name = 'aroon'
else:
window = self.get_int_positive(window)
column_name = 'aroon_{}'.format(window)
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[column_name] = aroon_up - aroon_down
def _get_z(self, column, window):
""" 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 = self.get_int_positive(window)
column_name = '{}_{}_z'.format(column, window)
col = self[column]
mean = self.sma(col, window)
std = self.mov_std(col, window)
self[column_name] = ((col - mean) / std).fillna(0.0)
def _atr(self, window):
tr = self._tr()
return self.smma(tr, window)
def _get_atr(self, window=None):
""" 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
:param window: number of periods
:return: None
"""
if window is None:
window = self.ATR_SMMA
column_name = 'atr'
else:
column_name = 'atr_{}'.format(window)
window = self.get_int_positive(window)
self[column_name] = self._atr(window)
def _get_dma(self):
""" Difference of Moving Average
default to 10 and 50.
:return: None
"""
self['dma'] = self['close_10_sma'] - self['close_50_sma']
def _get_dmi(self):
""" 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['pdi'] = self._get_pdi(self.PDI_SMMA)
self['mdi'] = self._get_mdi(self.MDI_SMMA)
self['dx'] = self._get_dx(self.DX_SMMA)
self['adx'] = self.ema(self['dx'], self.ADX_EMA)
self['adxr'] = self.ema(self['adx'], self.ADXR_EMA)
def _get_um_dm(self):
""" Up move and down move
initialize up move and down move
"""
hd = self._col_delta('high')
self['um'] = (hd > 0) * hd
ld = -self._col_delta('low')
self['dm'] = (ld > 0) * ld
def _get_pdm_ndm(self, window):
hd = self._col_delta('high')
ld = -self._col_delta('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, windows):
""" +DM, positive directional moving
If window is not 1, calculate the SMMA of +DM
:param windows: range
:return:
"""
window = self.get_int_positive(windows)
if window > 1:
column_name = 'pdm_{}'.format(window)
else:
column_name = 'pdm'
self[column_name] = self._pdm(window)
def _get_ndm(self, windows):
""" -DM, negative directional moving accumulation
If window is not 1, return the SMA of -DM.
:param windows: range
:return:
"""
window = self.get_int_positive(windows)
if window > 1:
column_name = 'ndm_{}'.format(window)
else:
column_name = 'ndm'
self[column_name] = self._ndm(window)
def _get_vr(self, windows=None):
if windows is None:
window = self.VR
column_name = 'vr'
else:
window = self.get_int_positive(windows)
column_name = 'vr_{}'.format(window)
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[column_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, windows):
""" +DI, positive directional moving index
:param windows: range
:return:
"""
window = self.get_int_positive(windows)
pdi, _ = self._get_pdi_ndi(window)
pdi_column = 'pdi_{}'.format(window)
self[pdi_column] = pdi
return self[pdi_column]
def _get_mdi(self, windows):
window = self.get_int_positive(windows)
_, ndi = self._get_pdi_ndi(window)
mdi_column = 'mdi_{}'.format(window)
self[mdi_column] = ndi
return self[mdi_column]
def _get_dx(self, windows):
window = self.get_int_positive(windows)
dx_column = 'dx_{}'.format(window)
pdi, mdi = self._get_pdi_ndi(window)
self[dx_column] = abs(pdi - mdi) / (pdi + mdi) * 100
return self[dx_column]
def _get_kdj_default(self):
""" default KDJ, 9 periods
:return: None
"""
self['kdjk'] = self['kdjk_{}'.format(self.KDJ_WINDOW)]
self['kdjd'] = self['kdjd_{}'.format(self.KDJ_WINDOW)]
self['kdjj'] = self['kdjj_{}'.format(self.KDJ_WINDOW)]
def _get_cr(self, windows=None):
""" 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.
:param windows: window of the moving sum
:return: None
"""
if windows is None:
window = 26
else:
window = self.get_int_positive(windows)
middle = self._tp()
last_middle = self._shift(middle, -1)
ym = self._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)
if windows is None:
cr = 'cr'
cr_ma1 = 'cr-ma1'
cr_ma2 = 'cr-ma2'
cr_ma3 = 'cr-ma3'
else:
cr = 'cr_{}'.format(window)
cr_ma1 = 'cr_{}-ma1'.format(window)
cr_ma2 = 'cr_{}-ma2'.format(window)
cr_ma3 = 'cr_{}-ma3'.format(window)
self[cr] = cr = p1 / p2 * 100
self[cr_ma1] = self._shifted_cr_sma(cr, self.CR_MA1)
self[cr_ma2] = self._shifted_cr_sma(cr, self.CR_MA2)
self[cr_ma3] = self._shifted_cr_sma(cr, self.CR_MA3)
def _shifted_cr_sma(self, cr, window):
cr_sma = self.sma(cr, window)
return self._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):
self['tp'] = self._tp()
def _get_middle(self):
self['middle'] = 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, window):
""" Get the K of KDJ
K = 2/3 × (prev. K) +1/3 × (curr. RSV)
2/3 and 1/3 are the smooth parameters.
:param window: number of periods
:return: None
"""
rsv_column = 'rsv_{}'.format(window)
k_column = 'kdjk_{}'.format(window)
self[k_column] = list(self._calc_kd(self.get(rsv_column)))
def _get_kdjd(self, window):
""" Get the D of KDJ
D = 2/3 × (prev. D) +1/3 × (curr. K)
2/3 and 1/3 are the smooth parameters.
:param window: number of periods
:return: None
"""
k_column = 'kdjk_{}'.format(window)
d_column = 'kdjd_{}'.format(window)
self[d_column] = list(self._calc_kd(self.get(k_column)))
def _get_kdjj(self, window):
""" Get the J of KDJ
J = 3K-2D
:param self: data
:param window: number of periods
:return: None
"""
k_column = 'kdjk_{}'.format(window)
d_column = 'kdjd_{}'.format(window)
j_column = 'kdjj_{}'.format(window)
self[j_column] = 3 * self[k_column] - 2 * self[d_column]
@staticmethod
def _delta(series, window):
return series.diff(-window).fillna(0.0)
def _get_d(self, column, shifts):
shift = self.to_int(shifts)
column_name = '{}_{}_d'.format(column, shift)
self[column_name] = self._delta(self[column], shift)
@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)
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, column, window):
""" get mean absolute deviation
:param column: column to calculate
:param window: number of periods
:return: None
"""
window = self.get_int_positive(window)
column_name = '{}_{}_mad'.format(column, window)