<jupyter_start><jupyter_text>AutoregressionsThis notebook introduces autoregression modeling using the `AutoReg` model. It also covers aspects of `ar_select_order` assists in selecting models that minimize an information criteria such as the AIC. An autoregressive model has dynamics given by $$ y_t = \delta + \phi_1 y_{t-1} + \ldots + \phi_p y_{t-p} + \epsilon_t. $$`AutoReg` also permits models with:* Deterministic terms (`trend`)  * `n`: No deterministic term   * `c`: Constant (default)  * `ct`: Constant and time trend  * `t`: Time trend only* Seasonal dummies (`seasonal`)  * `True` includes $s-1$ dummies where $s$ is the period of the time series (e.g., 12 for monthly)* Custom deterministic terms (`deterministic`)  * Accepts a `DeterministicProcess`* Exogenous variables (`exog`)  * A `DataFrame` or `array` of exogenous variables to include in the model* Omission of selected lags (`lags`)  * If `lags` is an iterable of integers, then only these are included in the model.The complete specification is$$ y_t = \delta_0 + \delta_1 t + \phi_1 y_{t-1} + \ldots + \phi_p y_{t-p} + \sum_{i=1}^{s-1} \gamma_i d_i + \sum_{j=1}^{m} \kappa_j x_{t,j} + \epsilon_t. $$where:* $d_i$ is a seasonal dummy that is 1 if $mod(t, period) = i$. Period 0 is excluded if the model contains a constant (`c` is in `trend`).* $t$ is a time trend ($1,2,\ldots$) that starts with 1 in the first observation.* $x_{t,j}$ are exogenous regressors.  **Note** these are time-aligned to the left-hand-side variable when defining a model.* $\epsilon_t$ is assumed to be a white noise process. This first cell imports standard packages and sets plots to appear inline.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as pdr
import seaborn as sns
from statsmodels.tsa.ar_model import AutoReg, ar_select_order
from statsmodels.tsa.api import acf, pacf, graphics<jupyter_output><empty_output><jupyter_text>This cell sets the plotting style, registers pandas date converters for matplotlib, and sets the default figure size.<jupyter_code>sns.set_style('darkgrid')
pd.plotting.register_matplotlib_converters()
# Default figure size
sns.mpl.rc('figure',figsize=(16, 6))<jupyter_output><empty_output><jupyter_text>The first set of examples uses the month-over-month growth rate in U.S. Housing starts that has not been seasonally adjusted. The seasonality is evident by the regular pattern of peaks and troughs. We set the frequency for the time series to "MS" (month-start) to avoid warnings when using `AutoReg`.<jupyter_code>data = pdr.get_data_fred('HOUSTNSA', '1959-01-01', '2019-06-01')
housing = data.HOUSTNSA.pct_change().dropna()
# Scale by 100 to get percentages
housing = 100 * housing.asfreq('MS')
fig, ax = plt.subplots()
ax = housing.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>We can start with an AR(3).  While this is not a good model for this data, it demonstrates the basic use of the API.<jupyter_code>mod = AutoReg(housing, 3, old_names=False)
res = mod.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>`AutoReg` supports the same covariance estimators as `OLS`.  Below, we use `cov_type="HC0"`, which is White's covariance estimator. While the parameter estimates are the same, all of the quantities that depend on the standard error change.<jupyter_code>res = mod.fit(cov_type="HC0")
print(res.summary())
sel = ar_select_order(housing, 13, old_names=False)
sel.ar_lags
res = sel.model.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>`plot_predict` visualizes forecasts.  Here we produce a large number of forecasts which show the string seasonality captured by the model.<jupyter_code>fig = res.plot_predict(720, 840)<jupyter_output><empty_output><jupyter_text>`plot_diagnositcs` indicates that the model captures the key features in the data.<jupyter_code>fig = plt.figure(figsize=(16,9))
fig = res.plot_diagnostics(fig=fig, lags=30)<jupyter_output><empty_output><jupyter_text>Seasonal Dummies `AutoReg` supports seasonal dummies which are an alternative way to model seasonality.  Including the dummies shortens the dynamics to only an AR(2).<jupyter_code>sel = ar_select_order(housing, 13, seasonal=True, old_names=False)
sel.ar_lags
res = sel.model.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>The seasonal dummies are obvious in the forecasts which has a non-trivial seasonal component in all periods 10 years in to the future.<jupyter_code>fig = res.plot_predict(720, 840)
fig = plt.figure(figsize=(16,9))
fig = res.plot_diagnostics(lags=30, fig=fig)<jupyter_output><empty_output><jupyter_text>Seasonal Dynamics While `AutoReg` does not directly support Seasonal components since it uses OLS to estimate parameters, it is possible to capture seasonal dynamics using an over-parametrized Seasonal AR that does not impose the restrictions in the Seasonal AR.<jupyter_code>yoy_housing = data.HOUSTNSA.pct_change(12).resample("MS").last().dropna()
_, ax = plt.subplots()
ax = yoy_housing.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>We start by selecting a model using the simple method that only chooses the maximum lag.  All lower lags are automatically included. The maximum lag to check is set to 13 since this allows the model to next a Seasonal AR that has both a short-run AR(1) component and a Seasonal AR(1) component, so that$$ (1-\phi_s L^{12})(1-\phi_1 L)y_t = \epsilon_t $$which becomes$$ y_t = \phi_1 y_{t-1} +\phi_s Y_{t-12} - \phi_1\phi_s Y_{t-13} + \epsilon_t $$when expanded. `AutoReg` does not enforce the structure, but can estimate the nesting model $$ y_t = \phi_1 y_{t-1} +\phi_{12} Y_{t-12} - \phi_{13} Y_{t-13} + \epsilon_t. $$We see that all 13 lags are selected.<jupyter_code>sel = ar_select_order(yoy_housing, 13, old_names=False)
sel.ar_lags<jupyter_output><empty_output><jupyter_text>It seems unlikely that all 13 lags are required.  We can set `glob=True` to search all $2^{13}$ models that include up to 13 lags.Here we see that the first three are selected, as is the 7th, and finally the 12th and 13th are selected.  This is superficially similar to the structure described above.After fitting the model, we take a look at the diagnostic plots that indicate that this specification appears to be adequate to capture the dynamics in the data.<jupyter_code>sel = ar_select_order(yoy_housing, 13, glob=True, old_names=False)
sel.ar_lags
res = sel.model.fit()
print(res.summary())
fig = plt.figure(figsize=(16,9))
fig = res.plot_diagnostics(fig=fig, lags=30)<jupyter_output><empty_output><jupyter_text>We can also include seasonal dummies.  These are all insignificant since the model is using year-over-year changes.<jupyter_code>sel = ar_select_order(yoy_housing, 13, glob=True, seasonal=True, old_names=False)
sel.ar_lags
res = sel.model.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>Industrial ProductionWe will use the industrial production index data to examine forecasting.<jupyter_code>data = pdr.get_data_fred('INDPRO', '1959-01-01', '2019-06-01')
ind_prod = data.INDPRO.pct_change(12).dropna().asfreq('MS')
_, ax = plt.subplots(figsize=(16,9))
ind_prod.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>We will start by selecting a model using up to 12 lags.  An AR(13) minimizes the BIC criteria even though many coefficients are insignificant.<jupyter_code>sel = ar_select_order(ind_prod, 13, 'bic', old_names=False)
res = sel.model.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>We can also use a global search which allows longer lags to enter if needed without requiring the shorter lags. Here we see many lags dropped. The model indicates there may be some seasonality in the data.<jupyter_code>sel = ar_select_order(ind_prod, 13, 'bic', glob=True, old_names=False)
sel.ar_lags
res_glob = sel.model.fit()
print(res.summary())<jupyter_output><empty_output><jupyter_text>`plot_predict` can be used to produce forecast plots along with confidence intervals. Here we produce forecasts starting at the last observation and continuing for 18 months.<jupyter_code>ind_prod.shape
fig = res_glob.plot_predict(start=714, end=732)<jupyter_output><empty_output><jupyter_text>The forecasts from the full model and the restricted model are very similar. I also include an AR(5) which has very different dynamics<jupyter_code>res_ar5 = AutoReg(ind_prod, 5, old_names=False).fit()
predictions = pd.DataFrame({"AR(5)": res_ar5.predict(start=714, end=726),
                            "AR(13)": res.predict(start=714, end=726),
                            "Restr. AR(13)": res_glob.predict(start=714, end=726)})
