{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# VIF Calculation\n",
        "\n",
        "Calculate variance inflation factors for education, experience, and tenure using auxiliary regressions."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from pathlib import Path\n",
        "\n",
        "DATASET = \"WAGE1.DTA\"\n",
        "VARIABLES = [\"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 r_squared(target, controls):\n",
        "    y = df[target].to_numpy()\n",
        "    X = np.column_stack([np.ones(len(df)), df[controls].to_numpy()])\n",
        "    beta = np.linalg.lstsq(X, y, rcond=None)[0]\n",
        "    residuals = y - X @ beta\n",
        "    return 1 - np.sum(residuals ** 2) / np.sum((y - y.mean()) ** 2)\n",
        "\n",
        "for target in VARIABLES:\n",
        "    controls = [name for name in VARIABLES if name != target]\n",
        "    r2 = r_squared(target, controls)\n",
        "    vif = 1 / (1 - r2)\n",
        "    print(f\"{target}: auxiliary R-squared={r2:.4f}, VIF={vif:.3f}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "VIF summarizes how strongly one regressor can be predicted by the other regressors. It is a precision warning, not automatic proof that a model is invalid."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
