-
-
Notifications
You must be signed in to change notification settings - Fork 848
/
volatility.py
647 lines (482 loc) · 20.8 KB
/
volatility.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
"""
.. module:: volatility
:synopsis: Volatility Indicators.
.. moduleauthor:: Dario Lopez Padial (Bukosabino)
"""
import numpy as np
import pandas as pd
from ta.utils import IndicatorMixin, ema
class AverageTrueRange(IndicatorMixin):
"""Average True Range (ATR)
The indicator provide an indication of the degree of price volatility.
Strong moves, in either direction, are often accompanied by large ranges,
or large True Ranges.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_true_range_atr
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
cs = self._close.shift(1)
tr = self._high.combine(cs, max) - self._low.combine(cs, min)
atr = np.zeros(len(self._close))
atr[self._n-1] = tr[0:self._n].mean()
for i in range(self._n, len(atr)):
atr[i] = (atr[i-1] * (self._n-1) + tr.iloc[i]) / float(self._n)
self._atr = pd.Series(data=atr, index=tr.index)
def average_true_range(self) -> pd.Series:
"""Average True Range (ATR)
Returns:
pandas.Series: New feature generated.
"""
atr = self._check_fillna(self._atr, value=0)
return pd.Series(atr, name='atr')
class BollingerBands(IndicatorMixin):
"""Bollinger Bands
https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 20, ndev: int = 2, fillna: bool = False):
self._close = close
self._n = n
self._ndev = ndev
self._fillna = fillna
self._run()
def _run(self):
self._mavg = self._close.rolling(self._n, min_periods=0).mean()
self._mstd = self._close.rolling(self._n, min_periods=0).std(ddof=0)
self._hband = self._mavg + self._ndev * self._mstd
self._lband = self._mavg - self._ndev * self._mstd
def bollinger_mavg(self) -> pd.Series:
"""Bollinger Channel Middle Band
Returns:
pandas.Series: New feature generated.
"""
mavg = self._check_fillna(self._mavg, value=-1)
return pd.Series(mavg, name='mavg')
def bollinger_hband(self) -> pd.Series:
"""Bollinger Channel High Band
Returns:
pandas.Series: New feature generated.
"""
hband = self._check_fillna(self._hband, value=-1)
return pd.Series(hband, name='hband')
def bollinger_lband(self) -> pd.Series:
"""Bollinger Channel Low Band
Returns:
pandas.Series: New feature generated.
"""
lband = self._check_fillna(self._lband, value=-1)
return pd.Series(lband, name='lband')
def bollinger_wband(self) -> pd.Series:
"""Bollinger Channel Band Width
From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_width
Returns:
pandas.Series: New feature generated.
"""
wband = ((self._hband - self._lband) / self._mavg) * 100
wband = self._check_fillna(wband, value=0)
return pd.Series(wband, name='bbiwband')
def bollinger_pband(self) -> pd.Series:
"""Bollinger Channel Percentage Band
From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_perce
Returns:
pandas.Series: New feature generated.
"""
pband = (self._close - self._lband) / (self._hband - self._lband)
pband = self._check_fillna(pband, value=0)
return pd.Series(pband, name='bbipband')
def bollinger_hband_indicator(self) -> pd.Series:
"""Bollinger Channel Indicator Crossing High Band (binary).
It returns 1, if close is higher than bollinger_hband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
hband = pd.Series(np.where(self._close > self._hband, 1.0, 0.0), index=self._close.index)
hband = self._check_fillna(hband, value=0)
return pd.Series(hband, index=self._close.index, name='bbihband')
def bollinger_lband_indicator(self) -> pd.Series:
"""Bollinger Channel Indicator Crossing Low Band (binary).
It returns 1, if close is lower than bollinger_lband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
lband = pd.Series(np.where(self._close < self._lband, 1.0, 0.0), index=self._close.index)
lband = self._check_fillna(lband, value=0)
return pd.Series(lband, name='bbilband')
class KeltnerChannel(IndicatorMixin):
"""KeltnerChannel
Keltner Channels are a trend following indicator used to identify reversals with channel breakouts and
channel direction. Channels can also be used to identify overbought and oversold levels when the trend
is flat.
https://school.stockcharts.com/doku.php?id=technical_indicators:keltner_channels
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
ov(bool): if True, use original version as the centerline (SMA of typical price)
if False, use EMA of close as the centerline. More info:
https://school.stockcharts.com/doku.php?id=technical_indicators:keltner_channels
"""
def __init__(
self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False,
ov: bool = True):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._ov = ov
self._run()
def _run(self):
if self._ov:
self._tp = ((self._high + self._low + self._close) / 3.0).rolling(self._n, min_periods=0).mean()
self._tp_high = (((4 * self._high) - (2 * self._low) + self._close) / 3.0).rolling(
self._n, min_periods=0).mean()
self._tp_low = (((-2 * self._high) + (4 * self._low) + self._close) / 3.0).rolling(
self._n, min_periods=0).mean()
else:
self._tp = self._close.ewm(span=self._n, min_periods=0, adjust=False).mean()
atr = AverageTrueRange(
close=self._close, high=self._high, low=self._high, n=10, fillna=self._fillna
).average_true_range()
self._tp_high = self._tp + (2*atr)
self._tp_low = self._tp - (2*atr)
def keltner_channel_mband(self) -> pd.Series:
"""Keltner Channel Middle Band
Returns:
pandas.Series: New feature generated.
"""
tp = self._check_fillna(self._tp, value=-1)
return pd.Series(tp, name='mavg')
def keltner_channel_hband(self) -> pd.Series:
"""Keltner Channel High Band
Returns:
pandas.Series: New feature generated.
"""
tp = self._check_fillna(self._tp_high, value=-1)
return pd.Series(tp, name='kc_hband')
def keltner_channel_lband(self) -> pd.Series:
"""Keltner Channel Low Band
Returns:
pandas.Series: New feature generated.
"""
tp_low = self._check_fillna(self._tp_low, value=-1)
return pd.Series(tp_low, name='kc_lband')
def keltner_channel_wband(self) -> pd.Series:
"""Keltner Channel Band Width
Returns:
pandas.Series: New feature generated.
"""
wband = ((self._tp_high - self._tp_low) / self._tp) * 100
wband = self._check_fillna(wband, value=0)
return pd.Series(wband, name='bbiwband')
def keltner_channel_pband(self) -> pd.Series:
"""Keltner Channel Percentage Band
Returns:
pandas.Series: New feature generated.
"""
pband = (self._close - self._tp_low) / (self._tp_high - self._tp_low)
pband = self._check_fillna(pband, value=0)
return pd.Series(pband, name='bbipband')
def keltner_channel_hband_indicator(self) -> pd.Series:
"""Keltner Channel Indicator Crossing High Band (binary)
It returns 1, if close is higher than keltner_channel_hband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
hband = pd.Series(np.where(self._close > self._tp_high, 1.0, 0.0), index=self._close.index)
hband = self._check_fillna(hband, value=0)
return pd.Series(hband, name='dcihband')
def keltner_channel_lband_indicator(self) -> pd.Series:
"""Keltner Channel Indicator Crossing Low Band (binary)
It returns 1, if close is lower than keltner_channel_lband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
lband = pd.Series(np.where(self._close < self._tp_low, 1.0, 0.0), index=self._close.index)
lband = self._check_fillna(lband, value=0)
return pd.Series(lband, name='dcilband')
class DonchianChannel(IndicatorMixin):
"""Donchian Channel
https://www.investopedia.com/terms/d/donchianchannels.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 20, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
self._hband = self._close.rolling(self._n, min_periods=0).max()
self._lband = self._close.rolling(self._n, min_periods=0).min()
def donchian_channel_hband(self) -> pd.Series:
"""Donchian Channel High Band
Returns:
pandas.Series: New feature generated.
"""
hband = self._check_fillna(self._hband, value=-1)
return pd.Series(hband, name='dchband')
def donchian_channel_lband(self) -> pd.Series:
"""Donchian Channel Low Band
Returns:
pandas.Series: New feature generated.
"""
lband = self._check_fillna(self._lband, value=-1)
return pd.Series(lband, name='dclband')
def donchian_channel_hband_indicator(self) -> pd.Series:
"""Donchian Channel Indicator Crossing High Band (binary)
It returns 1, if close is higher than donchian_channel_hband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
hband = pd.Series(np.where(self._close >= self._hband, 1.0, 0.0), index=self._close.index)
hband = self._check_fillna(hband, value=0)
return pd.Series(hband, name='dcihband')
def donchian_channel_lband_indicator(self) -> pd.Series:
"""Donchian Channel Indicator Crossing Low Band (binary)
It returns 1, if close is lower than donchian_channel_lband. Else, it returns 0.
Returns:
pandas.Series: New feature generated.
"""
lband = pd.Series(np.where(self._close <= self._lband, 1.0, 0.0), index=self._close.index)
lband = self._check_fillna(lband, value=0)
return pd.Series(lband, name='dcilband')
def average_true_range(high, low, close, n=14, fillna=False):
"""Average True Range (ATR)
The indicator provide an indication of the degree of price volatility.
Strong moves, in either direction, are often accompanied by large ranges,
or large True Ranges.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_true_range_atr
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = AverageTrueRange(high=high, low=low, close=close, n=n, fillna=fillna)
return indicator.average_true_range()
def bollinger_mavg(close, n=20, fillna=False):
"""Bollinger Bands (BB)
N-period simple moving average (MA).
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = BollingerBands(close=close, n=n, fillna=fillna)
return indicator.bollinger_mavg()
def bollinger_hband(close, n=20, ndev=2, fillna=False):
"""Bollinger Bands (BB)
Upper band at K times an N-period standard deviation above the moving
average (MA + Kdeviation).
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = BollingerBands(close=close, n=n, ndev=ndev, fillna=fillna)
return indicator.bollinger_hband()
def bollinger_lband(close, n=20, ndev=2, fillna=False):
"""Bollinger Bands (BB)
Lower band at K times an N-period standard deviation below the moving
average (MA − Kdeviation).
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = BollingerBands(close=close, n=n, ndev=ndev, fillna=fillna)
return indicator.bollinger_lband()
def bollinger_hband_indicator(close, n=20, ndev=2, fillna=False):
"""Bollinger High Band Indicator
Returns 1, if close is higher than bollinger high band. Else, return 0.
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = BollingerBands(close=close, n=n, ndev=ndev, fillna=fillna)
return indicator.bollinger_hband_indicator()
def bollinger_lband_indicator(close, n=20, ndev=2, fillna=False):
"""Bollinger Low Band Indicator
Returns 1, if close is lower than bollinger low band. Else, return 0.
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
ndev(int): n factor standard deviation
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = BollingerBands(close=close, n=n, ndev=ndev, fillna=fillna)
return indicator.bollinger_hband_indicator()
def keltner_channel_mband(high, low, close, n=10, fillna=False):
"""Keltner channel (KC)
Showing a simple moving average line (central) of typical price.
https://en.wikipedia.org/wiki/Keltner_channel
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = KeltnerChannel(high=high, low=low, close=close, n=n, fillna=False)
return indicator.keltner_channel_mband()
def keltner_channel_hband(high, low, close, n=10, fillna=False):
"""Keltner channel (KC)
Showing a simple moving average line (high) of typical price.
https://en.wikipedia.org/wiki/Keltner_channel
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = KeltnerChannel(high=high, low=low, close=close, n=n, fillna=False)
return indicator.keltner_channel_hband()
def keltner_channel_lband(high, low, close, n=10, fillna=False):
"""Keltner channel (KC)
Showing a simple moving average line (low) of typical price.
https://en.wikipedia.org/wiki/Keltner_channel
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = KeltnerChannel(high=high, low=low, close=close, n=n, fillna=False)
return indicator.keltner_channel_lband()
def keltner_channel_hband_indicator(high, low, close, n=10, fillna=False):
"""Keltner Channel High Band Indicator (KC)
Returns 1, if close is higher than keltner high band channel. Else,
return 0.
https://en.wikipedia.org/wiki/Keltner_channel
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = KeltnerChannel(high=high, low=low, close=close, n=n, fillna=False)
return indicator.keltner_channel_hband_indicator()
def keltner_channel_lband_indicator(high, low, close, n=10, fillna=False):
"""Keltner Channel Low Band Indicator (KC)
Returns 1, if close is lower than keltner low band channel. Else, return 0.
https://en.wikipedia.org/wiki/Keltner_channel
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = KeltnerChannel(high=high, low=low, close=close, n=n, fillna=False)
return indicator.keltner_channel_lband_indicator()
def donchian_channel_hband(close, n=20, fillna=False):
"""Donchian channel (DC)
The upper band marks the highest price of an issue for n periods.
https://www.investopedia.com/terms/d/donchianchannels.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = DonchianChannel(close=close, n=n, fillna=fillna)
return indicator.donchian_channel_hband()
def donchian_channel_lband(close, n=20, fillna=False):
"""Donchian channel (DC)
The lower band marks the lowest price for n periods.
https://www.investopedia.com/terms/d/donchianchannels.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = DonchianChannel(close=close, n=n, fillna=fillna)
return indicator.donchian_channel_lband()
def donchian_channel_hband_indicator(close, n=20, fillna=False):
"""Donchian High Band Indicator
Returns 1, if close is higher than donchian high band channel. Else,
return 0.
https://www.investopedia.com/terms/d/donchianchannels.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = DonchianChannel(close=close, n=n, fillna=fillna)
return indicator.donchian_channel_hband_indicator()
def donchian_channel_lband_indicator(close, n=20, fillna=False):
"""Donchian Low Band Indicator
Returns 1, if close is lower than donchian low band channel. Else,
return 0.
https://www.investopedia.com/terms/d/donchianchannels.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = DonchianChannel(close=close, n=n, fillna=fillna)
return indicator.donchian_channel_lband_indicator()