Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created August 18, 2019 03:50
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/e23a551eafe5e516a0e4b8805091970e to your computer and use it in GitHub Desktop.
Save yuyasugano/e23a551eafe5e516a0e4b8805091970e to your computer and use it in GitHub Desktop.
Matplotlib Bollinger sample
def Bollinger(df, window=25):
df1 = df.copy()
df1["ma"] = df1.close.rolling(window=window).mean()
df1["sigma"] = df1.close.rolling(window=window).std()
df1["ma+2sigma"] = df1.ma + 2*df1.sigma
df1["ma-2sigma"] = df1.ma - 2*df1.sigma
df1["diffplus"] = df1.close - df1["ma+2sigma"]
df1["diffminus"] = df1["ma-2sigma"] - df1.close
s_up = df1[df1["diffplus"] > 0]["close"]
s_down = df1[df1["diffminus"] > 0]["close"]
xdate = [x.date() for x in df1.index]
plt.figure(figsize=(15,5))
plt.grid()
plt.xlim(xdate[0], xdate[-1])
plt.scatter(s_up.index, s_up.values,marker="x", s=100, color="blue")
plt.scatter(s_down.index, s_down.values,marker="x", s=100, color="red")
plt.plot(xdate, df1.close.values, label="original", color="b", alpha=0.9)
plt.plot(xdate, df1.ma.values, label="{}ma".format(window))
plt.fill_between(xdate, df1.ma-df1.sigma, df1.ma+df1.sigma, color="red", alpha=0.7, label="$1\sigma$")
plt.fill_between(xdate, df1.ma-2*df1.sigma, df1.ma+2*df1.sigma, color="red", alpha=0.3, label="$2\sigma$")
plt.fill_between(xdate, df1.ma-3*df1.sigma, df1.ma+3*df1.sigma, color="red", alpha=0.1, label="$3\sigma$")
plt.legend()
Bollinger(df, window=25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment