{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "66195396-2615-48ab-aa26-954532d0bc35",
   "metadata": {},
   "source": [
    "# SARIMAX and ARIMA: Frequently Asked Questions (FAQ)\n",
    "\n",
    "This notebook contains explanations for frequently asked questions.\n",
    "\n",
    "* Comparing trends and exogenous variables in `SARIMAX`, `ARIMA` and `AutoReg`\n",
    "* Reconstructing residuals, fitted values and forecasts in `SARIMAX` and `ARIMA`\n",
    "* Initial residuals in `SARIMAX` and `ARIMA`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "174cebe5-2bfb-4258-96b0-a292e5cdbcf7",
   "metadata": {},
   "source": [
    "## Comparing trends and exogenous variables in `SARIMAX`, `ARIMA` and `AutoReg`\n",
    "\n",
    "`ARIMA` are formally OLS with ARMA errors.  A basic AR(1) in the OLS with ARMA errors is described as \n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t & = \\delta + \\epsilon_t \\\\\n",
    "\\epsilon_t & = \\rho \\epsilon_{t-1} + \\eta_t \\\\\n",
    "\\eta_t & \\sim WN(0,\\sigma^2) \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "In large samples, $\\hat{\\delta}\\stackrel{p}{\\rightarrow} E[Y]$.\n",
    "\n",
    "`SARIMAX` uses a different representation, so that the model when estimated using `SARIMAX` is\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t & = \\phi + \\rho Y_{t-1} + \\eta_t \\\\\n",
    "\\eta_t & \\sim WN(0,\\sigma^2) \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "\n",
    "This is the same representation that is used when the model is estimated using OLS (`AutoReg`). In large samples, $\\hat{\\phi}\\stackrel{p}{\\rightarrow} E[Y](1-\\rho)$.\n",
    "\n",
    "In the next cell, we simulate a large sample and verify that these relationship hold in practice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba21553a-e571-42ac-b166-b625a50509fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe284c44-b750-4e6e-94d0-b238f364cd7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "rng = np.random.default_rng(20210819)\n",
    "eta = rng.standard_normal(5200)\n",
    "rho = 0.8\n",
    "beta = 10\n",
    "epsilon = eta.copy()\n",
    "for i in range(1, eta.shape[0]):\n",
    "    epsilon[i] = rho * epsilon[i - 1] + eta[i]\n",
    "y = beta + epsilon\n",
    "y = y[200:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f02b87c6-ee8f-4bb1-bf08-d252b9277733",
   "metadata": {},
   "outputs": [],
   "source": [
    "from statsmodels.tsa.api import SARIMAX, AutoReg\n",
    "from statsmodels.tsa.arima.model import ARIMA"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e8212dc-e259-422f-b10b-3b742e86b36c",
   "metadata": {},
   "source": [
    "The three models are specified and estimated in the next cell.  An AR(0) is included as a reference. The AR(0) is identical using all three estimators."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7200d248-bd47-4c95-9f1c-6daaf1e09bb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "ar0_res = SARIMAX(y, order=(0, 0, 0), trend=\"c\").fit()\n",
    "sarimax_res = SARIMAX(y, order=(1, 0, 0), trend=\"c\").fit()\n",
    "arima_res = ARIMA(y, order=(1, 0, 0), trend=\"c\").fit()\n",
    "autoreg_res = AutoReg(y, 1, trend=\"c\").fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f502bdd-9ba5-47e4-8aeb-e83e5e1d8898",
   "metadata": {},
   "source": [
    "The table below contains the estimated parameter in the model, the estimated AR(1) coefficient, and the long-run mean which is either equal to the estimated parameters (AR(0) or `ARIMA`), or depends on the ratio of the intercept to 1 minus the AR(1) parameter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ff07d0e-6754-4664-93e4-0f9299096868",
   "metadata": {},
   "outputs": [],
   "source": [
    "intercept = [\n",
    "    ar0_res.params[0],\n",
    "    sarimax_res.params[0],\n",
    "    arima_res.params[0],\n",
    "    autoreg_res.params[0],\n",
    "]\n",
    "rho_hat = [0] + [r.params[1] for r in (sarimax_res, arima_res, autoreg_res)]\n",
    "long_run = [\n",
    "    ar0_res.params[0],\n",
    "    sarimax_res.params[0] / (1 - sarimax_res.params[1]),\n",
    "    arima_res.params[0],\n",
    "    autoreg_res.params[0] / (1 - autoreg_res.params[1]),\n",
    "]\n",
    "cols = [\"AR(0)\", \"SARIMAX\", \"ARIMA\", \"AutoReg\"]\n",
    "pd.DataFrame(\n",
    "    [intercept, rho_hat, long_run],\n",
    "    columns=cols,\n",
    "    index=[\"delta-or-phi\", \"rho\", \"long-run mean\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f81803a-0902-4715-a1a6-0a609c8bd614",
   "metadata": {},
   "source": [
    "### Differences between trend and exog in `SARIMAX`\n",
    "\n",
    "When `SARIMAX` includes `exog` variables, then the `exog` are treated as OLS regressors, so that the model estimated is\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t - X_t \\beta & = \\delta + \\rho (Y_{t-1} - X_{t-1}\\beta) + \\eta_t \\\\\n",
    "\\eta_t & \\sim WN(0,\\sigma^2) \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "In the next example, we omit the trend and instead include a column of 1, which produces a model that is equivalent, in large samples, to the case with no exogenous regressor and `trend=\"c\"`. Here the estimated value of `const` matches the value estimated using `ARIMA`. This happens since both exog in `SARIMAX` and the trend in `ARIMA` are treated as linear regression models with ARMA errors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c18adf81-1ad9-4d11-a23b-e6d139c1fa3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "sarimax_exog_res = SARIMAX(y, exog=np.ones_like(y), order=(1, 0, 0), trend=\"n\").fit()\n",
    "print(sarimax_exog_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74d8b733-e74f-4e86-b663-111ab6953b79",
   "metadata": {},
   "source": [
    "### Using `exog` in `SARIMAX` and `ARIMA`\n",
    "\n",
    "While `exog` are treated the same in both models, the intercept continues to differ.  Below we add an exogenous regressor to `y` and then fit the model using all three methods. The data generating process is now\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t & = \\delta + X_t \\beta + \\epsilon_t \\\\\n",
    "\\epsilon_t & = \\rho \\epsilon_{t-1} + \\eta_t \\\\\n",
    "\\eta_t & \\sim WN(0,\\sigma^2) \\\\\n",
    "\\end{align}\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8978b4c9-05cb-4674-9c67-53eccd8302a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "full_x = rng.standard_normal(eta.shape)\n",
    "x = full_x[200:]\n",
    "y += 3 * x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bebdfd6-cb1b-4c33-a4a5-3eb54fe73e24",
   "metadata": {},
   "outputs": [],
   "source": [
    "sarimax_exog_res = SARIMAX(y, exog=x, order=(1, 0, 0), trend=\"c\").fit()\n",
    "arima_exog_res = ARIMA(y, exog=x, order=(1, 0, 0), trend=\"c\").fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9015313a-a7b1-436c-a0f0-c567aae09141",
   "metadata": {},
   "source": [
    "Examining the parameter tables, we see that the parameter estimates on `x1` are identical while the estimates of the `intercept` continue to differ due to the differences in the treatment of trends in these estimators."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34f02944-22c0-47d6-8f53-2f3528a99e1a",
   "metadata": {},
   "source": [
    "#### `SARIMAX`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "573ef935-85d2-49e6-b6a1-0041253fc71a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_params(s):\n",
    "    from io import StringIO\n",
    "\n",
    "    return pd.read_csv(StringIO(s.tables[1].as_csv()), index_col=0)\n",
    "\n",
    "\n",
    "print_params(sarimax_exog_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb72481a-29db-4e40-bdc4-8023ff81c51a",
   "metadata": {},
   "source": [
    "#### `ARIMA`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "101e7417-d6fc-448c-9d87-9ba44aafcc70",
   "metadata": {},
   "outputs": [],
   "source": [
    "print_params(arima_exog_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "553c24db-4156-4867-b711-f0e1369c9382",
   "metadata": {},
   "source": [
    "### `exog` in `AutoReg`\n",
    "\n",
    "When using `AutoReg` to estimate a model using OLS, the model differs from both `SARIMAX` and `ARIMA`. The `AutoReg` specification with exogenous variables is \n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t & = \\phi + \\rho Y_{t-1} + X_{t}\\beta + \\eta_t \\\\\n",
    "\\eta_t & \\sim WN(0,\\sigma^2) \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "This specification is not equivalent to the specification estimated in `SARIMAX` and `ARIMA`. Here the difference is non-trivial, and naive estimation on the same time series results in different parameter values, even in large samples (and the limit). Estimating this model changes the parameter estimates on the AR(1) coefficient."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4259b7e0-3624-4724-bdbf-eba073a5efb6",
   "metadata": {},
   "source": [
    "#### `AutoReg`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3af7fcc8-6e85-4d76-b2c8-e57a782c0884",
   "metadata": {},
   "outputs": [],
   "source": [
    "autoreg_exog_res = AutoReg(y, 1, exog=x, trend=\"c\").fit()\n",
    "print_params(autoreg_exog_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "170b7189-8efc-4b7e-9243-46e5ee6043cb",
   "metadata": {},
   "source": [
    "The key difference can be seen by writing the model in lag operator notation.\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "(1-\\phi L ) Y_t & = X_{t}\\beta + \\eta_t \\Rightarrow \\\\\n",
    "Y_t & = (1-\\phi L )^{-1}\\left(X_{t}\\beta + \\eta_t\\right) \\\\\n",
    "Y_t & = \\sum_{i=0}^{\\infty} \\phi^i \\left(X_{t-i}\\beta + \\eta_{t-i}\\right)\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "where it is is assumed that $|\\phi|<1$.  Here we see that $Y_t$ depends on all lagged values of $X_t$ and $\\eta_t$.  This differs from the specification estimated by `SARIMAX` and `ARIMA`, which can be seen to be\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "Y_t - X_t \\beta & = \\delta + \\rho (Y_{t-1} - X_{t-1}\\beta) + \\eta_t \\\\\n",
    "\\left(1-\\rho L \\right)\\left(Y_t - X_t  \\beta\\right) & = \\delta +  \\eta_t \\\\\n",
    "Y_t - X_t  \\beta & = \\frac{\\delta}{1-\\rho} +  \\left(1-\\rho L \\right)^{-1}\\eta_t \\\\\n",
    "Y_t - X_t  \\beta & = \\frac{\\delta}{1-\\rho} +  \\sum_{i=0}^\\infty \\rho^i \\eta_{t-i} \\\\\n",
    "Y_t  & = \\frac{\\delta}{1-\\rho} + X_t  \\beta +  \\sum_{i=0}^\\infty \\rho^i \\eta_{t-i} \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "In this specification, $Y_t$ only depends on $X_t$ and no other lags."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "869a050c-ea1b-42df-aac3-a14722c109e9",
   "metadata": {},
   "source": [
    "### Using the correct DGP with `AutoReg`\n",
    "\n",
    "Simulating the process that is estimated in `AutoReg` shows that the parameters are recovered from the true model. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "faa9c3a2-aa68-4a9c-ade2-edf4df7798c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "y = beta + eta\n",
    "epsilon = eta.copy()\n",
    "for i in range(1, eta.shape[0]):\n",
    "    y[i] = beta * (1 - rho) + rho * y[i - 1] + 3 * full_x[i] + eta[i]\n",
    "y = y[200:]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c37ad9d-dad8-4a51-adba-88b60667698c",
   "metadata": {},
   "source": [
    "#### `AutoReg` with correct DGP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2734e0db-39ab-4233-90b2-7c60ba48483a",
   "metadata": {},
   "outputs": [],
   "source": [
    "autoreg_alt_exog_res = AutoReg(y, 1, exog=x, trend=\"c\").fit()\n",
    "print_params(autoreg_alt_exog_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a51863e-6799-402b-96a2-b1212ea86216",
   "metadata": {},
   "source": [
    "## Reconstructing residuals, fitted values and forecasts in `SARIMAX` and `ARIMA`\n",
    "\n",
    "In models that contain only autoregressive terms, trends and exogenous variables, fitted values and forecasts can be easily reconstructed once the maximum lag length in the model has been reached.  In practice, this means after $(P+D)s+p+d$ periods. Earlier predictions and residuals are harder to reconstruct since the model builds the best prediction for $Y_t|Y_{t-1},Y_{t-2},...$.  When the number of lags of $Y$ is less than the autoregressive order, then the expression for the optimal prediction differs from the model.  For example, when predicting the very first value, $Y_1$, there is no information available from the history of $Y$, and so the best prediction is the unconditional mean. In the case of an AR(1), the second prediction will follow the model, so that when using `ARIMA`, the prediction is\n",
    "\n",
    "$$\n",
    "Y_2 = \\hat{\\delta} + \\hat{\\rho} \\left(Y_1 - \\hat{\\delta}\\right)\n",
    "$$\n",
    "\n",
    "since `ARIMA` treats both exogenous and trend terms as regression with ARMA errors.\n",
    "\n",
    "This can be seen in the next set of cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c17c510-0e76-41a2-a6a0-4ac9fa705136",
   "metadata": {},
   "outputs": [],
   "source": [
    "arima_res = ARIMA(y, order=(1, 0, 0), trend=\"c\").fit()\n",
    "print_params(arima_res.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7198b7b8-e564-4284-8d68-7b4b7a3fd914",
   "metadata": {},
   "outputs": [],
   "source": [
    "arima_res.predict(0, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d887b51b-f689-4dd1-874c-5bc95010bdd8",
   "metadata": {},
   "outputs": [],
   "source": [
    "delta_hat, rho_hat = arima_res.params[:2]\n",
    "delta_hat + rho_hat * (y[0] - delta_hat)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "646b941f-5f5b-40c4-be15-a7a1f54af5af",
   "metadata": {},
   "source": [
    "`SARIMAX` treats trend terms differently, and so the one-step forecast from a model estimated using `SARIMAX` is\n",
    "\n",
    "$$\n",
    "Y_2 = \\hat\\delta + \\hat\\rho Y_1\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76e37005-93f3-4b5b-8a63-de67f7f1f8a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "sarima_res = SARIMAX(y, order=(1, 0, 0), trend=\"c\").fit()\n",
    "print_params(sarima_res.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35546219-1730-41ed-be61-06e8fc7487b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "sarima_res.predict(0, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52620a07-ab3c-4a9c-b1b2-b6976ed335bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "delta_hat, rho_hat = sarima_res.params[:2]\n",
    "delta_hat + rho_hat * y[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71873544-677a-4061-87ed-76c095cc37f0",
   "metadata": {},
   "source": [
    "### Prediction with MA components\n",
    "\n",
    "When a model contains a MA component, the prediction is more complicated since errors are never directly observable.  The prediction is still $Y_t|Y_{t-1},Y_{t-2},...$, and when the MA component is invertible, then the optimal prediction can be represented as a $t$-lag AR process. When $t$ is large, this should be very close to the prediction as if the errors were observable. For short lags, this can differ markedly.\n",
    "\n",
    "In the next cell we simulate an MA(1) process, and fit an MA model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4db1fb2-135e-43cf-a55f-852698ca9540",
   "metadata": {},
   "outputs": [],
   "source": [
    "rho = 0.8\n",
    "beta = 10\n",
    "epsilon = eta.copy()\n",
    "for i in range(1, eta.shape[0]):\n",
    "    epsilon[i] = rho * eta[i - 1] + eta[i]\n",
    "y = beta + epsilon\n",
    "y = y[200:]\n",
    "\n",
    "ma_res = ARIMA(y, order=(0, 0, 1), trend=\"c\").fit()\n",
    "print_params(ma_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21826604-ee43-47c1-82e5-cd2b6728a36c",
   "metadata": {},
   "source": [
    "We start by looking at predictions near the beginning of the sample corresponding `y[1]`, ..., `y[5]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed868e49-e12e-44fd-bf09-37b1b33cf3f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "ma_res.predict(1, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2c410e-c03f-45bd-957d-272f71dd49e7",
   "metadata": {},
   "source": [
    "and the corresponding residuals that are needed to produce the \"direct\" forecasts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8356c92c-6686-41e0-93fc-3f5c0983fd89",
   "metadata": {},
   "outputs": [],
   "source": [
    "ma_res.resid[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9092d6a2-2de2-46f2-9965-6ecc471d7661",
   "metadata": {},
   "source": [
    "Using the model parameters, we can produce the \"direct\" forecasts using the MA(1) specification\n",
    "\n",
    "$$\n",
    "\\hat Y_t = \\hat\\delta + \\hat\\rho \\hat\\epsilon_{t-1}\n",
    "$$\n",
    "\n",
    "We see that these are not especially close to the actual model predictions for the initial forecasts, but that the gap quickly reduces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea2373ad-533f-44b9-9597-7a34a1eeb4be",
   "metadata": {},
   "outputs": [],
   "source": [
    "delta_hat, rho_hat = ma_res.params[:2]\n",
    "direct = delta_hat + rho_hat * ma_res.resid[:5]\n",
    "direct"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eab3797d-d51e-41af-b452-6a64deb9bc9c",
   "metadata": {},
   "source": [
    "The difference is nearly a standard deviation for the first but declines as the index increases."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e469678d-2791-4344-ac0d-00e0937db050",
   "metadata": {},
   "outputs": [],
   "source": [
    "ma_res.predict(1, 5) - direct"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b45bf944-392a-432f-a89a-4d0d9c19f30d",
   "metadata": {},
   "source": [
    "We next look at the end of the sample and the final three predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5e38740-78fb-450c-a20a-2ce04f7bff9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = y.shape[0]\n",
    "ma_res.predict(t - 3, t - 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77418292-c7f0-4a0a-9ef0-050d4350aa51",
   "metadata": {},
   "outputs": [],
   "source": [
    "ma_res.resid[-4:-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8d6e6ed-9575-46ed-a8f0-02e376ee3db9",
   "metadata": {},
   "outputs": [],
   "source": [
    "direct = delta_hat + rho_hat * ma_res.resid[-4:-1]\n",
    "direct"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c64c4b6-3062-403d-90e8-2bbfd8923ae7",
   "metadata": {},
   "source": [
    "The \"direct\" forecasts are identical. This happens since the effect of the short sample has disappeared by the end of the sample (In practice it is negligible by observations 100 or so, and numerically absent by around observation 160)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b61fde0-17fb-4678-9267-c624c49ee26e",
   "metadata": {},
   "outputs": [],
   "source": [
    "ma_res.predict(t - 3, t - 1) - direct"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e7a2a2d-e7db-4b4a-8fb9-408ff21256d3",
   "metadata": {},
   "source": [
    "The same principle applies in more complicated model that include multiple lags or seasonal term - predictions in AR models are simple once the effective lag length has been reached, while predictions in models that contains MA components are only simple once the maximum root of the MA lag polynomial is sufficiently small so that the residuals are close to the true residuals. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c2e2caa-bd34-4f9c-8272-e8fcb389ef03",
   "metadata": {},
   "source": [
    "### Prediction differences in `SARIMAX` and `ARIMA`\n",
    "\n",
    "The formulas used to make predictions from `SARIMAX` and `ARIMA` models differ in one key aspect - `ARIMA` treats all trend terms, e.g, the intercept or time trend, as part of the exogenous regressors.  For example, an AR(1) model with an intercept and linear time trend estimated using `ARIMA` has the specification\n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "Y_t - \\delta_0 - \\delta_1 t & = \\epsilon_t \\\\\n",
    "\\epsilon_t & = \\rho \\epsilon_{t-1} + \\eta_t\n",
    "\\end{align*}\n",
    "$$\n",
    "\n",
    "When the same model is estimated using `SARIMAX`, the specification is \n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "Y_t & = \\epsilon_t \\\\\n",
    "\\epsilon_t & =  \\delta_0 + \\delta_1 t  + \\rho \\epsilon_{t-1} + \\eta_t\n",
    "\\end{align*}\n",
    "$$\n",
    "\n",
    "The differences are more apparent when the model contains exogenous regressors, $X_t$.  The `ARIMA` specification is\n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "Y_t - \\delta_0 - \\delta_1 t - X_t \\beta & = \\epsilon_t \\\\\n",
    "\\epsilon_t & = \\rho \\epsilon_{t-1} + \\eta_t \\\\\n",
    "           & = \\rho \\left(Y_{t-1} - \\delta_0 - \\delta_1 (t-1) - X_{t-1} \\beta\\right) + \\eta_t\n",
    "\\end{align*}\n",
    "$$\n",
    "\n",
    "while the `SARIMAX` specification is \n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "Y_t & =  X_t \\beta + \\epsilon_t \\\\\n",
    "\\epsilon_t & =  \\delta_0 + \\delta_1 t  + \\rho \\epsilon_{t-1} + \\eta_t \\\\\n",
    "           & = \\delta_0 + \\delta_1 t  + \\rho \\left(Y_{t-1} - X_{t-1}\\beta\\right) + \\eta_t\n",
    "\\end{align*}\n",
    "$$\n",
    "\n",
    "The key difference between these two is that the intercept and the trend are effectively equivalent to exogenous regressions in `ARIMA` while they are more like standard ARMA terms in `SARIMAX`.\n",
    "\n",
    "The next cell simulates an ARX with a time trend using the specification in `ARIMA` and estimates the parameters using both estimators."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9e9004b-35c0-4005-8520-358e2462514b",
   "metadata": {},
   "outputs": [],
   "source": [
    "rho = 0.8\n",
    "beta = 2\n",
    "delta0 = 10\n",
    "delta1 = 0.5\n",
    "epsilon = eta.copy()\n",
    "for i in range(1, eta.shape[0]):\n",
    "    epsilon[i] = rho * epsilon[i - 1] + eta[i]\n",
    "t = np.arange(epsilon.shape[0])\n",
    "y = delta0 + delta1 * t + beta * full_x + epsilon\n",
    "y = y[200:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9a06c47-d73e-486b-9d36-0c27029e2920",
   "metadata": {},
   "outputs": [],
   "source": [
    "start = np.array([110, delta1, beta, rho, 1])\n",
    "arx_res = ARIMA(y, exog=x, order=(1, 0, 0), trend=\"ct\").fit()\n",
    "mod = SARIMAX(y, exog=x, order=(1, 0, 0), trend=\"ct\")\n",
    "start[:2] *= 1 - rho\n",
    "sarimax_res = mod.fit(start_params=start, method=\"bfgs\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff71109f-b71a-4a45-9068-8a73969d4892",
   "metadata": {},
   "source": [
    "The two estimators fit similarly, although there is a small difference in the log-likelihood.  This is a numerical issue and should not materially affect the predictions. Importantly the two trend parameters, `const` and `x1` (unfortunately named for the time trend), differ between the two.  The other parameters are effectively identical."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84ffc296-0c6c-4052-98db-b6c9420e9a92",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(arx_res.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b158f625-0d67-4fed-bd0e-fae961395b69",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(sarimax_res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6b2a9e4-3796-44f1-9476-bf2da357d8b3",
   "metadata": {},
   "source": [
    "## Initial residuals `SARIMAX` and `ARIMA`\n",
    "\n",
    "Residuals for observations before the maximal model order, which depends on the AR, MA, Seasonal AR, Seasonal MA and differencing parameters, are not reliable and should not be used for performance assessment. In general, in an ARIMA with orders $(p,d,q)\\times(P,D,Q,s)$, the formula for residuals that are less well behaved is:\n",
    "\n",
    "$$\n",
    "\\max((P+D)s+p+d,Qs+q)\n",
    "$$\n",
    "\n",
    "We can simulate some data from an ARIMA(1,0,0)(1,0,0,12) and examine the residuals."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43f9387d-b431-4079-b98a-2a76f7e9595a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "rho = 0.8\n",
    "psi = -0.6\n",
    "beta = 20\n",
    "epsilon = eta.copy()\n",
    "for i in range(13, eta.shape[0]):\n",
    "    epsilon[i] = (\n",
    "        rho * epsilon[i - 1]\n",
    "        + psi * epsilon[i - 12]\n",
    "        - (rho * psi) * epsilon[i - 13]\n",
    "        + eta[i]\n",
    "    )\n",
    "y = beta + epsilon\n",
    "y = y[200:]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8f3e2ca-8022-4940-b1a9-ed5d245c73c7",
   "metadata": {},
   "source": [
    "With a large sample, the parameter estimates are very close to the DGP parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bcefc73-cfc4-4ae0-9af0-f55aa83bee99",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = ARIMA(y, order=(1, 0, 0), trend=\"c\", seasonal_order=(1, 0, 0, 12)).fit()\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0eafd7c5-a796-40a1-b460-9a9163686c3b",
   "metadata": {},
   "source": [
    "We can first examine the initial 13 residuals by plotting against the actual shocks in the model.  While there is a correspondence, it is fairly weak and the correlation is much less than 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9cc7fe30-4e40-468a-930e-14bf0aa0d929",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.rc(\"figure\", figsize=(10, 10))\n",
    "plt.rc(\"font\", size=14)\n",
    "\n",
    "_ = plt.scatter(res.resid[:13], eta[200 : 200 + 13])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1af117bd-a51c-496a-bf1d-0c08a88a8101",
   "metadata": {},
   "source": [
    "Looking at the next 24 residuals and shocks, we see there is nearly perfect correlation. This is expected in large samples once the less accurate residuals are ignored."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12b89d33-1cf2-435a-9dc8-ef04d2d6f8ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "_ = plt.scatter(res.resid[13:37], eta[200 + 13 : 200 + 37])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4a381b2-fcc4-44ee-901c-109cdc02a1f1",
   "metadata": {},
   "source": [
    "Next, we simulate an ARIMA(1,1,0), and include a time trend."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "790f834c-8b13-4475-9a09-aea19ace79fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(20210819)\n",
    "eta = rng.standard_normal(5200)\n",
    "rho = 0.8\n",
    "beta = 20\n",
    "epsilon = eta.copy()\n",
    "for i in range(2, eta.shape[0]):\n",
    "    epsilon[i] = (1 + rho) * epsilon[i - 1] - rho * epsilon[i - 2] + eta[i]\n",
    "t = np.arange(epsilon.shape[0])\n",
    "y = beta + 2 * t + epsilon\n",
    "y = y[200:]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5521dfb2-3bcc-4a28-b2df-f92e95fe4259",
   "metadata": {},
   "source": [
    "Again the parameter estimates are very close to the DGP parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d56ebbb-2143-4582-8409-df1c9026a3df",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = ARIMA(y, order=(1, 1, 0), trend=\"t\").fit()\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9626a1d-b742-4a48-b2e5-e10be84e01c7",
   "metadata": {},
   "source": [
    "The residuals are not accurate, and the first residual is approximately 500.  The others are closer, although in this model the first 2 should usually be ignored."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48a1b52b-6506-4e8d-aad5-4d8f80c65f79",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.resid[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "138445dd-e028-4e29-958f-6ab9f4efe674",
   "metadata": {},
   "source": [
    "The reason why the first residual is so large is that the optimal prediction of this value is the mean of the difference, which is 1.77.  Once the first value is known, the second value makes use of the first value in its prediction and the prediction is substantially closer to the truth."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11088c2a-9d7e-4d88-ac26-48a5b5df6867",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.predict(0, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf626404-fbd8-42ab-b6b2-5ffcad3e7b51",
   "metadata": {},
   "source": [
    "It is worth noting that the results class contains two parameters than can be helpful in understanding which residuals are problematic, `loglikelihood_burn` and `nobs_diffuse`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "947f58ee-44bb-45d6-88c9-6757b0be1481",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.loglikelihood_burn, res.nobs_diffuse"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
