{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SARIMAX: Introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook replicates examples from the Stata ARIMA time series estimation and postestimation documentation.\n",
    "\n",
    "First, we replicate the four estimation examples http://www.stata.com/manuals13/tsarima.pdf:\n",
    "\n",
    "1. ARIMA(1,1,1) model on the U.S. Wholesale Price Index (WPI) dataset.\n",
    "2. Variation of example 1 which adds an MA(4) term to the ARIMA(1,1,1) specification to allow for an additive seasonal effect.\n",
    "3. ARIMA(2,1,0) x (1,1,0,12) model of monthly airline data. This example allows a multiplicative seasonal effect.\n",
    "4. ARMA(1,1) model with exogenous regressors; describes consumption as an autoregressive process on which also the money supply is assumed to be an explanatory variable.\n",
    "\n",
    "Second, we demonstrate postestimation capabilities to replicate http://www.stata.com/manuals13/tsarimapostestimation.pdf. The model from example 4 is used to demonstrate:\n",
    "\n",
    "1. One-step-ahead in-sample prediction\n",
    "2. n-step-ahead out-of-sample forecasting\n",
    "3. n-step-ahead in-sample dynamic prediction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.stats import norm\n",
    "import statsmodels.api as sm\n",
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime\n",
    "import requests\n",
    "from io import BytesIO\n",
    "# Register converters to avoid warnings\n",
    "pd.plotting.register_matplotlib_converters()\n",
    "plt.rc(\"figure\", figsize=(16,8))\n",
    "plt.rc(\"font\", size=14)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ARIMA Example 1: Arima\n",
    "\n",
    "As can be seen in the graphs from Example 2, the Wholesale price index (WPI) is growing over time (i.e. is not stationary). Therefore an ARMA model is not a good specification. In this first example, we consider a model where the original time series is assumed to be integrated of order 1, so that the difference is assumed to be stationary, and fit a model with one autoregressive lag and one moving average lag, as well as an intercept term.\n",
    "\n",
    "The postulated data process is then:\n",
    "\n",
    "$$\n",
    "\\Delta y_t = c + \\phi_1 \\Delta y_{t-1} + \\theta_1 \\epsilon_{t-1} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "where $c$ is the intercept of the ARMA model, $\\Delta$ is the first-difference operator, and we assume $\\epsilon_{t} \\sim N(0, \\sigma^2)$. This can be rewritten to emphasize lag polynomials as (this will be useful in example 2, below):\n",
    "\n",
    "$$\n",
    "(1 - \\phi_1 L ) \\Delta y_t = c + (1 + \\theta_1 L) \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "where $L$ is the lag operator.\n",
    "\n",
    "Notice that one difference between the Stata output and the output below is that Stata estimates the following model:\n",
    "\n",
    "$$\n",
    "(\\Delta y_t - \\beta_0) = \\phi_1 ( \\Delta y_{t-1} - \\beta_0) + \\theta_1 \\epsilon_{t-1} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "where $\\beta_0$ is the mean of the process $y_t$. This model is equivalent to the one estimated in the statsmodels SARIMAX class, but the interpretation is different. To see the equivalence, note that:\n",
    "\n",
    "$$\n",
    "(\\Delta y_t - \\beta_0) = \\phi_1 ( \\Delta y_{t-1} - \\beta_0) + \\theta_1 \\epsilon_{t-1} + \\epsilon_{t} \\\\\n",
    "\\Delta y_t = (1 - \\phi_1) \\beta_0 + \\phi_1 \\Delta y_{t-1} + \\theta_1 \\epsilon_{t-1} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "so that $c = (1 - \\phi_1) \\beta_0$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset\n",
    "wpi1 = requests.get('https://www.stata-press.com/data/r12/wpi1.dta').content\n",
    "data = pd.read_stata(BytesIO(wpi1))\n",
    "data.index = data.t\n",
    "# Set the frequency\n",
    "data.index.freq=\"QS-OCT\"\n",
    "\n",
    "# Fit the model\n",
    "mod = sm.tsa.statespace.SARIMAX(data['wpi'], trend='c', order=(1,1,1))\n",
    "res = mod.fit(disp=False)\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thus the maximum likelihood estimates imply that for the process above, we have:\n",
    "\n",
    "$$\n",
    "\\Delta y_t = 0.0943 + 0.8742 \\Delta y_{t-1} - 0.4120 \\epsilon_{t-1} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "where $\\epsilon_{t} \\sim N(0, 0.5257)$. Finally, recall that $c = (1 - \\phi_1) \\beta_0$, and here $c = 0.0943$ and $\\phi_1 = 0.8742$. To compare with the output from Stata, we could calculate the mean:\n",
    "\n",
    "$$\\beta_0 = \\frac{c}{1 - \\phi_1} = \\frac{0.0943}{1 - 0.8742} = 0.7496$$\n",
    "\n",
    "**Note**: This value is virtually identical to the value in the Stata documentation, $\\beta_0 = 0.7498$. The slight difference is likely down to rounding and subtle differences in stopping criterion of the numerical optimizers used."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ARIMA Example 2: Arima with additive seasonal effects\n",
    "\n",
    "This model is an extension of that from example 1. Here the data is assumed to follow the process:\n",
    "\n",
    "$$\n",
    "\\Delta y_t = c + \\phi_1 \\Delta y_{t-1} + \\theta_1 \\epsilon_{t-1} + \\theta_4 \\epsilon_{t-4} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "The new part of this model is that there is allowed to be a annual seasonal effect (it is annual even though the periodicity is 4 because the dataset is quarterly). The second difference is that this model uses the log of the data rather than the level.\n",
    "\n",
    "Before estimating the dataset, graphs showing:\n",
    "\n",
    "1. The time series (in logs)\n",
    "2. The first difference of the time series (in logs)\n",
    "3. The autocorrelation function\n",
    "4. The partial autocorrelation function.\n",
    "\n",
    "From the first two graphs, we note that the original time series does not appear to be stationary, whereas the first-difference does. This supports either estimating an ARMA model on the first-difference of the data, or estimating an ARIMA model with 1 order of integration (recall that we are taking the latter approach). The last two graphs support the use of an ARMA(1,1,1) model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset\n",
    "data = pd.read_stata(BytesIO(wpi1))\n",
    "data.index = data.t\n",
    "data.index.freq=\"QS-OCT\"\n",
    "\n",
    "data['ln_wpi'] = np.log(data['wpi'])\n",
    "data['D.ln_wpi'] = data['ln_wpi'].diff()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Graph data\n",
    "fig, axes = plt.subplots(1, 2, figsize=(15,4))\n",
    "\n",
    "# Levels\n",
    "axes[0].plot(data.index._mpl_repr(), data['wpi'], '-')\n",
    "axes[0].set(title='US Wholesale Price Index')\n",
    "\n",
    "# Log difference\n",
    "axes[1].plot(data.index._mpl_repr(), data['D.ln_wpi'], '-')\n",
    "axes[1].hlines(0, data.index[0], data.index[-1], 'r')\n",
    "axes[1].set(title='US Wholesale Price Index - difference of logs');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Graph data\n",
    "fig, axes = plt.subplots(1, 2, figsize=(15,4))\n",
    "\n",
    "fig = sm.graphics.tsa.plot_acf(data.iloc[1:]['D.ln_wpi'], lags=40, ax=axes[0])\n",
    "fig = sm.graphics.tsa.plot_pacf(data.iloc[1:]['D.ln_wpi'], lags=40, ax=axes[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To understand how to specify this model in statsmodels, first recall that from example 1 we used the following code to specify the ARIMA(1,1,1) model:\n",
    "\n",
    "```python\n",
    "mod = sm.tsa.statespace.SARIMAX(data['wpi'], trend='c', order=(1,1,1))\n",
    "```\n",
    "\n",
    "The `order` argument is a tuple of the form `(AR specification, Integration order, MA specification)`. The integration order must be an integer (for example, here we assumed one order of integration, so it was specified as 1. In a pure ARMA model where the underlying data is already stationary, it would be 0).\n",
    "\n",
    "For the AR specification and MA specification components, there are two possibilities. The first is to specify the **maximum degree** of the corresponding lag polynomial, in which case the component is an integer. For example, if we wanted to specify an ARIMA(1,1,4) process, we would use:\n",
    "\n",
    "```python\n",
    "mod = sm.tsa.statespace.SARIMAX(data['wpi'], trend='c', order=(1,1,4))\n",
    "```\n",
    "\n",
    "and the corresponding data process would be:\n",
    "\n",
    "$$\n",
    "y_t = c + \\phi_1 y_{t-1} + \\theta_1 \\epsilon_{t-1} + \\theta_2 \\epsilon_{t-2} + \\theta_3 \\epsilon_{t-3} + \\theta_4 \\epsilon_{t-4} + \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "or\n",
    "\n",
    "$$\n",
    "(1 - \\phi_1 L)\\Delta y_t = c + (1 + \\theta_1 L + \\theta_2 L^2 + \\theta_3 L^3 + \\theta_4 L^4) \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "When the specification parameter is given as a maximum degree of the lag polynomial, it implies that all polynomial terms up to that degree are included. Notice that this is *not* the model we want to use, because it would include terms for $\\epsilon_{t-2}$ and $\\epsilon_{t-3}$, which we do not want here.\n",
    "\n",
    "What we want is a polynomial that has terms for the 1st and 4th degrees, but leaves out the 2nd and 3rd terms. To do that, we need to provide a tuple for the specification parameter, where the tuple describes **the lag polynomial itself**. In particular, here we would want to use:\n",
    "\n",
    "```python\n",
    "ar = 1          # this is the maximum degree specification\n",
    "ma = (1,0,0,1)  # this is the lag polynomial specification\n",
    "mod = sm.tsa.statespace.SARIMAX(data['wpi'], trend='c', order=(ar,1,ma)))\n",
    "```\n",
    "\n",
    "This gives the following form for the process of the data:\n",
    "\n",
    "$$\n",
    "\\Delta y_t = c + \\phi_1 \\Delta y_{t-1} + \\theta_1 \\epsilon_{t-1} + \\theta_4 \\epsilon_{t-4} + \\epsilon_{t} \\\\\n",
    "(1 - \\phi_1 L)\\Delta y_t = c + (1 + \\theta_1 L + \\theta_4 L^4) \\epsilon_{t}\n",
    "$$\n",
    "\n",
    "which is what we want."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Fit the model\n",
    "mod = sm.tsa.statespace.SARIMAX(data['ln_wpi'], trend='c', order=(1,1,(1,0,0,1)))\n",
    "res = mod.fit(disp=False)\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ARIMA Example 3: Airline Model\n",
    "\n",
    "In the previous example, we included a seasonal effect in an *additive* way, meaning that we added a term allowing the process to depend on the 4th MA lag. It may be instead that we want to model a seasonal effect in a multiplicative way. We often write the model then as an ARIMA $(p,d,q) \\times (P,D,Q)_s$, where the lowercase letters indicate the specification for the non-seasonal component, and the uppercase letters indicate the specification for the seasonal component; $s$ is the periodicity of the seasons (e.g. it is often 4 for quarterly data or 12 for monthly data). The data process can be written generically as:\n",
    "\n",
    "$$\n",
    "\\phi_p (L) \\tilde \\phi_P (L^s) \\Delta^d \\Delta_s^D y_t = A(t) + \\theta_q (L) \\tilde \\theta_Q (L^s) \\epsilon_t\n",
    "$$\n",
    "\n",
    "where:\n",
    "\n",
    "- $\\phi_p (L)$ is the non-seasonal autoregressive lag polynomial\n",
    "- $\\tilde \\phi_P (L^s)$ is the seasonal autoregressive lag polynomial\n",
    "- $\\Delta^d \\Delta_s^D y_t$ is the time series, differenced $d$ times, and seasonally differenced $D$ times.\n",
    "- $A(t)$ is the trend polynomial (including the intercept)\n",
    "- $\\theta_q (L)$ is the non-seasonal moving average lag polynomial\n",
    "- $\\tilde \\theta_Q (L^s)$ is the seasonal moving average lag polynomial\n",
    "\n",
    "sometimes we rewrite this as:\n",
    "\n",
    "$$\n",
    "\\phi_p (L) \\tilde \\phi_P (L^s) y_t^* = A(t) + \\theta_q (L) \\tilde \\theta_Q (L^s) \\epsilon_t\n",
    "$$\n",
    "\n",
    "where $y_t^* = \\Delta^d \\Delta_s^D y_t$. This emphasizes that just as in the simple case, after we take differences (here both non-seasonal and seasonal) to make the data stationary, the resulting model is just an ARMA model.\n",
    "\n",
    "As an example, consider the airline model ARIMA $(2,1,0) \\times (1,1,0)_{12}$, with an intercept. The data process can be written in the form above as:\n",
    "\n",
    "$$\n",
    "(1 - \\phi_1 L - \\phi_2 L^2) (1 - \\tilde \\phi_1 L^{12}) \\Delta \\Delta_{12} y_t = c + \\epsilon_t\n",
    "$$\n",
    "\n",
    "Here, we have:\n",
    "\n",
    "- $\\phi_p (L) = (1 - \\phi_1 L - \\phi_2 L^2)$\n",
    "- $\\tilde \\phi_P (L^s) = (1 - \\phi_1 L^12)$\n",
    "- $d = 1, D = 1, s=12$ indicating that $y_t^*$ is derived from $y_t$ by taking first-differences and then taking 12-th differences.\n",
    "- $A(t) = c$ is the *constant* trend polynomial (i.e. just an intercept)\n",
    "- $\\theta_q (L) = \\tilde \\theta_Q (L^s) = 1$ (i.e. there is no moving average effect)\n",
    "\n",
    "It may still be confusing to see the two lag polynomials in front of the time-series variable, but notice that we can multiply the lag polynomials together to get the following model:\n",
    "\n",
    "$$\n",
    "(1 - \\phi_1 L - \\phi_2 L^2 - \\tilde \\phi_1 L^{12} + \\phi_1 \\tilde \\phi_1 L^{13} + \\phi_2 \\tilde \\phi_1 L^{14} ) y_t^* = c + \\epsilon_t\n",
    "$$\n",
    "\n",
    "which can be rewritten as:\n",
    "\n",
    "$$\n",
    "y_t^* = c + \\phi_1 y_{t-1}^* + \\phi_2 y_{t-2}^* + \\tilde \\phi_1 y_{t-12}^* - \\phi_1 \\tilde \\phi_1 y_{t-13}^* - \\phi_2 \\tilde \\phi_1 y_{t-14}^* + \\epsilon_t\n",
    "$$\n",
    "\n",
    "This is similar to the additively seasonal model from example 2, but the coefficients in front of the autoregressive lags are actually combinations of the underlying seasonal and non-seasonal parameters.\n",
    "\n",
    "Specifying the model in statsmodels is done simply by adding the `seasonal_order` argument, which accepts a tuple of the form `(Seasonal AR specification, Seasonal Integration order, Seasonal MA, Seasonal periodicity)`. The seasonal AR and MA specifications, as before, can be expressed as a maximum polynomial degree or as the lag polynomial itself. Seasonal periodicity is an integer.\n",
    "\n",
    "For the airline model ARIMA $(2,1,0) \\times (1,1,0)_{12}$ with an intercept, the command is:\n",
    "\n",
    "```python\n",
    "mod = sm.tsa.statespace.SARIMAX(data['lnair'], order=(2,1,0), seasonal_order=(1,1,0,12))\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset\n",
    "air2 = requests.get('https://www.stata-press.com/data/r12/air2.dta').content\n",
    "data = pd.read_stata(BytesIO(air2))\n",
    "data.index = pd.date_range(start=datetime(int(data.time[0]), 1, 1), periods=len(data), freq='MS')\n",
    "data['lnair'] = np.log(data['air'])\n",
    "\n",
    "# Fit the model\n",
    "mod = sm.tsa.statespace.SARIMAX(data['lnair'], order=(2,1,0), seasonal_order=(1,1,0,12), simple_differencing=True)\n",
    "res = mod.fit(disp=False)\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that here we used an additional argument `simple_differencing=True`. This controls how the order of integration is handled in ARIMA models. If `simple_differencing=True`, then the time series provided as `endog` is literally differenced and an ARMA model is fit to the resulting new time series. This implies that a number of initial periods are lost to the differencing process, however it may be necessary either to compare results to other packages (e.g. Stata's `arima` always uses  simple differencing) or if the seasonal periodicity is large.\n",
    "\n",
    "The default is `simple_differencing=False`, in which case the integration component is implemented as part of the state space formulation, and all of the original data can be used in estimation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ARIMA Example 4: ARMAX (Friedman)\n",
    "\n",
    "This model demonstrates the use of explanatory variables (the X part of ARMAX). When exogenous regressors are included, the SARIMAX module uses the concept of \"regression with SARIMA errors\" (see http://robjhyndman.com/hyndsight/arimax/ for details of regression with ARIMA errors versus alternative specifications), so that the model is specified as:\n",
    "\n",
    "$$\n",
    "y_t = \\beta_t x_t + u_t \\\\\n",
    "        \\phi_p (L) \\tilde \\phi_P (L^s) \\Delta^d \\Delta_s^D u_t = A(t) +\n",
    "            \\theta_q (L) \\tilde \\theta_Q (L^s) \\epsilon_t\n",
    "$$\n",
    "\n",
    "Notice that the first equation is just a linear regression, and the second equation just describes the process followed by the error component as SARIMA (as was described in example 3). One reason for this specification is that the estimated parameters have their natural interpretations.\n",
    "\n",
    "This specification nests many simpler specifications. For example, regression with AR(2) errors is:\n",
    "\n",
    "$$\n",
    "y_t = \\beta_t x_t + u_t \\\\\n",
    "(1 - \\phi_1 L - \\phi_2 L^2) u_t = A(t) + \\epsilon_t\n",
    "$$\n",
    "\n",
    "The model considered in this example is regression with ARMA(1,1) errors. The process is then written:\n",
    "\n",
    "$$\n",
    "\\text{consump}_t = \\beta_0 + \\beta_1 \\text{m2}_t + u_t \\\\\n",
    "(1 - \\phi_1 L) u_t = (1 - \\theta_1 L) \\epsilon_t\n",
    "$$\n",
    "\n",
    "Notice that $\\beta_0$ is, as described in example 1 above, *not* the same thing as an intercept specified by `trend='c'`. Whereas in the examples above we estimated the intercept of the model via the trend polynomial, here, we demonstrate how to estimate $\\beta_0$ itself by adding a constant to the exogenous dataset. In the output, the $beta_0$ is called `const`, whereas above the intercept $c$ was called `intercept` in the output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset\n",
    "friedman2 = requests.get('https://www.stata-press.com/data/r12/friedman2.dta').content\n",
    "data = pd.read_stata(BytesIO(friedman2))\n",
    "data.index = data.time\n",
    "data.index.freq = \"QS-OCT\"\n",
    "\n",
    "# Variables\n",
    "endog = data.loc['1959':'1981', 'consump']\n",
    "exog = sm.add_constant(data.loc['1959':'1981', 'm2'])\n",
    "\n",
    "# Fit the model\n",
    "mod = sm.tsa.statespace.SARIMAX(endog, exog, order=(1,0,1))\n",
    "res = mod.fit(disp=False)\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ARIMA Postestimation: Example 1 - Dynamic Forecasting\n",
    "\n",
    "Here we describe some of the post-estimation capabilities of statsmodels' SARIMAX.\n",
    "\n",
    "First, using the model from example, we estimate the parameters using data that *excludes the last few observations* (this is a little artificial as an example, but it allows considering performance of out-of-sample forecasting and facilitates comparison to Stata's documentation)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset\n",
    "raw = pd.read_stata(BytesIO(friedman2))\n",
    "raw.index = raw.time\n",
    "raw.index.freq = \"QS-OCT\"\n",
    "data = raw.loc[:'1981']\n",
    "\n",
    "# Variables\n",
    "endog = data.loc['1959':, 'consump']\n",
    "exog = sm.add_constant(data.loc['1959':, 'm2'])\n",
    "nobs = endog.shape[0]\n",
    "\n",
    "# Fit the model\n",
    "mod = sm.tsa.statespace.SARIMAX(endog.loc[:'1978-01-01'], exog=exog.loc[:'1978-01-01'], order=(1,0,1))\n",
    "fit_res = mod.fit(disp=False, maxiter=250)\n",
    "print(fit_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we want to get results for the full dataset but using the estimated parameters (on a subset of the data)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod = sm.tsa.statespace.SARIMAX(endog, exog=exog, order=(1,0,1))\n",
    "res = mod.filter(fit_res.params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `predict` command is first applied here to get in-sample predictions. We use the `full_results=True` argument to allow us to calculate confidence intervals (the default output of `predict` is just the predicted values).\n",
    "\n",
    "With no other arguments, `predict` returns the one-step-ahead in-sample predictions for the entire sample."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# In-sample one-step-ahead predictions\n",
    "predict = res.get_prediction()\n",
    "predict_ci = predict.conf_int()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also get *dynamic predictions*. One-step-ahead prediction uses the true values of the endogenous values at each step to predict the next in-sample value. Dynamic predictions use one-step-ahead prediction up to some point in the dataset (specified by the `dynamic` argument); after that, the previous *predicted* endogenous values are used in place of the true endogenous values for each new predicted element.\n",
    "\n",
    "The `dynamic` argument is specified to be an *offset* relative to the `start` argument. If `start` is not specified, it is assumed to be `0`.\n",
    "\n",
    "Here we perform dynamic prediction starting in the first quarter of 1978."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dynamic predictions\n",
    "predict_dy = res.get_prediction(dynamic='1978-01-01')\n",
    "predict_dy_ci = predict_dy.conf_int()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can graph the one-step-ahead and dynamic predictions (and the corresponding confidence intervals) to see their relative performance. Notice that up to the point where dynamic prediction begins (1978:Q1), the two are the same."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Graph\n",
    "fig, ax = plt.subplots(figsize=(9,4))\n",
    "npre = 4\n",
    "ax.set(title='Personal consumption', xlabel='Date', ylabel='Billions of dollars')\n",
    "\n",
    "# Plot data points\n",
    "data.loc['1977-07-01':, 'consump'].plot(ax=ax, style='o', label='Observed')\n",
    "\n",
    "# Plot predictions\n",
    "predict.predicted_mean.loc['1977-07-01':].plot(ax=ax, style='r--', label='One-step-ahead forecast')\n",
    "ci = predict_ci.loc['1977-07-01':]\n",
    "ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color='r', alpha=0.1)\n",
    "predict_dy.predicted_mean.loc['1977-07-01':].plot(ax=ax, style='g', label='Dynamic forecast (1978)')\n",
    "ci = predict_dy_ci.loc['1977-07-01':]\n",
    "ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color='g', alpha=0.1)\n",
    "\n",
    "legend = ax.legend(loc='lower right')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, graph the prediction *error*. It is obvious that, as one would suspect, one-step-ahead prediction is considerably better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prediction error\n",
    "\n",
    "# Graph\n",
    "fig, ax = plt.subplots(figsize=(9,4))\n",
    "npre = 4\n",
    "ax.set(title='Forecast error', xlabel='Date', ylabel='Forecast - Actual')\n",
    "\n",
    "# In-sample one-step-ahead predictions and 95% confidence intervals\n",
    "predict_error = predict.predicted_mean - endog\n",
    "predict_error.loc['1977-10-01':].plot(ax=ax, label='One-step-ahead forecast')\n",
    "ci = predict_ci.loc['1977-10-01':].copy()\n",
    "ci.iloc[:,0] -= endog.loc['1977-10-01':]\n",
    "ci.iloc[:,1] -= endog.loc['1977-10-01':]\n",
    "ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], alpha=0.1)\n",
    "\n",
    "# Dynamic predictions and 95% confidence intervals\n",
    "predict_dy_error = predict_dy.predicted_mean - endog\n",
    "predict_dy_error.loc['1977-10-01':].plot(ax=ax, style='r', label='Dynamic forecast (1978)')\n",
    "ci = predict_dy_ci.loc['1977-10-01':].copy()\n",
    "ci.iloc[:,0] -= endog.loc['1977-10-01':]\n",
    "ci.iloc[:,1] -= endog.loc['1977-10-01':]\n",
    "ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color='r', alpha=0.1)\n",
    "\n",
    "legend = ax.legend(loc='lower left');\n",
    "legend.get_frame().set_facecolor('w')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
