简体   繁体   中英

AR model in statsmodels

I am trying to fit a Time Series Auto Regressive model in Python

Input DF:

code                                test_col  

2018-09-20 18:00:00                      10                      
2018-09-20 19:00:00                      20                     
2018-09-20 20:00:00                      21                       
2018-09-20 21:00:00                      17                      
2018-09-20 22:00:00                      7 

Index of the DF:

DatetimeIndex(['2018-09-20 18:00:00'.......]

Model:

 mod = AR(DF[test_col])
 res = mod.fit(maxlag= 20, ic= 'aic')
 last_hour = df.index[[len(df)-1]]
 pred = res.predict(start=last_hour[0],end = last_hour[0] )

last_hour => fetches the latest timestamp from the index for which I want to predict

Error:

File "pandas/tslib.pyx", line 1280, in pandas.tslib._Timestamp.__sub__ (pandas/tslib.c:23914)
TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'int'

I checked the type of the "last_hour"

print (type(last_hour))
<class 'pandas.tseries.index.DatetimeIndex'>

Any suggestions on how to rectify this.

将熊猫从V-19更新到23.解决了此问题。

I think there is an issue with the way the datetime index is cast in your dataframe because the following lines of code work for me:

import pandas as pd
from statsmodels.tsa.ar_model import AR
DF = pd.DataFrame({'code': ['2018-09-20 18:00:00', '2018-09-20 19:00:00', '2018-09-20 20:00:00', '2018-09-20 21:00:00', '2018-09-20 22:00:00'],
                   'test_col': [10, 20, 21, 17, 7]})
DF['code'] = pd.to_datetime(DF['code'])
DF = DF.set_index('code')
mod = AR(DF['test_col'])
res = mod.fit(maxlag= 2, ic= 'aic')
last_hour = DF.index[[len(DF)-1]]
pred = res.predict(start=last_hour[0],end = last_hour[0])

Checking the last_hour object gives

print(last_hour)
DatetimeIndex(['2018-09-20 22:00:00'], dtype='datetime64[ns]', name='code', freq=None)

One thing to try would be to reset_index, then convert the column to datetime, then set it to index again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM