17

Is anyone else having trouble with the new rolling.std() in pandas? The deprecated method was rolling_std(). The new method runs fine but produces a constant number that does not roll with the time series.

Sample code is below. If you trade stocks, you may recognize the formula for Bollinger bands. The output I get from rolling.std() tracks the stock day by day and is obviously not rolling.

This in in pandas 0.19.1. Any help would be appreciated.

import datetime
import pandas as pd
import pandas_datareader.data as web

start = datetime.datetime(2012,1,1)
end = datetime.datetime(2012,12,31)
g = web.DataReader(['AAPL'], 'yahoo', start, end)
stocks = g['Close']
stocks['Date'] = pd.to_datetime(stocks.index)
stocks['AAPL_LO'] = stocks['AAPL'] - stocks['AAPL'].rolling(20).std() * 2
stocks['AAPL_HI'] = stocks['AAPL'] + stocks['AAPL'].rolling(20).std() * 2
stocks.dropna(axis=0, how='any', inplace=True)
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Mark
  • 1,079
  • 1
  • 9
  • 8
  • Can you add the output you're actually expecting? – Julien Marrec Nov 22 '16 at 12:59
  • 3
    `stocks['AAPL'].rolling(20).std()` gives exactly the same output as `pd.rolling_std(stocks['AAPL'], window=20)`... – Julien Marrec Nov 22 '16 at 13:01
  • 3
    I can't reproduce here: it sounds as though you're saying `stocks['AAPL'].rolling(20).std()` is constant, but I see a non-constant time-varying result. For example, plotting, I see much thinner bands at around the July 2012 mark from those at around April 2012. – Mark Dickinson Nov 22 '16 at 13:05
  • Thanks for showing std() is working correctly. I had expected the 20-day lookback to be smoother, but it seems I will have to use mean() as well. – Mark Nov 23 '16 at 20:57

1 Answers1

21
import pandas as pd
from pandas_datareader import data as pdr
import numpy as np
import datetime

end = datetime.date.today()
begin=end-pd.DateOffset(365*10)
st=begin.strftime('%Y-%m-%d')
ed=end.strftime('%Y-%m-%d')


data = pdr.get_data_yahoo("AAPL",st,ed)

def bollinger_strat(data, window, no_of_std):
    rolling_mean = data['Close'].rolling(window).mean()
    rolling_std = data['Close'].rolling(window).std()

    df['Bollinger High'] = rolling_mean + (rolling_std * no_of_std)
    df['Bollinger Low'] = rolling_mean - (rolling_std * no_of_std)     

bollinger_strat(data,20,2)