如何正确设置statsmodels.tsa.ar_model.AR.predict函数的开始/结束参数

时间:2017-05-07 19:10:51

标签: python pandas statsmodels

我有一个不规则间隔时间序列的项目成本数据框,我想尝试应用statsmodel AR model against

这是其数据框中的数据样本:

               cost
date               
2015-07-16    35.98
2015-08-11    25.00
2015-08-11    43.94
2015-08-13    26.25
2015-08-18    15.38
2015-08-24    77.72
2015-09-09    40.00
2015-09-09    20.00
2015-09-09    65.00
2015-09-23    70.50
2015-09-29    59.00
2015-11-03    19.25
2015-11-04    19.97
2015-11-10    26.25
2015-11-12    19.97
2015-11-12    23.97
2015-11-12    21.88
2015-11-23    23.50
2015-11-23    33.75
2015-11-23    22.70
2015-11-23    33.75
2015-11-24    27.95
2015-11-24    27.95
2015-11-24    27.95
...
2017-03-31    21.93
2017-04-06    22.45
2017-04-06    26.85
2017-04-12    60.40
2017-04-12    37.00
2017-04-12    20.00
2017-04-12    66.00
2017-04-12    60.00
2017-04-13    41.95
2017-04-13    25.97
2017-04-13    29.48
2017-04-19    41.00
2017-04-19    58.00
2017-04-19    78.00
2017-04-19    12.00
2017-04-24    51.05
2017-04-26    21.88
2017-04-26    50.05
2017-04-28    21.00
2017-04-28    30.00

我很难理解如何在start函数中使用endpredict

根据the docs

  

start:int,str或datetime   用于开始预测的零索引观察数,即,第一个>预测开始了。也可以是要解析的日期字符串或日期时间类型。

     

end:int,str或datetime零索引观察数   结束预测,即第一个预测开始。也可以是   要解析的日期字符串或日期时间类型。

我创建了一个每日时间系列为空的数据框,将不规则间隔的时间序列数据添加到其中,然后尝试应用该模型。

data = pd.read_csv('data.csv', index_col=1, parse_dates=True)
df = pd.DataFrame(index=pd.date_range(start=datetime(2015, 1, 1), end=datetime(2017, 12, 31), freq='d'))
df = df.join(data)
df.cost.interpolate(inplace=True)
ar_model = sm.tsa.AR(df, missing='drop', freq='D')
ar_res = ar_model.fit(maxlag=9, method='mle', disp=-1)
pred = ar_res.predict(start='2016', end='2016')

predict函数导致错误pandas.tslib.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 605-12-31 00:00:00

如果我尝试使用更具体的日期,我会收到相同类型的错误:

pred = ar_res.predict(start='2016-01-01', end='2016-06-01')    

如果我尝试使用整数,我会得到一个不同的错误:

pred = ar_res.predict(start=0, end=len(data))
Wrong number of items passed 202, placement implies 197

如果我实际使用datetime,则会收到显示为no rule for interpreting end的错误。

我在这里如此努力地撞墙,我想我肯定会有一些错过的东西。

最终,我想使用该模型进行样本外预测(例如下一季度的预测)。

2 个答案:

答案 0 :(得分:1)

如果您传递System.out.println(Arrays.stream(names).max(Comparator.naturalOrder()).get());(而非datetime):

,则此方法有效
date

答案 1 :(得分:0)

所以我创建了一个每日索引来计算等间隔时间序列要求,但它仍然是非唯一的(由@ user333700评论)。

我添加了一个groupby函数来将重复日期加在一起,然后可以使用predict对象运行datetime函数(由@andy-hayden回答)。

df = df.groupby(pd.TimeGrouper(freq='D')).sum()
...
ar_res.predict(start=min(df.index), end=datetime(2018,12,31))

使用predict函数提供结果,我现在能够分析结果并调整参数以获得有用的东西。