_, ax = plt.subplots()
ax = predictions.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>The diagnostics indicate the model captures most of the the dynamics in the data. The ACF shows a patters at the seasonal frequency and so a more complete seasonal model (`SARIMAX`) may be needed.<jupyter_code>fig = plt.figure(figsize=(16,9))
fig = res_glob.plot_diagnostics(fig=fig, lags=30)<jupyter_output><empty_output><jupyter_text>ForecastingForecasts are produced using the `predict` method from a results instance. The default produces static forecasts which are one-step forecasts. Producing multi-step forecasts requires using `dynamic=True`.  In this next cell, we produce 12-step-heard forecasts for the final 24 periods in the sample.  This requires a loop.**Note**: These are technically in-sample since the data we are forecasting was used to estimate parameters. Producing OOS forecasts requires two models.  The first must exclude the OOS period.  The second uses the `predict` method from the full-sample model with the parameters from the shorter sample model that excluded the OOS period.<jupyter_code>import numpy as np
start = ind_prod.index[-24]
forecast_index = pd.date_range(start, freq=ind_prod.index.freq, periods=36)
cols = ['-'.join(str(val) for val in (idx.year, idx.month)) for idx in forecast_index]
forecasts = pd.DataFrame(index=forecast_index,columns=cols)
for i in range(1, 24):
    fcast = res_glob.predict(start=forecast_index[i], end=forecast_index[i+12], dynamic=True)
    forecasts.loc[fcast.index, cols[i]] = fcast
