Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created August 18, 2019 03:17
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/0f9a8214997965ee7d009f28de18529f to your computer and use it in GitHub Desktop.
Save yuyasugano/0f9a8214997965ee7d009f28de18529f to your computer and use it in GitHub Desktop.
Matplotlib Moving Average sample
# df copy
df_ = df.copy()
df_["ma25"] = df_.close.rolling(window=25).mean()
df_["ma75"] = df_.close.rolling(window=75).mean()
df_["diff"] = df_.ma25-df_.ma75
df_["unixtime"] = [datetime.timestamp(t) for t in df.index]
# line and Moving Average
xdate = [x.date() for x in df_.index]
plt.figure(figsize=(15,5))
plt.plot(xdate, df_.close,label="original")
plt.plot(xdate, df_.ma75,label="75days")
plt.plot(xdate, df_.ma25,label="25days")
plt.xlim(xdate[0], xdate[-1])
plt.grid()
# Cross points
for i in range(1, len(df_)):
if df_.iloc[i-1]["diff"] < 0 and df_.iloc[i]["diff"] > 0:
print("{}:GOLDEN CROSS".format(xdate[i]))
plt.scatter(xdate[i], df_.iloc[i]["ma25"], marker="o", s=100, color="b")
plt.scatter(xdate[i], df_.iloc[i]["close"], marker="o", s=50, color="b", alpha=0.5)
if df_.iloc[i-1]["diff"] > 0 and df_.iloc[i]["diff"] < 0:
print("{}:DEAD CROSS".format(xdate[i]))
plt.scatter(xdate[i], df_.iloc[i]["ma25"], marker="o", s=100, color="r")
plt.scatter(xdate[i], df_.iloc[i]["close"], marker="o", s=50, color="r", alpha=0.5)
plt.legend()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment