pandas 熊猫滚动标准差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40742364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:29:01  来源:igfitidea点击:

Pandas rolling standard deviation

pythonpandasstandard-deviation

提问by Sam

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.

有没有其他人对 Pandas 的新功能有问题rolling.std()?不推荐使用的方法是rolling_std(). 新方法运行良好,但会产生一个不随时间序列滚动的常数。

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.

示例代码如下。如果您交易股票,您可能会认识布林带的公式。我得到的输出rolling.std()每天都在跟踪库存,显然没有滚动。

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

这在Pandas 0.19.1 中。任何帮助,将不胜感激。

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)

回答by Abhishek Kulkarni

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)