import pandas as pd
import matplotlib.pyplot as plt
def Bollinger_Bands (data, n):
MA = data['Close'].rolling(window=n).mean()
SD = data['Close'].rolling(window=n).std()
data['Lower_BB'] = MA - (2 * SD) # Lower Bollinger Band
data['Upper_BB'] = MA + (2 * SD) # Upper Bollinger Band
return data
nifty = pd.read_csv("C:/Users/jnnim/Downloads/TATACHEMBO.csv")
nifty.head()
n = 3 # IN COURSE IT IS n = 21 but when i used my data i had to maek it n = 3 why is it and what is n #doing in code
nifty_bb = Bollinger_Bands(nifty, n)
nifty_bb.tail()
plt.figure(figsize=(10,5))
plt.plot(nifty_bb.Close)
plt.plot(nifty_bb.Lower_BB)
plt.plot(nifty_bb.Upper_BB)
plt.grid(True)
plt.show()
Here n is the size of the moving window. This is the number of observations required for calculating the statistics.
For example, if you want to calculate the rolling mean for window=3 or n=3 of a closing price.
Date 2019-12-31 157.699997 2020-01-02 160.619995 2020-01-03 158.619995 2020-01-06 159.029999 2020-01-07 157.580002 Name: Close, dtype: float64
Then the rolling function for window=3 will calculate the mean of the first three prices that is from 2019-12-31 to 2020-01-03. Then for the next period, it will calculate the mean from 2020-01-02 to 2020-01-06.
Date | Price | Rolling Mean |
---|---|---|
2019-12-31 | 157.699997 | NaN |
2020-01-02 | 160.619995 | NaN |
2020-01-03 | 158.619995 | 158.979996 |
2020-01-06 | 159.029999 | 159.423330 |
2020-01-07 | 157.580002 | 158.409999 |
Here, you get two NaN values as you are calculating the rolling mean from the third period.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html