{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Feasible GLS\n",
        "\n",
        "Module 8 notebook lab. This notebook uses original Ceteris Lab teaching data and does not report real empirical findings.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Learning goal\n",
        "Estimate a variance function and fit FGLS.\n",
        "\n",
        "Dataset: MODULE8_FGLS_DEMO. Variables: observation_id, outcome, income, age, treatment, variance_driver.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import statsmodels.api as sm\n",
        "\n",
        "df = pd.read_csv(\"/data/module-8/module8_fgls_demo.csv\")\n",
        "X = sm.add_constant(df[[\"income\", \"age\", \"treatment\"]])\n",
        "ols = sm.OLS(df[\"outcome\"], X).fit()\n",
        "variance_model = sm.OLS(np.log(ols.resid ** 2 + 1e-6), X).fit()\n",
        "h_hat = np.exp(variance_model.fittedvalues)\n",
        "fgls = sm.WLS(df[\"outcome\"], X, weights=1 / h_hat).fit()\n",
        "print(\"OLS\")\n",
        "print(ols.params.round(4))\n",
        "print(\"FGLS\")\n",
        "print(fgls.params.round(4))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reflection\n",
        "Write two sentences: one sentence explaining what the diagnostic or robust result says, and one sentence explaining a limitation or next step.\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    },
    "ceteris_lab": {
      "module": "Module 8",
      "lesson": "Feasible GLS",
      "dataset": "MODULE8_FGLS_DEMO",
      "copyright": "Original Ceteris Lab notebook. No external text, tables, or figures are reproduced."
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
