如何用统计分析创建移动平均函数?

时间:2018-08-07 13:32:02

标签: python pandas statistics time-series moving-average

def adf(ts):

# Determing rolling statistics
rolmean = pd.rolling_mean(ts, window=12)
rolstd = pd.rolling_std(ts, window=12)
#Plot rolling statistics:
orig = plt.plot(ts, color='blue',label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd, color='black', label = 'Rolling Std')
plt.legend(loc='best')
plt.title('Rolling Mean & Standard Deviation')
plt.show(block=False)

# Calculate ADF factors
adftest = adfuller(ts, autolag='AIC')
adfoutput = pd.Series(adftest[0:4], index=['Test Statistic','p-value','# of Lags Used',
                                          'Number of Observations Used'])
for key,value in adftest[4].items():
    adfoutput['Critical Value (%s)'%key] = value
return adfoutput**

上面我创建了计算MA窗口5的函数。 但是当我运行以下代码时,我得到了错误。.

df['priceModLogMA12'] = pd.rolling_mean(df.priceModLog, window = 5)**
AttributeError: module 'pandas' has no attribute 'rolling_mean'

2 个答案:

答案 0 :(得分:2)

我认为我们应该使用

rolmean = ts.rolling(window=12).mean()

代替

rolmean = pd.rolling_mean(ts, window=12)

因为不赞成使用pd.rolling_mean

编辑

只是改变

rolmean = pd.rolling_mean(ts, window=12)
rolstd = pd.rolling_std(ts, window=12)

收件人

rolmean = ts.rolling(window=12).mean()
rolstd = ts.rolling(window=12).std()

编辑

如果您正在谈论这条线,请从以下位置更改

df['priceModLogMA12'] = pd.rolling_mean(df.priceModLog, window = 5)

收件人

df['priceModLogMA12'] = df.priceModLog.rolling(window = 5).mean()

答案 1 :(得分:1)

rolling_mean已在熊猫中删除。相反,您应该使用pandas.DataFrame.rolling,然后应用mean()。看一下here。您可以像这样编辑它:

ts.rolling(window=12).mean()