Python

正確計算布林帶

  • August 31, 2017

我的布林帶如下圖所示,這似乎不正確。知道我計算上下布林帶的程式碼有什麼問題嗎?

我從這裡獲得了我的數據

start, end = dt.datetime(1976, 1, 1), dt.datetime(2013, 12, 31)
sp = web.DataReader('^GSPC','yahoo', start, end) 
here are my bollinger calculations

布林帶計算

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)

在此處輸入圖像描述

在Pandas 0.19.2++ 中:

def Bolinger_Bands(stock_price, window_size, num_of_std):

   rolling_mean = stock_price.rolling(window=window_size).mean()
   rolling_std  = stock_price.rolling(window=window_size).std()
   upper_band = rolling_mean + (rolling_std*num_of_std)
   lower_band = rolling_mean - (rolling_std*num_of_std)

   return rolling_mean, upper_band, lower_band

def main():

    price_series = get_data(ticker, dates) # it is a Pandas series...

    rolling_avg_price, upper_band, lower_band = Bolinger_Bands(price_series, 20, 2)

    do_other_processing(rolling_avg_price, upper_band, lower_band)
    ...
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()

在此處輸入圖像描述

引用自:https://quant.stackexchange.com/questions/11264