SARIMAX: Model selection, missing data¶
The example mirrors Durbin and Koopman (2012), Chapter 8.4 in application of Box-Jenkins methodology to fit ARMA models. The novel feature is the ability of the model to work on datasets with missing values.
[1]:
%matplotlib inline
[2]:
import numpy as np
import pandas as pd
from scipy.stats import norm
import statsmodels.api as sm
import matplotlib.pyplot as plt
[3]:
import requests
from io import BytesIO
from zipfile import ZipFile
# Download the dataset
dk = requests.get('http://www.ssfpack.com/files/DK-data.zip').content
f = BytesIO(dk)
zipped = ZipFile(f)
df = pd.read_table(
BytesIO(zipped.read('internet.dat')),
skiprows=1, header=None, sep='\s+', engine='python',
names=['internet','dinternet']
)
---------------------------------------------------------------------------
ProxySchemeUnknown Traceback (most recent call last)
<ipython-input-3-074aec8a1161> in <module>
4
5 # Download the dataset
----> 6 dk = requests.get('http://www.ssfpack.com/files/DK-data.zip').content
7 f = BytesIO(dk)
8 zipped = ZipFile(f)
/usr/lib/python3/dist-packages/requests/api.py in get(url, params, **kwargs)
73
74 kwargs.setdefault('allow_redirects', True)
---> 75 return request('get', url, params=params, **kwargs)
76
77
/usr/lib/python3/dist-packages/requests/api.py in request(method, url, **kwargs)
58 # cases, and look like a memory leak in others.
59 with sessions.Session() as session:
---> 60 return session.request(method=method, url=url, **kwargs)
61
62
/usr/lib/python3/dist-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
531 }
532 send_kwargs.update(settings)
--> 533 resp = self.send(prep, **send_kwargs)
534
535 return resp
/usr/lib/python3/dist-packages/requests/sessions.py in send(self, request, **kwargs)
644
645 # Send the request
--> 646 r = adapter.send(request, **kwargs)
647
648 # Total elapsed time of the request (approximately)
/usr/lib/python3/dist-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
410
411 try:
--> 412 conn = self.get_connection(request.url, proxies)
413 except LocationValueError as e:
414 raise InvalidURL(e, request=request)
/usr/lib/python3/dist-packages/requests/adapters.py in get_connection(self, url, proxies)
307 raise InvalidProxyURL("Please check proxy URL. It is malformed"
308 " and could be missing the host.")
--> 309 proxy_manager = self.proxy_manager_for(proxy)
310 conn = proxy_manager.connection_from_url(url)
311 else:
/usr/lib/python3/dist-packages/requests/adapters.py in proxy_manager_for(self, proxy, **proxy_kwargs)
197 maxsize=self._pool_maxsize,
198 block=self._pool_block,
--> 199 **proxy_kwargs)
200
201 return manager
/usr/lib/python3/dist-packages/urllib3/poolmanager.py in proxy_from_url(url, **kw)
468
469 def proxy_from_url(url, **kw):
--> 470 return ProxyManager(proxy_url=url, **kw)
/usr/lib/python3/dist-packages/urllib3/poolmanager.py in __init__(self, proxy_url, num_pools, headers, proxy_headers, **connection_pool_kw)
418
419 if proxy.scheme not in ("http", "https"):
--> 420 raise ProxySchemeUnknown(proxy.scheme)
421
422 self.proxy = proxy
ProxySchemeUnknown: Not supported proxy scheme None
Model Selection¶
As in Durbin and Koopman, we force a number of the values to be missing.
[4]:
# Get the basic series
dta_full = df.dinternet[1:].values
dta_miss = dta_full.copy()
# Remove datapoints
missing = np.r_[6,16,26,36,46,56,66,72,73,74,75,76,86,96]-1
dta_miss[missing] = np.nan
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-70c0b0b5593e> in <module>
1 # Get the basic series
----> 2 dta_full = df.dinternet[1:].values
3 dta_miss = dta_full.copy()
4
5 # Remove datapoints
NameError: name 'df' is not defined
Then we can consider model selection using the Akaike information criteria (AIC), but running the model for each variant and selecting the model with the lowest AIC value.
There are a couple of things to note here:
- When running such a large batch of models, particularly when the autoregressive and moving average orders become large, there is the possibility of poor maximum likelihood convergence. Below we ignore the warnings since this example is illustrative.
- We use the option
enforce_invertibility=False, which allows the moving average polynomial to be non-invertible, so that more of the models are estimable. - Several of the models do not produce good results, and their AIC value is set to NaN. This is not surprising, as Durbin and Koopman note numerical problems with the high order models.
[5]:
import warnings
aic_full = pd.DataFrame(np.zeros((6,6), dtype=float))
aic_miss = pd.DataFrame(np.zeros((6,6), dtype=float))
warnings.simplefilter('ignore')
# Iterate over all ARMA(p,q) models with p,q in [0,6]
for p in range(6):
for q in range(6):
if p == 0 and q == 0:
continue
# Estimate the model with no missing datapoints
mod = sm.tsa.statespace.SARIMAX(dta_full, order=(p,0,q), enforce_invertibility=False)
try:
res = mod.fit(disp=False)
aic_full.iloc[p,q] = res.aic
except:
aic_full.iloc[p,q] = np.nan
# Estimate the model with missing datapoints
mod = sm.tsa.statespace.SARIMAX(dta_miss, order=(p,0,q), enforce_invertibility=False)
try:
res = mod.fit(disp=False)
aic_miss.iloc[p,q] = res.aic
except:
aic_miss.iloc[p,q] = np.nan
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-bcbba42f81f2> in <module>
13
14 # Estimate the model with no missing datapoints
---> 15 mod = sm.tsa.statespace.SARIMAX(dta_full, order=(p,0,q), enforce_invertibility=False)
16 try:
17 res = mod.fit(disp=False)
NameError: name 'dta_full' is not defined
For the models estimated over the full (non-missing) dataset, the AIC chooses ARMA(1,1) or ARMA(3,0). Durbin and Koopman suggest the ARMA(1,1) specification is better due to parsimony.
For the models estimated over missing dataset, the AIC chooses ARMA(1,1)
Note: the AIC values are calculated differently than in Durbin and Koopman, but show overall similar trends.
Postestimation¶
Using the ARMA(1,1) specification selected above, we perform in-sample prediction and out-of-sample forecasting.
[6]:
# Statespace
mod = sm.tsa.statespace.SARIMAX(dta_miss, order=(1,0,1))
res = mod.fit(disp=False)
print(res.summary())
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-8dd911607628> in <module>
1 # Statespace
----> 2 mod = sm.tsa.statespace.SARIMAX(dta_miss, order=(1,0,1))
3 res = mod.fit(disp=False)
4 print(res.summary())
NameError: name 'dta_miss' is not defined
[7]:
# In-sample one-step-ahead predictions, and out-of-sample forecasts
nforecast = 20
predict = res.get_prediction(end=mod.nobs + nforecast)
idx = np.arange(len(predict.predicted_mean))
predict_ci = predict.conf_int(alpha=0.5)
# Graph
fig, ax = plt.subplots(figsize=(12,6))
ax.xaxis.grid()
ax.plot(dta_miss, 'k.')
# Plot
ax.plot(idx[:-nforecast], predict.predicted_mean[:-nforecast], 'gray')
ax.plot(idx[-nforecast:], predict.predicted_mean[-nforecast:], 'k--', linestyle='--', linewidth=2)
ax.fill_between(idx, predict_ci[:, 0], predict_ci[:, 1], alpha=0.15)
ax.set(title='Figure 8.9 - Internet series');
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-394a7033843a> in <module>
1 # In-sample one-step-ahead predictions, and out-of-sample forecasts
2 nforecast = 20
----> 3 predict = res.get_prediction(end=mod.nobs + nforecast)
4 idx = np.arange(len(predict.predicted_mean))
5 predict_ci = predict.conf_int(alpha=0.5)
NameError: name 'res' is not defined