_, ax = plt.subplots(figsize=(16, 10))
ind_prod.iloc[-24:].plot(ax=ax, color="black", linestyle="--")
ax = forecasts.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>Comparing to SARIMAX`SARIMAX` is an implementation of a Seasonal Autoregressive Integrated Moving Average with eXogenous regressors model.  It supports:* Specification of seasonal and nonseasonal AR and MA components* Inclusion of Exogenous variables* Full maximum-likelihood estimation using the Kalman FilterThis model is more feature rich than `AutoReg`. Unlike `SARIMAX`, `AutoReg` estimates parameters using OLS.  This is faster and the problem is globally convex, and so there are no issues with local minima. The closed-form estimator and its performance are the key advantages of `AutoReg` over `SARIMAX` when comparing AR(P) models.  `AutoReg` also support seasonal dummies, which can be used with `SARIMAX` if the user includes them as exogenous regressors.<jupyter_code>from statsmodels.tsa.api import SARIMAX

sarimax_mod = SARIMAX(ind_prod, order=((1,5,12,13),0, 0), trend='c')
sarimax_res = sarimax_mod.fit()
print(sarimax_res.summary())
sarimax_params = sarimax_res.params.iloc[:-1].copy()
sarimax_params.index = res_glob.params.index
params = pd.concat([res_glob.params, sarimax_params], axis=1, sort=False)
params.columns = ["AutoReg", "SARIMAX"]
params<jupyter_output><empty_output><jupyter_text>Custom Deterministic ProcessesThe `deterministic` parameter allows a custom `DeterministicProcess` to be used. This allows for more complex deterministic terms to be constructed, for example one that includes seasonal components with two periods, or, as the next example shows, one that uses a Fourier series rather than seasonal dummies.<jupyter_code>from statsmodels.tsa.deterministic import DeterministicProcess
dp = DeterministicProcess(housing.index, constant=True, period=12, fourier=2)
mod = AutoReg(housing,2, trend="n",seasonal=False, deterministic=dp)
res = mod.fit()
print(res.summary())
fig = res.plot_predict(720, 840)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10205915999346299, 'fraction_numerical': 0.019284196764177152, 'mean_word_length': 5.953977272727273, 'pattern_counts': {'":': 3, '<': 89, '<?xml version=': 0, '>': 89, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '22', 'dir': 'jupyter-structured-clean-dedup', 'id': '4577', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 4105, 'n_tokens_neox': 3827, 'n_words': 1308, 'path': 'examples/notebooks/autoregressions.ipynb', 'repo_name': 'chriswmann/statsmodels', 'size': '12238'}