{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Partialling-Out Demonstration\n",
        "\n",
        "Recover the education coefficient by first removing the part of education explained by experience and tenure."
      ]
    },
    {
      "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 residualize(series, controls):\n",
        "    X = np.column_stack([np.ones(len(df)), df[controls].to_numpy()])\n",
        "    beta = np.linalg.lstsq(X, series.to_numpy(), rcond=None)[0]\n",
        "    return series.to_numpy() - X @ beta\n",
        "\n",
        "educ_leftover = residualize(df[\"educ\"], [\"exper\", \"tenure\"])\n",
        "X_partial = np.column_stack([np.ones(len(df)), educ_leftover])\n",
        "partial_beta = np.linalg.lstsq(X_partial, df[\"lwage\"].to_numpy(), rcond=None)[0][1]\n",
        "\n",
        "X_full = np.column_stack([np.ones(len(df)), df[[\"educ\", \"exper\", \"tenure\"]].to_numpy()])\n",
        "full_beta = np.linalg.lstsq(X_full, df[\"lwage\"].to_numpy(), rcond=None)[0][1]\n",
        "\n",
        "print(\"Partialling-out coefficient:\", round(partial_beta, 4))\n",
        "print(\"Full model education coefficient:\", round(full_beta, 4))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "The partialling-out coefficient uses only the part of education that is not explained by the controls."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
