{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Robust Linear Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import statsmodels.api as sm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Estimation\n",
    "\n",
    "Load data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = sm.datasets.stackloss.load()\n",
    "data.exog = sm.add_constant(data.exog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Huber's T norm with the (default) median absolute deviation scaling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "huber_t = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT())\n",
    "hub_results = huber_t.fit()\n",
    "print(hub_results.params)\n",
    "print(hub_results.bse)\n",
    "print(\n",
    "    hub_results.summary(\n",
    "        yname=\"y\", xname=[\"var_%d\" % i for i in range(len(hub_results.params))]\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Huber's T norm with 'H2' covariance matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hub_results2 = huber_t.fit(cov=\"H2\")\n",
    "print(hub_results2.params)\n",
    "print(hub_results2.bse)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Andrew's Wave norm with Huber's Proposal 2 scaling and 'H3' covariance matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "andrew_mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.AndrewWave())\n",
    "andrew_results = andrew_mod.fit(scale_est=sm.robust.scale.HuberScale(), cov=\"H3\")\n",
    "print(\"Parameters: \", andrew_results.params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "See ``help(sm.RLM.fit)`` for more options and ``module sm.robust.scale`` for scale options\n",
    "\n",
    "## Comparing OLS and RLM\n",
    "\n",
    "Artificial data with outliers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nsample = 50\n",
    "x1 = np.linspace(0, 20, nsample)\n",
    "X = np.column_stack((x1, (x1 - 5) ** 2))\n",
    "X = sm.add_constant(X)\n",
    "sig = 0.3  # smaller error variance makes OLS<->RLM contrast bigger\n",
    "beta = [5, 0.5, -0.0]\n",
    "y_true2 = np.dot(X, beta)\n",
    "y2 = y_true2 + sig * 1.0 * np.random.normal(size=nsample)\n",
    "y2[[39, 41, 43, 45, 48]] -= 5  # add some outliers (10% of nsample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 1: quadratic function with linear truth\n",
    "\n",
    "Note that the quadratic term in OLS regression will capture outlier effects. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = sm.OLS(y2, X).fit()\n",
    "print(res.params)\n",
    "print(res.bse)\n",
    "print(res.predict())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Estimate RLM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resrlm = sm.RLM(y2, X).fit()\n",
    "print(resrlm.params)\n",
    "print(resrlm.bse)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Draw a plot to compare OLS estimates to the robust estimates:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(12, 8))\n",
    "ax = fig.add_subplot(111)\n",
    "ax.plot(x1, y2, \"o\", label=\"data\")\n",
    "ax.plot(x1, y_true2, \"b-\", label=\"True\")\n",
    "pred_ols = res.get_prediction()\n",
    "iv_l = pred_ols.summary_frame()[\"obs_ci_lower\"]\n",
    "iv_u = pred_ols.summary_frame()[\"obs_ci_upper\"]\n",
    "\n",
    "ax.plot(x1, res.fittedvalues, \"r-\", label=\"OLS\")\n",
    "ax.plot(x1, iv_u, \"r--\")\n",
    "ax.plot(x1, iv_l, \"r--\")\n",
    "ax.plot(x1, resrlm.fittedvalues, \"g.-\", label=\"RLM\")\n",
    "ax.legend(loc=\"best\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 2: linear function with linear truth\n",
    "\n",
    "Fit a new OLS model using only the linear term and the constant:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X2 = X[:, [0, 1]]\n",
    "res2 = sm.OLS(y2, X2).fit()\n",
    "print(res2.params)\n",
    "print(res2.bse)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Estimate RLM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "resrlm2 = sm.RLM(y2, X2).fit()\n",
    "print(resrlm2.params)\n",
    "print(resrlm2.bse)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Draw a plot to compare OLS estimates to the robust estimates:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pred_ols = res2.get_prediction()\n",
    "iv_l = pred_ols.summary_frame()[\"obs_ci_lower\"]\n",
    "iv_u = pred_ols.summary_frame()[\"obs_ci_upper\"]\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 6))\n",
    "ax.plot(x1, y2, \"o\", label=\"data\")\n",
    "ax.plot(x1, y_true2, \"b-\", label=\"True\")\n",
    "ax.plot(x1, res2.fittedvalues, \"r-\", label=\"OLS\")\n",
    "ax.plot(x1, iv_u, \"r--\")\n",
    "ax.plot(x1, iv_l, \"r--\")\n",
    "ax.plot(x1, resrlm2.fittedvalues, \"g.-\", label=\"RLM\")\n",
    "legend = ax.legend(loc=\"best\")"
   ]
  }
 ],
 "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": 4
}
