Calculating Bollinger Band Correctly

My bollinger band comes out like the below, which doesn't seem right. Any idea what is wrong with my code for calculating upper and lower bollinber bands?

I obtained my data from here

start, end = dt.datetime(1976, 1, 1), dt.datetime(2013, 12, 31)
here are my bollinger calculations


calculation for bollinger band

ave = pd.stats.moments.rolling_mean(self[name], window)
std = pd.stats.moments.rolling_std(self[name], window)
self['upper'] = ave + (2 * std)
self['lower'] = ave - (2 * std)


-
I am not into python but looks like that your average (ave) time series does not look right in relation to "SP", at least ave does not converge with "SP". – Matt Wolf May 13 '14 at 5:53
Perhaps try to plot ave to see where it is, and perhaps on a different window plot std to see its size. Providing a full code might be helpful as well. – Bach May 13 '14 at 6:41
@Bach I second the recommendation on providing more code (or perhaps a simplified version that can reproduce the plot from scratch). – John May 14 '14 at 14:35
Seems like the rolling Standard deviation for the $lower$ band is slightly lagging the $SP$ ... Make sure the rolling window is the same for both the upper & lower bands – Rime Dec 11 '14 at 6:45

def bbands(price, length=30, numsd=2):
""" returns average, upper band, and lower band"""
ave = pd.stats.moments.rolling_mean(price,length)
sd = pd.stats.moments.rolling_std(price,length)
upband = ave + (sd*numsd)
dnband = ave - (sd*numsd)
return np.round(ave,3), np.round(upband,3), np.round(dnband,3)

sp['ave'], sp['upper'], sp['lower'] = bbands(sp.Close, length=30, numsd=1)
sp= sp[-200:]
sp.plot()


-

Try to plot the rolling mean against your quotes for SP and see if it makes sense. Although you line of code to compute the rolling mean is correct, there might be something wrong in the data that you pass as input.

-