-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMACD.py
199 lines (155 loc) · 5.58 KB
/
MACD.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
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
import mplfinance as mpf
def loadStocks(start, end, stock):
df = yf.download(stock, start, end, interval='1d')
return df
def findSMA(short_sma, long_sma, df):
SMAs = [short_sma, long_sma]
for i in SMAs:
df["SMA_" + str(i)] = df.iloc[:, 4].rolling(window=i).mean()
return df, SMAs
def findMACD(data):
# SMA
arraySMA = [0] * data.shape[0]
arraySMA = data.iloc[:, 4].rolling(window=10).mean()
# Temp SMA values until I figure out how this should really work
yesterdayEMA12 = arraySMA[12]
yesterdayEMA26 = arraySMA[26]
yesterdaySignal = 20
# Generating Arrays with a size that is the number of rows
arrayEMA12 = [0] * data.shape[0]
arrayEMA26 = [0] * data.shape[0]
arrayMACD = [0] * data.shape[0]
arraySignal = [0] * data.shape[0]
for i in range(len(data.index)):
# Skip the first few to get a good moving average
if i < 13:
continue
# Calculate the 12EMA, 26EMA, and MACD and store the values in respective arrays
todayEMA12 = (data['Adj Close'][i] * (2 / (1 + 12))) + yesterdayEMA12 * (1 - (2 / (1 + 12)))
yesterdayEMA12 = todayEMA12
if i < 27:
continue
todayEMA26 = (data['Adj Close'][i] * (2 / (1 + 26))) + yesterdayEMA26 * (1 - (2 / (1 + 26)))
todayMACD = todayEMA12 - todayEMA26
yesterdayEMA26 = todayEMA26
if i == 27:
yesterdaySignal = todayMACD
continue
todaySignal = (todayMACD * (2 / (1 + 9))) + yesterdaySignal * (1 - (2 / (1 + 9)))
# Previous EMA values to calculate next EMA value
yesterdaySignal = todaySignal
# Array of MACD values
arrayMACD[i] = todayMACD
# Array of Signal (9 EMA of MACD)
arraySignal[i] = todaySignal
# Store Arrays into dataframe
data['MACD'] = arrayMACD
data['Signal'] = arraySignal
fig = plt.figure(num=1, clear=True)
ax = fig.add_subplot(1, 1, 1)
ax.plot(arrayMACD, label='MACD')
ax.plot(arraySignal, label='Signal Line')
ax.legend()
ax.set(title='MACD (12, 26, 9) - SPY', ylabel='Indicator Value', xlim=(0, 2516))
ax.set_xticklabels(['2010-Jan-04', '2011-Dec-27', '2013-Dec-23', '2015-Dec-17', '2017-Dec-12', '2019-Dec-09'])
plt.show()
# Return the dataframe
return data
def tradeSMA(df, short_sma, long_sma):
position = 0
counter = 0
percentChange = []
for i in df.index:
SMA_short = df["SMA_" + str(short_sma)]
SMA_long = df["SMA_" + str(long_sma)]
close = df['Adj Close'][i]
# buy
if (SMA_short[i] > SMA_long[i]):
if (position == 0):
buyP = close # buy price
position = 1 # turn position
# sell
elif (SMA_short[i] < SMA_long[i]):
if (position == 1): # have a position in down trend
position = 0 # selling position
sellP = close # sell price
perc = (sellP / buyP - 1) * 100
percentChange.append(perc)
if (counter == df["Adj Close"].count() - 1 and position == 1):
position = 0
sellP = close
perc = (sellP / buyP - 1) * 100
percentChange.append(perc)
counter += 1
return percentChange
def tradeMACD(df):
position = 0
counter = 0
percentChange = []
for i in df.index:
close = df['Adj Close'][i]
# buy
if (df['MACD'][i] > df['Signal'][i]):
if (position == 0):
buyP = close # buy price
position = 1 # turn position
# sell
elif (df['MACD'][i] < df['Signal'][i]):
if (position == 1): # have a position in down trend
position = 0 # selling position
sellP = close # sell price
perc = (sellP / buyP - 1) * 100
percentChange.append(perc)
if (counter == df["Adj Close"].count() - 1 and position == 1):
position = 0
sellP = close
perc = (sellP / buyP - 1) * 100
percentChange.append(perc)
counter += 1
return percentChange
def calcReturn(percentChange, df):
gains = 0
numGains = 0
losses = 0
numLosses = 0
totReturn = 1
for i in percentChange:
if (i > 0):
gains += i
numGains += 1
else:
losses += i
numLosses += 1
totReturn = totReturn * ((i / 100) + 1)
totReturn = round((totReturn - 1) * 100, 2)
totTrades = numGains + numLosses
return totTrades, totReturn
def SMA(start, end, stock, short_sma, long_sma, plot=False):
df = loadStocks(start, end, stock)
df_updated, SMAs = findSMA(short_sma, long_sma, df)
percentChange = tradeSMA(df_updated, short_sma, long_sma)
if plot == True:
mpf.plot(df, type='ohlc', figratio=(16, 6),
mav=(short_sma, long_sma),
# volume=True,
title= str('MACD (12, 26, 9) - SPY'), style='charles')
# print(df_updated)
return calcReturn(percentChange, df_updated)
def MACD(start, end, stock):
df = loadStocks(start, end, stock)
df = findMACD(df)
percentChange = tradeMACD(df)
return calcReturn(percentChange, df)
def main():
start = ['2010-01-01']
end = ['2020-01-01']
stocks = ['SPY', 'VGT', 'XLV']
short_sma = [10, 20, 30]
long_sma = [50, 60, 70, 80]
print(MACD(start[0], end[0], stocks[2]))
SMA(start[0], end[0], stocks[0], short_sma[0], long_sma[0], False)
main()