Logo

Using dates with timeseries models

In [1]: import statsmodels.api as sm

In [2]: import numpy as np

In [3]: import pandas

Getting started

In [4]: data = sm.datasets.sunspots.load()

Right now an annual date series must be datetimes at the end of the year.

In [5]: from datetime import datetime

In [6]: dates = sm.tsa.datetools.dates_from_range('1700', length=len(data.endog))

Using Pandas

Make a pandas TimeSeries or DataFrame

In [7]: endog = pandas.TimeSeries(data.endog, index=dates)

and instantiate the model

In [8]: ar_model = sm.tsa.AR(endog, freq='A')

In [9]: pandas_ar_res = ar_model.fit(maxlag=9, method='mle', disp=-1)

Let’s do some out-of-sample prediction

In [10]: pred = pandas_ar_res.predict(start='2005', end='2015')

In [11]: print pred
2005-12-31    20.003288
2006-12-31    24.703987
2007-12-31    20.026133
2008-12-31    23.473648
2009-12-31    30.858579
2010-12-31    61.335452
2011-12-31    87.024692
2012-12-31    91.321251
2013-12-31    79.921621
2014-12-31    60.799510
2015-12-31    40.374856

Using explicit dates

In [12]: ar_model = sm.tsa.AR(data.endog, dates=dates, freq='A')

In [13]: ar_res = ar_model.fit(maxlag=9, method='mle', disp=-1)

In [14]: pred = ar_res.predict(start='2005', end='2015')

In [15]: print pred
[ 20.00328761  24.70398736  20.02613288  23.47364837  30.85857901
  61.33545245  87.02469212  91.32125134  79.92162132  60.79951027
  40.37485636]

This just returns a regular array, but since the model has date information attached, you can get the prediction dates in a roundabout way.

In [16]: print ar_res._data.predict_dates
[1970-01-14 224:00:00 1970-01-14 24:00:00 1970-01-14 80:00:00
 1970-01-15 224:00:00 1970-01-15 24:00:00 1970-01-15 80:00:00
 1970-01-16 200:00:00 1970-01-16 24:00:00 1970-01-17 144:00:00
 1970-01-17 200:00:00 1970-01-17 00:00:00]

This attribute only exists if predict has been called. It holds the dates associated with the last call to predict. .. TODO: should this be attached to the results instance?

Table Of Contents

This Page