-
-
Notifications
You must be signed in to change notification settings - Fork 849
/
volume.py
672 lines (507 loc) · 22.3 KB
/
volume.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
# -*- coding: future_fstrings -*-
"""
.. module:: volume
:synopsis: Volume Indicators.
.. moduleauthor:: Dario Lopez Padial (Bukosabino)
"""
import numpy as np
import pandas as pd
from ta.utils import IndicatorMixin, ema
class AccDistIndexIndicator(IndicatorMixin):
"""Accumulation/Distribution Index (ADI)
Acting as leading indicator of price movements.
https://school.stockcharts.com/doku.php?id=technical_indicators:accumulation_distribution_line
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._volume = volume
self._fillna = fillna
self._run()
def _run(self):
clv = ((self._close - self._low) - (self._high - self._close)) / (self._high - self._low)
clv = clv.fillna(0.0) # float division by zero
ad = clv * self._volume
self._ad = ad.cumsum()
def acc_dist_index(self) -> pd.Series:
"""Accumulation/Distribution Index (ADI)
Returns:
pandas.Series: New feature generated.
"""
ad = self._check_fillna(self._ad, value=0)
return pd.Series(ad, name='adi')
class OnBalanceVolumeIndicator(IndicatorMixin):
"""On-balance volume (OBV)
It relates price and volume in the stock market. OBV is based on a
cumulative total volume.
https://en.wikipedia.org/wiki/On-balance_volume
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):
self._close = close
self._volume = volume
self._fillna = fillna
self._run()
def _run(self):
obv = np.where(self._close < self._close.shift(1), -self._volume, self._volume)
self._obv = pd.Series(obv, index=self._close.index).cumsum()
def on_balance_volume(self) -> pd.Series:
"""On-balance volume (OBV)
Returns:
pandas.Series: New feature generated.
"""
obv = self._check_fillna(self._obv, value=0)
return pd.Series(obv, name='obv')
class ChaikinMoneyFlowIndicator(IndicatorMixin):
"""Chaikin Money Flow (CMF)
It measures the amount of Money Flow Volume over a specific period.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series,
volume: pd.Series, n: int = 20, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._volume = volume
self._n = n
self._fillna = fillna
self._run()
def _run(self):
mfv = ((self._close - self._low) - (self._high - self._close)) / (self._high - self._low)
mfv = mfv.fillna(0.0) # float division by zero
mfv *= self._volume
self._cmf = mfv.rolling(self._n, min_periods=0).sum() / self._volume.rolling(self._n, min_periods=0).sum()
def chaikin_money_flow(self) -> pd.Series:
"""Chaikin Money Flow (CMF)
Returns:
pandas.Series: New feature generated.
"""
cmf = self._check_fillna(self._cmf, value=0)
return pd.Series(cmf, name='cmf')
class ForceIndexIndicator(IndicatorMixin):
"""Force Index (FI)
It illustrates how strong the actual buying or selling pressure is. High
positive values mean there is a strong rising trend, and low values signify
a strong downward trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, volume: pd.Series, n: int = 13, fillna: bool = False):
self._close = close
self._volume = volume
self._n = n
self._fillna = fillna
self._run()
def _run(self):
fi = (self._close - self._close.shift(1)) * self._volume
self._fi = ema(fi, self._n, fillna=self._fillna)
def force_index(self) -> pd.Series:
"""Force Index (FI)
Returns:
pandas.Series: New feature generated.
"""
fi = self._check_fillna(self._fi, value=0)
return pd.Series(fi, name=f'fi_{self._n}')
class EaseOfMovementIndicator(IndicatorMixin):
"""Ease of movement (EoM, EMV)
It relate an asset's price change to its volume and is particularly useful
for assessing the strength of a trend.
https://en.wikipedia.org/wiki/Ease_of_movement
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, volume: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._volume = volume
self._n = n
self._fillna = fillna
self._run()
def _run(self):
self._emv = (self._high.diff(1) + self._low.diff(1)) * (self._high - self._low) / (2 * self._volume)
self._emv *= 100000000
def ease_of_movement(self) -> pd.Series:
"""Ease of movement (EoM, EMV)
Returns:
pandas.Series: New feature generated.
"""
emv = self._check_fillna(self._emv, value=0)
return pd.Series(emv, name=f'eom_{self._n}')
def sma_ease_of_movement(self) -> pd.Series:
"""Signal Ease of movement (EoM, EMV)
Returns:
pandas.Series: New feature generated.
"""
emv = self._emv.rolling(self._n, min_periods=0).mean()
emv = self._check_fillna(emv, value=0)
return pd.Series(emv, name=f'sma_eom_{self._n}')
class VolumePriceTrendIndicator(IndicatorMixin):
"""Volume-price trend (VPT)
Is based on a running cumulative volume that adds or substracts a multiple
of the percentage change in share price trend and current volume, depending
upon the investment's upward or downward movements.
https://en.wikipedia.org/wiki/Volume%E2%80%93price_trend
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):
self._close = close
self._volume = volume
self._fillna = fillna
self._run()
def _run(self):
vpt = (self._volume * ((self._close - self._close.shift(1, fill_value=self._close.mean()))
/ self._close.shift(1, fill_value=self._close.mean())))
self._vpt = vpt.shift(1, fill_value=vpt.mean()) + vpt
def volume_price_trend(self) -> pd.Series:
"""Volume-price trend (VPT)
Returns:
pandas.Series: New feature generated.
"""
vpt = self._check_fillna(self._vpt, value=0)
return pd.Series(vpt, name='vpt')
class NegativeVolumeIndexIndicator(IndicatorMixin):
"""Negative Volume Index (NVI)
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:negative_volume_inde
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values with 1000.
"""
def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):
self._close = close
self._volume = volume
self._fillna = fillna
self._run()
def _run(self):
price_change = self._close.pct_change()
vol_decrease = (self._volume.shift(1) > self._volume)
self._nvi = pd.Series(data=np.nan, index=self._close.index, dtype='float64', name='nvi')
self._nvi.iloc[0] = 1000
for i in range(1, len(self._nvi)):
if vol_decrease.iloc[i]:
self._nvi.iloc[i] = self._nvi.iloc[i - 1] * (1.0 + price_change.iloc[i])
else:
self._nvi.iloc[i] = self._nvi.iloc[i - 1]
def negative_volume_index(self) -> pd.Series:
"""Negative Volume Index (NVI)
Returns:
pandas.Series: New feature generated.
"""
# IDEA: There shouldn't be any na; might be better to throw exception
nvi = self._check_fillna(self._nvi, value=1000)
return pd.Series(nvi, name='nvi')
class MFIIndicator(IndicatorMixin):
"""Money Flow Index (MFI)
Uses both price and volume to measure buying and selling pressure. It is
positive when the typical price rises (buying pressure) and negative when
the typical price declines (selling pressure). A ratio of positive and
negative money flow is then plugged into an RSI formula to create an
oscillator that moves between zero and one hundred.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:money_flow_index_mfi
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self,
high: pd.Series,
low: pd.Series,
close: pd.Series,
volume: pd.Series,
n: int = 14,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._volume = volume
self._n = n
self._fillna = fillna
self._run()
def _run(self):
# 1 typical price
tp = (self._high + self._low + self._close) / 3.0
# 2 up or down column
up_down = np.where(tp > tp.shift(1), 1, np.where(tp < tp.shift(1), -1, 0))
# 3 money flow
mf = tp * self._volume * up_down
# 4 positive and negative money flow with n periods
n_positive_mf = mf.rolling(self._n).apply(lambda x: np.sum(np.where(x >= 0.0, x, 0.0)), raw=True)
n_negative_mf = abs(mf.rolling(self._n).apply(lambda x: np.sum(np.where(x < 0.0, x, 0.0)), raw=True))
# n_positive_mf = np.where(mf.rolling(self._n).sum() >= 0.0, mf, 0.0)
# n_negative_mf = abs(np.where(mf.rolling(self._n).sum() < 0.0, mf, 0.0))
# 5 money flow index
mr = n_positive_mf / n_negative_mf
self._mr = (100 - (100 / (1 + mr)))
def money_flow_index(self) -> pd.Series:
"""Money Flow Index (MFI)
Returns:
pandas.Series: New feature generated.
"""
mr = self._check_fillna(self._mr, value=50)
return pd.Series(mr, name=f'mfi_{self._n}')
class VolumeWeightedAveragePrice(IndicatorMixin):
"""Volume Weighted Average Price (VWAP)
VWAP equals the dollar value of all trading periods divided
by the total trading volume for the current day.
The calculation starts when trading opens and ends when it closes.
Because it is good for the current trading day only,
intraday periods and data are used in the calculation.
https://school.stockcharts.com/doku.php?id=technical_indicators:vwap_intraday
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
def __init__(self,
high: pd.Series,
low: pd.Series,
close: pd.Series,
volume: pd.Series,
n: int = 14,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._volume = volume
self._n = n
self._fillna = fillna
self._run()
def _run(self):
# 1 typical price
tp = (self._high + self._low + self._close) / 3.0
# 2 typical price * volume
pv = (tp * self._volume)
# 3 total price * volume
total_pv = pv.rolling(self._n, min_periods=1).sum()
# 4 total volume
total_volume = self._volume.rolling(self._n, min_periods=1).sum()
self.vwap = total_pv / total_volume
def volume_weighted_average_price(self) -> pd.Series:
"""Volume Weighted Average Price (VWAP)
Returns:
pandas.Series: New feature generated.
"""
vwap = self._check_fillna(self.vwap)
return pd.Series(vwap, name=f'vwap_{self._n}')
def acc_dist_index(high, low, close, volume, fillna=False):
"""Accumulation/Distribution Index (ADI)
Acting as leading indicator of price movements.
https://en.wikipedia.org/wiki/Accumulation/distribution_index
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return AccDistIndexIndicator(high=high, low=low, close=close, volume=volume, fillna=fillna).acc_dist_index()
def on_balance_volume(close, volume, fillna=False):
"""On-balance volume (OBV)
It relates price and volume in the stock market. OBV is based on a
cumulative total volume.
https://en.wikipedia.org/wiki/On-balance_volume
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return OnBalanceVolumeIndicator(close=close, volume=volume, fillna=fillna).on_balance_volume()
def chaikin_money_flow(high, low, close, volume, n=20, fillna=False):
"""Chaikin Money Flow (CMF)
It measures the amount of Money Flow Volume over a specific period.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return ChaikinMoneyFlowIndicator(
high=high, low=low, close=close, volume=volume, n=n, fillna=fillna).chaikin_money_flow()
def force_index(close, volume, n=13, fillna=False):
"""Force Index (FI)
It illustrates how strong the actual buying or selling pressure is. High
positive values mean there is a strong rising trend, and low values signify
a strong downward trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return ForceIndexIndicator(close=close, volume=volume, n=n, fillna=fillna).force_index()
def ease_of_movement(high, low, volume, n=14, fillna=False):
"""Ease of movement (EoM, EMV)
It relate an asset's price change to its volume and is particularly useful
for assessing the strength of a trend.
https://en.wikipedia.org/wiki/Ease_of_movement
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return EaseOfMovementIndicator(
high=high, low=low, volume=volume, n=n, fillna=fillna).ease_of_movement()
def sma_ease_of_movement(high, low, volume, n=14, fillna=False):
"""Ease of movement (EoM, EMV)
It relate an asset's price change to its volume and is particularly useful
for assessing the strength of a trend.
https://en.wikipedia.org/wiki/Ease_of_movement
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return EaseOfMovementIndicator(
high=high, low=low, volume=volume, n=n, fillna=fillna).sma_ease_of_movement()
def volume_price_trend(close, volume, fillna=False):
"""Volume-price trend (VPT)
Is based on a running cumulative volume that adds or substracts a multiple
of the percentage change in share price trend and current volume, depending
upon the investment's upward or downward movements.
https://en.wikipedia.org/wiki/Volume%E2%80%93price_trend
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return VolumePriceTrendIndicator(close=close, volume=volume, fillna=fillna).volume_price_trend()
def negative_volume_index(close, volume, fillna=False):
"""Negative Volume Index (NVI)
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:negative_volume_inde
The Negative Volume Index (NVI) is a cumulative indicator that uses the
change in volume to decide when the smart money is active. Paul Dysart
first developed this indicator in the 1930s. [...] Dysart's Negative Volume
Index works under the assumption that the smart money is active on days
when volume decreases and the not-so-smart money is active on days when
volume increases.
The cumulative NVI line was unchanged when volume increased from one
period to the other. In other words, nothing was done. Norman Fosback, of
Stock Market Logic, adjusted the indicator by substituting the percentage
price change for Net Advances.
This implementation is the Fosback version.
If today's volume is less than yesterday's volume then:
nvi(t) = nvi(t-1) * ( 1 + (close(t) - close(t-1)) / close(t-1) )
Else
nvi(t) = nvi(t-1)
Please note: the "stockcharts.com" example calculation just adds the
percentange change of price to previous NVI when volumes decline; other
sources indicate that the same percentage of the previous NVI value should
be added, which is what is implemented here.
Args:
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
fillna(bool): if True, fill nan values with 1000.
Returns:
pandas.Series: New feature generated.
See also:
https://en.wikipedia.org/wiki/Negative_volume_index
"""
return NegativeVolumeIndexIndicator(close=close, volume=volume, fillna=fillna).negative_volume_index()
def money_flow_index(high, low, close, volume, n=14, fillna=False):
"""Money Flow Index (MFI)
Uses both price and volume to measure buying and selling pressure. It is
positive when the typical price rises (buying pressure) and negative when
the typical price declines (selling pressure). A ratio of positive and
negative money flow is then plugged into an RSI formula to create an
oscillator that moves between zero and one hundred.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:money_flow_index_mfi
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = MFIIndicator(high=high, low=low, close=close, volume=volume, n=n, fillna=fillna)
return indicator.money_flow_index()
def volume_weighted_average_price(
high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, n: int = 14, fillna: bool = False):
"""Volume Weighted Average Price (VWAP)
VWAP equals the dollar value of all trading periods divided
by the total trading volume for the current day.
The calculation starts when trading opens and ends when it closes.
Because it is good for the current trading day only,
intraday periods and data are used in the calculation.
https://school.stockcharts.com/doku.php?id=technical_indicators:vwap_intraday
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
volume(pandas.Series): dataset 'Volume' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = VolumeWeightedAveragePrice(high=high, low=low, close=close, volume=volume, n=n, fillna=fillna)
return indicator.volume_weighted_average_price()
# TODO
def put_call_ratio():
"""Put/Call ratio (PCR)
https://en.wikipedia.org/wiki/Put/call_ratio
"""
# TODO
pass