{
 "metadata": {
  "name": "",
  "signature": "sha256:a71297440c00135de29e296d1bacbc38ddcd90ca149d1c2042d1ef2e222bfb96"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Generalized Least Squares"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from __future__ import print_function\n",
      "import statsmodels.api as sm\n",
      "import numpy as np\n",
      "from statsmodels.iolib.table import (SimpleTable, default_txt_fmt)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The Longley dataset is a time series dataset: "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "data = sm.datasets.longley.load()\n",
      "data.exog = sm.add_constant(data.exog)\n",
      "print(data.exog[:5])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "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",
     "collapsed": false,
     "input": [
      "ols_resid = sm.OLS(data.endog, data.exog).fit().resid"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "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",
     "collapsed": false,
     "input": [
      "resid_fit = sm.OLS(ols_resid[1:], sm.add_constant(ols_resid[:-1])).fit()\n",
      "print(resid_fit.tvalues[1])\n",
      "print(resid_fit.pvalues[1])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      " While we don't have strong evidence that the errors follow an AR(1)\n",
      " process we continue"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "rho = resid_fit.params[1]"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "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",
     "collapsed": false,
     "input": [
      "from scipy.linalg import toeplitz\n",
      "\n",
      "toeplitz(range(5))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "order = toeplitz(range(len(ols_resid)))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "so that our error covariance structure is actually rho**order\n",
      " which defines an autocorrelation structure"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "sigma = rho**order\n",
      "gls_model = sm.GLS(data.endog, data.exog, sigma=sigma)\n",
      "gls_results = gls_model.fit()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "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",
     "collapsed": false,
     "input": [
      "glsar_model = sm.GLSAR(data.endog, data.exog, 1)\n",
      "glsar_results = glsar_model.iterative_fit(1)\n",
      "print(glsar_results.summary())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "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",
     "collapsed": false,
     "input": [
      "print(gls_results.params)\n",
      "print(glsar_results.params)\n",
      "print(gls_results.bse)\n",
      "print(glsar_results.bse)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}