Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created August 18, 2019 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuyasugano/f2dae73fdf346ae82907043533cd6208 to your computer and use it in GitHub Desktop.
Save yuyasugano/f2dae73fdf346ae82907043533cd6208 to your computer and use it in GitHub Desktop.
Matplotlib MACD sample
def MACD(df):
df1 = df.copy()
df1["MACD"] = df1.close.ewm(span=12, min_periods=1).mean() - df1.close.ewm(span=26, min_periods=1).mean()
df1["signal"] = df1.MACD.ewm(span=9, min_periods=1).mean()
df1["macd_diff"] = df1["MACD"] - df1["signal"]
xdate = [x.date() for x in df1.index]
plt.figure(figsize=(15,10))
# plot the original
plt.subplot(211)
plt.plot(xdate, df1.close,label="original")
plt.xlim(xdate[0], xdate[-1])
plt.legend()
plt.grid()
# plot MACD
plt.subplot(212)
plt.title("MACD")
plt.plot(xdate, df1.MACD, label="MACD")
plt.plot(xdate, df1.signal, label="signal")
plt.xlim(xdate[0], xdate[-1])
plt.legend()
plt.grid(True)
# Cross points
for i in range(1, len(df1)):
if df1.iloc[i-1]["macd_diff"] < 0 and df1.iloc[i]["macd_diff"] > 0:
print("{}:GOLDEN CROSS".format(xdate[0]))
plt.scatter(xdate[i], df1.iloc[i]["MACD"], marker="o", s=100, color="b")
if df1.iloc[i-1]["macd_diff"] > 0 and df1.iloc[i]["macd_diff"] < 0:
print("{}:DEAD CROSS".format(xdate[0]))
plt.scatter(xdate[i], df1.iloc[i]["MACD"], marker="o", s=100, color="r")
MACD(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment