{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Residuals and Fitted Values\n",
        "\n",
        "Create fitted log wages and residuals from a multiple-regression model."
      ]
    },
    {
      "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",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "df = pd.read_stata(DATASET)[VARIABLES].dropna()\n",
        "y = df[\"lwage\"].to_numpy()\n",
        "X = np.column_stack([np.ones(len(df)), df[[\"educ\", \"exper\", \"tenure\"]].to_numpy()])\n",
        "beta = np.linalg.lstsq(X, y, rcond=None)[0]\n",
        "df[\"fitted_lwage\"] = X @ beta\n",
        "df[\"residual\"] = y - df[\"fitted_lwage\"]\n",
        "\n",
        "print(df[[\"lwage\", \"fitted_lwage\", \"residual\"]].head())\n",
        "print(\"Residual mean:\", round(df[\"residual\"].mean(), 8))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "plt.scatter(df[\"fitted_lwage\"], df[\"residual\"], alpha=0.6)\n",
        "plt.axhline(0, linestyle=\"--\")\n",
        "plt.xlabel(\"Fitted log wage\")\n",
        "plt.ylabel(\"Residual\")\n",
        "plt.title(\"Residuals versus fitted values\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "A residual is the part of the outcome not fitted by the included variables. The plot helps students look for patterns the model may have missed."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
