{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generalized Least Squares"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import statsmodels.api as sm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Longley dataset is a time series dataset: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "data = sm.datasets.longley.load()\n",
    "data.exog = sm.add_constant(data.exog)\n",
    "print(data.exog.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    " Let's assume that the data is heteroskedastic and that we know\n",
    " the nature of the heteroskedasticity.  We can then define\n",
    " `sigma` and use it to give us a GLS model\n",
    "\n",
    " First we will obtain the residuals from an OLS fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "ols_resid = sm.OLS(data.endog, data.exog).fit().resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Assume that the error terms follow an AR(1) process with a trend:\n",
    "\n",
    "$\\epsilon_i = \\beta_0 + \\rho\\epsilon_{i-1} + \\eta_i$\n",
    "\n",
    "where $\\eta \\sim N(0,\\Sigma^2)$\n",
    "\n",
    "and that $\\rho$ is simply the correlation of the residual a consistent estimator for rho is to regress the residuals on the lagged residuals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "resid_fit = sm.OLS(\n",
    "    np.asarray(ols_resid)[1:], sm.add_constant(np.asarray(ols_resid)[:-1])\n",
    ").fit()\n",
    "print(resid_fit.tvalues[1])\n",
    "print(resid_fit.pvalues[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " While we do not have strong evidence that the errors follow an AR(1)\n",
    " process we continue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "rho = resid_fit.params[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we know, an AR(1) process means that near-neighbors have a stronger\n",
    " relation so we can give this structure by using a toeplitz matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from scipy.linalg import toeplitz\n",
    "\n",
    "toeplitz(range(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "order = toeplitz(range(len(ols_resid)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "so that our error covariance structure is actually rho**order\n",
    " which defines an autocorrelation structure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sigma = rho ** order\n",
    "gls_model = sm.GLS(data.endog, data.exog, sigma=sigma)\n",
    "gls_results = gls_model.fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Of course, the exact rho in this instance is not known so it it might make more sense to use feasible gls, which currently only has experimental support.\n",
    "\n",
    "We can use the GLSAR model with one lag, to get to a similar result:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "glsar_model = sm.GLSAR(data.endog, data.exog, 1)\n",
    "glsar_results = glsar_model.iterative_fit(1)\n",
    "print(glsar_results.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Comparing gls and glsar results, we see that there are some small\n",
    " differences in the parameter estimates and the resulting standard\n",
    " errors of the parameter estimate. This might be do to the numerical\n",
    " differences in the algorithm, e.g. the treatment of initial conditions,\n",
    " because of the small number of observations in the longley dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(gls_results.params)\n",
    "print(glsar_results.params)\n",
    "print(gls_results.bse)\n",
    "print(glsar_results.bse)"
   ]
  }
 ],
 "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.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
