forked from chrisconlan/algorithmic-trading-with-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicators.py
77 lines (57 loc) · 2.31 KB
/
indicators.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
import pandas as pd
from pypm.data_io import load_eod_data
def calculate_simple_moving_average(series: pd.Series, n: int=20) -> pd.Series:
"""Calculates the simple moving average"""
return series.rolling(n).mean()
def calculate_simple_moving_sample_stdev(series: pd.Series, n: int=20) -> pd.Series:
"""Calculates the simple moving average"""
return series.rolling(n).std()
def calculate_macd_oscillator(series: pd.Series,
n1: int=5, n2: int=34) -> pd.Series:
"""
Calculate the moving average convergence divergence oscillator, given a
short moving average of length n1 and a long moving average of length n2
"""
assert n1 < n2, f'n1 must be less than n2'
return calculate_simple_moving_average(series, n1) - \
calculate_simple_moving_average(series, n2)
def calculate_bollinger_bands(series: pd.Series, n: int=20) -> pd.DataFrame:
"""
Calculates the Bollinger Bands and returns them as a dataframe
"""
sma = calculate_simple_moving_average(series, n)
stdev = calculate_simple_moving_sample_stdev(series, n)
return pd.DataFrame({
'middle': sma,
'upper': sma + 2 * stdev,
'lower': sma - 2 * stdev
})
def calculate_money_flow_volume_series(df: pd.DataFrame) -> pd.Series:
"""
Calculates money flow series
"""
mfv = df['volume'] * (2*df['close'] - df['high'] - df['low']) / \
(df['high'] - df['low'])
return mfv
def calculate_money_flow_volume(df: pd.DataFrame, n: int=20) -> pd.Series:
"""
Calculates money flow volume, or q_t in our formula
"""
return calculate_money_flow_volume_series(df).rolling(n).sum()
def calculate_chaikin_money_flow(df: pd.DataFrame, n: int=20) -> pd.Series:
"""
Calculates the Chaikin money flow
"""
return calculate_money_flow_volume(df, n) / df['volume'].rolling(n).sum()
if __name__ == '__main__':
data = load_eod_data('AWU')
closes = data['close']
sma = calculate_simple_moving_average(closes, 10)
macd = calculate_macd_oscillator(closes, 5, 50)
bollinger_bands = calculate_bollinger_bands(closes, 100)
bollinger_bands = bollinger_bands.assign(closes=closes)
bollinger_bands.plot()
cmf = calculate_chaikin_money_flow(data)
# cmf.plot()
import matplotlib.pyplot as plt
plt.show()