Pandas standard deviation rolling

Anyone else have problems with the new rolling.std()in pandas? The outdated method was rolling_std(). The new method works fine, but creates a constant number that does not roll with time series.

The following is sample code. If you trade stocks, you can recognize the formula for Bollinger Bands. The output I get from rolling.std()tracks stocks day after day and obviously does not work.

This is in pandas 0.19.1. Any help would be greatly 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)
+4
source share
1 answer
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)
+1
source

Source: https://habr.com/ru/post/1661581/


All Articles