{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Omitted-Variable Bias Example\n",
        "\n",
        "Compare a short model and a model with controls, then discuss whether omitted variables may have moved the slope."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from pathlib import Path\n",
        "\n",
        "DATASET = \"WAGE1.DTA\"\n",
        "VARIABLES = [\"lwage\", \"educ\", \"exper\", \"tenure\"]\n",
        "DATA_FOLDER = \"https://drive.google.com/drive/folders/1_STdcydIcst-opcbwOKRFzUXsgxQgBoS?usp=sharing\"\n",
        "\n",
        "if not Path(DATASET).exists():\n",
        "    raise FileNotFoundError(\n",
        "        \"Dataset file not installed yet\\n\"\n",
        "        f\"Dataset: WAGE1\\n\"\n",
        "        f\"Variables needed: {', '.join(VARIABLES)}\\n\"\n",
        "        f\"Course data folder: {DATA_FOLDER}\\n\"\n",
        "        \"Admin upload instruction: upload the dataset in Admin -> Datasets and make it available to this notebook.\"\n",
        "    )"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "\n",
        "df = pd.read_stata(DATASET)[VARIABLES].dropna()\n",
        "\n",
        "def slope(columns):\n",
        "    X = np.column_stack([np.ones(len(df)), df[columns].to_numpy()])\n",
        "    beta = np.linalg.lstsq(X, df[\"lwage\"].to_numpy(), rcond=None)[0]\n",
        "    return dict(zip([\"intercept\", *columns], beta))\n",
        "\n",
        "short = slope([\"educ\"])\n",
        "controlled = slope([\"educ\", \"exper\", \"tenure\"])\n",
        "print(\"Short model education coefficient:\", round(short[\"educ\"], 4))\n",
        "print(\"Controlled education coefficient:\", round(controlled[\"educ\"], 4))\n",
        "print(\"Difference:\", round(short[\"educ\"] - controlled[\"educ\"], 4))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "A coefficient difference is evidence that the omitted controls mattered in the sample. It is not, by itself, proof that all omitted-variable bias is solved."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
