{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# R-squared Comparison\n",
        "\n",
        "Compare R-squared across nested wage models and separate fit from causal interpretation."
      ]
    },
    {
      "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 model_stats(columns):\n",
        "    y = df[\"lwage\"].to_numpy()\n",
        "    X = np.column_stack([np.ones(len(df)), df[columns].to_numpy()])\n",
        "    beta = np.linalg.lstsq(X, y, rcond=None)[0]\n",
        "    residuals = y - X @ beta\n",
        "    r_squared = 1 - np.sum(residuals ** 2) / np.sum((y - y.mean()) ** 2)\n",
        "    return r_squared, dict(zip([\"intercept\", *columns], beta))\n",
        "\n",
        "for columns in [[\"educ\"], [\"educ\", \"exper\"], [\"educ\", \"exper\", \"tenure\"]]:\n",
        "    r2, beta = model_stats(columns)\n",
        "    print(\"Model:\", \", \".join(columns))\n",
        "    print(\"  R-squared:\", round(r2, 4))\n",
        "    print(\"  education coefficient:\", round(beta[\"educ\"], 4))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "R-squared usually rises when variables are added. That does not automatically mean the new model has a better causal interpretation."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
