Search code examples
pythonpandasvariable-length

BollingerBand - rolling_mean - length number


I have a question about Bollinger Band. In the below code, the result occurs only if we give "1" to length. However, giving 1 to length is not logical.

dataframe = pd.DataFrame(data = speed)   
length=2    
def bbands(data, length, numsd=2):    
    ave = pd.stats.moments.rolling_mean(data,length)    
    sd = pd.stats.moments.rolling_std(data,length)    
    upband = ave + (sd*2)    
    dnband = ave - (sd*2)    
    print 'ave:', ave    
    print 'sd:', sd    
    print np.round(ave,3), np.round(upband,3), np.round(dnband,3)    

print bbands(dataframe, length=10, numsd=1)    
print speed    
dataframe['ave'], dataframe['upper'], dataframe['lower'] = bbands(dataframe, length, numsd=1)    
dataframe.plot()

When I attend any number rather than "1" to length, the "ave" is calculated as a below result. (I gave 3 to length, if I increase the length number, the number of NaN also increases)

[1440 rows x 1 columns]          0
0      NaN
1      NaN
2   92.250
3   92.254
4   92.459
5   93.639
6   94.250
.....

Solution

  • It appears the rolling_mean and rolling_std return NaN for the first length - 1 values. This makes sense, since it is calulating those values with length values at a time. You could filter out the NaNs from the resulting data frames:

    ave = pd.stats.moments.rolling_mean(data,length)
    ave = ave.dropna()
    
    sd = pd.stats.moments.rolling_std(data,length)
    sd = sd.dropna()