-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicators.py
204 lines (183 loc) · 8.44 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
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
import datetime as dt
from matplotlib import dates, ticker
import numpy as np
from util import get_data
import matplotlib.pyplot as plt
import pandas as pd
'''
Code implementing your indicators as functions that operate on DataFrames. There is no defined API for indicators.py,
but when it runs, the main method should generate the charts that will illustrate your indicators in the report.
Student Name: Apurva Gandhi
GT User ID: agandhi301
GT ID: 903862828
'''
# Helper Function
def calculate_rolling_mean(values, window_size):
return values.rolling(window_size).mean()
# Helper Function
def calculate_rolling_std(values, window_size):
return values.rolling(window_size).std()
# Indicator 1 - Simple Moving Average
def calculate_simple_moving_average(prices, window_size = 10):
simple_moving_average = calculate_rolling_mean(prices, window_size)
simple_moving_average_ratio = prices / simple_moving_average
return simple_moving_average, simple_moving_average_ratio
# Indicator 2 - Bollinger band
def calculate_bollinger_band_percentage(values, window_size=10, num_std_dev=2):
rolling_mean = calculate_rolling_mean(values, window_size)
rolling_std = calculate_rolling_std(values, window_size)
upper_band = rolling_mean + rolling_std * num_std_dev
lower_band = rolling_mean - rolling_std * num_std_dev
bollinger_band_percentage = (values - lower_band) / (upper_band - lower_band)
return bollinger_band_percentage
#Indicator 3 - Momentum
def calculate_momentum(values, window_size = 10):
return (values / values.shift(window_size)) - 1
# Indicator 4 - Commodity Channel Index - CCI
def calculate_commodity_channel_index(values, window_size=5):
rolling_mean = calculate_rolling_mean(values, window_size)
mean_deviation = abs(values - rolling_mean).rolling(window_size).mean()
# rolling_std = calculate_rolling_std(values, window_size)
# scaling_factor = 2 / rolling_std
return (values - rolling_mean) / (0.015 * mean_deviation)
# Indicator 5 - Moving Average Convergence Divergence (MACD)
def calculate_moving_average_convergence_divergence(values, short_period = 12, long_period = 26, signal_period = 9):
# Calculate the short-term EMA
short_ema = values.ewm(ignore_na=False, span=short_period, adjust=True).mean()
# Calculate the long-term EMA
long_ema = values.ewm(ignore_na=False, span=long_period, adjust=True).mean()
# Calculate the MACD line
macd_line = short_ema - long_ema
# Calculate the signal line (9-period EMA of MACD)
signal_line = macd_line.ewm(ignore_na=False, span=signal_period, adjust=True).mean()
# Calculate the MACD Histogram
macd_histogram = macd_line - signal_line
return macd_histogram
def test_code():
start_date = dt.datetime(2008, 1, 1)
end_date = dt.datetime(2009, 12, 31)
symbol = "JPM"
prices_df = get_data([symbol], pd.date_range(start_date, end_date))[symbol]
normalized_prices_df = prices_df/prices_df[0]
# Indicator 1 Graph
sma1 = calculate_rolling_mean(normalized_prices_df, 20)
sma2 = calculate_rolling_mean(normalized_prices_df, 100)
fig = plt.figure(figsize=(10, 6))
plt.title("Simple Moving average")
plt.ylabel("Normalized Price")
plt.xlabel("Date")
plt.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
plt.plot(sma1, label="SMA (Window size=20)", color="purple", lw=0.8)
plt.plot(sma2, label="SMA (Window size=100)", color="red", lw=0.8)
plt.grid(which='both', axis='both')
plt.tick_params(axis='x', which='major', labelsize=10)
fig.autofmt_xdate()
plt.legend(loc="best", frameon=True)
plt.savefig("sma.png")
plt.clf()
# Indicator 2 Graph
upper_band, lower_band = calculate_bollinger_bands(normalized_prices_df,20)
bollinger_band_percentage = (normalized_prices_df - lower_band) / (upper_band - lower_band)
fig = plt.figure(figsize=(10, 5))
plt.title("Bollinger Bands")
plt.xticks(rotation=20)
plt.ylabel("Normalized Price")
plt.xlabel("Date")
plt.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
plt.plot(upper_band, label="Upper Band", color="purple", lw=0.8)
plt.plot(lower_band, label="Lower Band", color="red", lw=0.8)
plt.grid(which='both', axis='both', linestyle="--")
plt.tick_params(axis='x', which='major', labelsize=10)
fig.autofmt_xdate()
plt.legend(loc="best", frameon=True)
plt.savefig("bollinger.png")
plt.clf()
fig = plt.figure(figsize=(10, 5))
plt.title("Bollinger Bands Percentage")
plt.xticks(rotation=20)
plt.ylabel("BB Percentage")
plt.xlabel("Date")
plt.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
plt.plot(bollinger_band_percentage, label="Bollinger Band Percentage", color="purple", lw=0.8)
plt.grid(which='both', axis='both', linestyle="--")
plt.tick_params(axis='x', which='major', labelsize=10)
fig.autofmt_xdate()
plt.legend(loc="best", frameon=True)
plt.savefig("bollinger_2.png")
plt.clf()
# Indicator 3 Graph
momentum = calculate_momentum(normalized_prices_df, 20)
fig = plt.figure(figsize=(10, 6))
ax1 = plt.subplot(211)
plt.suptitle("Momentum")
plt.ylabel("Momentum Index")
plt.xlabel("Date")
# left, right = plt.xlim()
# plt.xticks(np.arange(left, right, 60), rotation=10)
ax1.plot(momentum, label="Momentum", color="purple", lw=0.8)
plt.grid(which='both', axis='both', linestyle="--")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.axhline(y=0, color="red", lw=0.5)
plt.legend(loc="best", frameon=True)
ax2 = plt.subplot(212)
plt.ylabel("Normalized Prices")
plt.xlabel("Date")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.grid(which='both', axis='both', linestyle="--")
ax2.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
plt.legend(loc="best", frameon=True)
fig.autofmt_xdate()
plt.savefig("momentum.png")
plt.clf()
# Indicator 4 Graph
cci = calculate_commodity_channel_index(normalized_prices_df)
fig = plt.figure(figsize=(10, 6))
ax1 = plt.subplot(211)
plt.suptitle("Commodity Channel Index")
plt.ylabel("CCI Index")
plt.xlabel("Date")
ax1.plot(cci, label="CCI", color="purple", lw=0.8)
plt.grid(which='both', axis='both', linestyle="--")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.axhline(y=0, color="red", lw=0.5)
plt.legend(loc="best", frameon=True)
ax2 = plt.subplot(212)
plt.ylabel("Normalized Prices")
plt.xlabel("Date")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.grid(which='both', axis='both', linestyle="--")
ax2.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
plt.legend(loc="best", frameon=True)
fig.autofmt_xdate()
plt.savefig("cci.png")
plt.clf()
# Indicator 5 Graphs
macd_line, signal_line = calculate_moving_average_convergence_divergence(normalized_prices_df)
fig = plt.figure(figsize=(10, 6))
plt.suptitle("Moving Average Convergence Divergence")
ax1 = plt.subplot(211)
plt.grid(which='both', axis='both', linestyle="--")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.ylabel("MACD Index")
plt.xlabel("Date")
ax1.plot(macd_line, label="MACD", color="purple", lw=0.8)
ax1.plot(signal_line, label="Signal Line", color="blue", lw=0.8)
plt.legend(loc="best", frameon=True)
short_ema = normalized_prices_df.ewm(ignore_na=False, span=12, adjust=True).mean()
long_ema = normalized_prices_df.ewm(ignore_na=False, span=26, adjust=True).mean()
ax2 = plt.subplot(212)
plt.ylabel("Normalized Prices")
plt.xlabel("Date")
plt.tick_params(axis='x', which='major', labelsize=10)
plt.grid(which='both', axis='both', linestyle="--")
plt.plot(normalized_prices_df, label="JPM Prices", color="blue", lw=0.8)
ax2.plot(short_ema, label="Short EMA", color="purple", lw=0.8)
ax2.plot(long_ema, label="Long EMA", color="orange", lw=0.8)
plt.legend(loc="best", frameon=True)
fig.autofmt_xdate()
plt.savefig("macd.png")
plt.clf()
if __name__ == "__main__":
pd.set_option('display.max_rows', None) # Display all rows
pd.set_option('display.max_columns', None) # Display all columns
test_code()