{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "129e963d",
   "metadata": {},
   "source": [
    "# How linear regression works: the math, checked in Python\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/linear-regression-explained\n",
    "\n",
    "Put `northpine_weekly.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_weekly.csv). Northpine Software is a made-up company; the data is synthetic.\n",
    "\n",
    "Each section matches a section of the guide and prints the numbers it quotes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fb81fbc",
   "metadata": {},
   "source": [
    "## 1. The data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "34e91880",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:36.209410Z",
     "iopub.status.busy": "2026-12-05T03:22:36.209330Z",
     "iopub.status.idle": "2026-12-05T03:22:37.099429Z",
     "shell.execute_reply": "2026-12-05T03:22:37.098941Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(156, 7)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>week</th>\n",
       "      <th>search_interest_index</th>\n",
       "      <th>paid_search_spend</th>\n",
       "      <th>paid_social_spend</th>\n",
       "      <th>display_spend</th>\n",
       "      <th>promotion_week</th>\n",
       "      <th>revenue</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2023-01-02</td>\n",
       "      <td>81.2</td>\n",
       "      <td>3910</td>\n",
       "      <td>3790</td>\n",
       "      <td>4190</td>\n",
       "      <td>0</td>\n",
       "      <td>19600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2023-01-09</td>\n",
       "      <td>84.9</td>\n",
       "      <td>4400</td>\n",
       "      <td>9700</td>\n",
       "      <td>2990</td>\n",
       "      <td>0</td>\n",
       "      <td>22490</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2023-01-16</td>\n",
       "      <td>92.8</td>\n",
       "      <td>8690</td>\n",
       "      <td>3820</td>\n",
       "      <td>2830</td>\n",
       "      <td>0</td>\n",
       "      <td>35440</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2023-01-23</td>\n",
       "      <td>89.2</td>\n",
       "      <td>10980</td>\n",
       "      <td>5410</td>\n",
       "      <td>2570</td>\n",
       "      <td>0</td>\n",
       "      <td>37450</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2023-01-30</td>\n",
       "      <td>96.7</td>\n",
       "      <td>7670</td>\n",
       "      <td>6690</td>\n",
       "      <td>1530</td>\n",
       "      <td>0</td>\n",
       "      <td>36110</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        week  search_interest_index  paid_search_spend  paid_social_spend  \\\n",
       "0 2023-01-02                   81.2               3910               3790   \n",
       "1 2023-01-09                   84.9               4400               9700   \n",
       "2 2023-01-16                   92.8               8690               3820   \n",
       "3 2023-01-23                   89.2              10980               5410   \n",
       "4 2023-01-30                   96.7               7670               6690   \n",
       "\n",
       "   display_spend  promotion_week  revenue  \n",
       "0           4190               0    19600  \n",
       "1           2990               0    22490  \n",
       "2           2830               0    35440  \n",
       "3           2570               0    37450  \n",
       "4           1530               0    36110  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import statsmodels.formula.api as smf\n",
    "from sklearn.linear_model import Lasso, LinearRegression, Ridge, RidgeCV\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
    "from sklearn.model_selection import TimeSeriesSplit, cross_val_score\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "weekly = pd.read_csv(\"northpine_weekly.csv\", parse_dates=[\"week\"])\n",
    "print(weekly.shape)\n",
    "weekly.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "84892c71",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.100771Z",
     "iopub.status.busy": "2026-12-05T03:22:37.100625Z",
     "iopub.status.idle": "2026-12-05T03:22:37.108243Z",
     "shell.execute_reply": "2026-12-05T03:22:37.107814Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mean</th>\n",
       "      <th>std</th>\n",
       "      <th>min</th>\n",
       "      <th>max</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>week</th>\n",
       "      <td>2024-06-27 12:00:00</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2023-01-02 00:00:00</td>\n",
       "      <td>2025-12-22 00:00:00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>search_interest_index</th>\n",
       "      <td>109.6</td>\n",
       "      <td>13.8</td>\n",
       "      <td>81.2</td>\n",
       "      <td>134.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_search_spend</th>\n",
       "      <td>9536.5</td>\n",
       "      <td>2564.4</td>\n",
       "      <td>3910.0</td>\n",
       "      <td>15280.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_social_spend</th>\n",
       "      <td>5656.0</td>\n",
       "      <td>2314.8</td>\n",
       "      <td>500.0</td>\n",
       "      <td>12200.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>display_spend</th>\n",
       "      <td>4480.1</td>\n",
       "      <td>1499.4</td>\n",
       "      <td>400.0</td>\n",
       "      <td>8580.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>promotion_week</th>\n",
       "      <td>0.2</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>revenue</th>\n",
       "      <td>66283.1</td>\n",
       "      <td>25499.2</td>\n",
       "      <td>6710.0</td>\n",
       "      <td>120220.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                      mean      std                  min  \\\n",
       "week                   2024-06-27 12:00:00      NaN  2023-01-02 00:00:00   \n",
       "search_interest_index                109.6     13.8                 81.2   \n",
       "paid_search_spend                   9536.5   2564.4               3910.0   \n",
       "paid_social_spend                   5656.0   2314.8                500.0   \n",
       "display_spend                       4480.1   1499.4                400.0   \n",
       "promotion_week                         0.2      0.4                  0.0   \n",
       "revenue                            66283.1  25499.2               6710.0   \n",
       "\n",
       "                                       max  \n",
       "week                   2025-12-22 00:00:00  \n",
       "search_interest_index                134.3  \n",
       "paid_search_spend                  15280.0  \n",
       "paid_social_spend                  12200.0  \n",
       "display_spend                       8580.0  \n",
       "promotion_week                         1.0  \n",
       "revenue                           120220.0  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "weekly.describe().round(1).T[[\"mean\", \"std\", \"min\", \"max\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5a7d1374",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.109419Z",
     "iopub.status.busy": "2026-12-05T03:22:37.109343Z",
     "iopub.status.idle": "2026-12-05T03:22:37.111359Z",
     "shell.execute_reply": "2026-12-05T03:22:37.110957Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "promotion weeks: 24 of 156\n",
      "revenue: average 66,283, lowest 6,710, highest 120,220\n"
     ]
    }
   ],
   "source": [
    "print(f\"promotion weeks: {weekly['promotion_week'].sum()} of {len(weekly)}\")\n",
    "print(f\"revenue: average {weekly['revenue'].mean():,.0f}, lowest {weekly['revenue'].min():,}, highest {weekly['revenue'].max():,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "46855c72",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.112369Z",
     "iopub.status.busy": "2026-12-05T03:22:37.112289Z",
     "iopub.status.idle": "2026-12-05T03:22:37.115538Z",
     "shell.execute_reply": "2026-12-05T03:22:37.115117Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>search_interest_index</th>\n",
       "      <th>paid_search_spend</th>\n",
       "      <th>paid_social_spend</th>\n",
       "      <th>display_spend</th>\n",
       "      <th>promotion_week</th>\n",
       "      <th>revenue</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>search_interest_index</th>\n",
       "      <td>1.00</td>\n",
       "      <td>0.80</td>\n",
       "      <td>-0.07</td>\n",
       "      <td>0.53</td>\n",
       "      <td>-0.04</td>\n",
       "      <td>0.95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_search_spend</th>\n",
       "      <td>0.80</td>\n",
       "      <td>1.00</td>\n",
       "      <td>-0.10</td>\n",
       "      <td>0.46</td>\n",
       "      <td>-0.09</td>\n",
       "      <td>0.82</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_social_spend</th>\n",
       "      <td>-0.07</td>\n",
       "      <td>-0.10</td>\n",
       "      <td>1.00</td>\n",
       "      <td>0.02</td>\n",
       "      <td>-0.08</td>\n",
       "      <td>0.04</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>display_spend</th>\n",
       "      <td>0.53</td>\n",
       "      <td>0.46</td>\n",
       "      <td>0.02</td>\n",
       "      <td>1.00</td>\n",
       "      <td>-0.13</td>\n",
       "      <td>0.55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>promotion_week</th>\n",
       "      <td>-0.04</td>\n",
       "      <td>-0.09</td>\n",
       "      <td>-0.08</td>\n",
       "      <td>-0.13</td>\n",
       "      <td>1.00</td>\n",
       "      <td>0.05</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>revenue</th>\n",
       "      <td>0.95</td>\n",
       "      <td>0.82</td>\n",
       "      <td>0.04</td>\n",
       "      <td>0.55</td>\n",
       "      <td>0.05</td>\n",
       "      <td>1.00</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       search_interest_index  paid_search_spend  \\\n",
       "search_interest_index                   1.00               0.80   \n",
       "paid_search_spend                       0.80               1.00   \n",
       "paid_social_spend                      -0.07              -0.10   \n",
       "display_spend                           0.53               0.46   \n",
       "promotion_week                         -0.04              -0.09   \n",
       "revenue                                 0.95               0.82   \n",
       "\n",
       "                       paid_social_spend  display_spend  promotion_week  \\\n",
       "search_interest_index              -0.07           0.53           -0.04   \n",
       "paid_search_spend                  -0.10           0.46           -0.09   \n",
       "paid_social_spend                   1.00           0.02           -0.08   \n",
       "display_spend                       0.02           1.00           -0.13   \n",
       "promotion_week                     -0.08          -0.13            1.00   \n",
       "revenue                             0.04           0.55            0.05   \n",
       "\n",
       "                       revenue  \n",
       "search_interest_index     0.95  \n",
       "paid_search_spend         0.82  \n",
       "paid_social_spend         0.04  \n",
       "display_spend             0.55  \n",
       "promotion_week            0.05  \n",
       "revenue                   1.00  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "weekly.drop(columns=\"week\").corr().round(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c86de56",
   "metadata": {},
   "source": [
    "## 2. One input: the slope and intercept by hand"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e5f8c83f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.116461Z",
     "iopub.status.busy": "2026-12-05T03:22:37.116390Z",
     "iopub.status.idle": "2026-12-05T03:22:37.119351Z",
     "shell.execute_reply": "2026-12-05T03:22:37.118910Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average spend   9,536\n",
      "average revenue 66,283\n",
      "covariance      53,405,514\n",
      "variance        6,576,135\n",
      "slope           8.121\n",
      "intercept       -11,164\n"
     ]
    }
   ],
   "source": [
    "x = weekly[\"paid_search_spend\"]\n",
    "y = weekly[\"revenue\"]\n",
    "\n",
    "slope = ((x - x.mean()) * (y - y.mean())).sum() / ((x - x.mean()) ** 2).sum()\n",
    "intercept = y.mean() - slope * x.mean()\n",
    "\n",
    "print(f\"average spend   {x.mean():,.0f}\")\n",
    "print(f\"average revenue {y.mean():,.0f}\")\n",
    "print(f\"covariance      {np.cov(x, y)[0, 1]:,.0f}\")\n",
    "print(f\"variance        {x.var():,.0f}\")\n",
    "print(f\"slope           {slope:.3f}\")\n",
    "print(f\"intercept       {intercept:,.0f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d5907050",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.120330Z",
     "iopub.status.busy": "2026-12-05T03:22:37.120257Z",
     "iopub.status.idle": "2026-12-05T03:22:37.123080Z",
     "shell.execute_reply": "2026-12-05T03:22:37.122760Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "week of 2023-01-02: spend 3,910, revenue 19,600, predicted 20,590, residual -990\n",
      "sum of squared errors 33,556,834,142\n",
      "RMSE 14,667, MAE 11,473\n",
      "R² = 1 - 3.356e+10 / 1.008e+11 = 0.667\n"
     ]
    }
   ],
   "source": [
    "first = weekly.iloc[0]\n",
    "pred = intercept + slope * first[\"paid_search_spend\"]\n",
    "print(f\"week of {first['week']:%Y-%m-%d}: spend {first['paid_search_spend']:,}, \"\n",
    "      f\"revenue {first['revenue']:,}, predicted {pred:,.0f}, residual {first['revenue'] - pred:,.0f}\")\n",
    "\n",
    "resid = y - (intercept + slope * x)\n",
    "sse = (resid ** 2).sum()\n",
    "sst = ((y - y.mean()) ** 2).sum()\n",
    "print(f\"sum of squared errors {sse:,.0f}\")\n",
    "print(f\"RMSE {np.sqrt(sse / len(y)):,.0f}, MAE {resid.abs().mean():,.0f}\")\n",
    "print(f\"R² = 1 - {sse:.4g} / {sst:.4g} = {1 - sse / sst:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67022aed",
   "metadata": {},
   "source": [
    "## 3. The same answer from the normal equations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1b51c3a5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.124034Z",
     "iopub.status.busy": "2026-12-05T03:22:37.123968Z",
     "iopub.status.idle": "2026-12-05T03:22:37.126077Z",
     "shell.execute_reply": "2026-12-05T03:22:37.125771Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X'X =\n",
      " [[1.56000000e+02 1.48769000e+06]\n",
      " [1.48769000e+06 1.52066185e+10]]\n",
      "X'y = [1.03401600e+07 1.06886525e+11]\n",
      "beta = [-1.1163675e+04  8.1210000e+00]\n"
     ]
    }
   ],
   "source": [
    "X = np.column_stack([np.ones(len(x)), x])\n",
    "XtX = X.T @ X\n",
    "Xty = X.T @ y\n",
    "beta = np.linalg.solve(XtX, Xty)\n",
    "print(\"X'X =\\n\", XtX.round(0))\n",
    "print(\"X'y =\", Xty.round(0))\n",
    "print(\"beta =\", beta.round(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0128ee91",
   "metadata": {},
   "source": [
    "## 4. Gradient descent, with and without centring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4d0f2d88",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:37.126952Z",
     "iopub.status.busy": "2026-12-05T03:22:37.126886Z",
     "iopub.status.idle": "2026-12-05T03:22:38.547352Z",
     "shell.execute_reply": "2026-12-05T03:22:38.546869Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    10 steps  raw: slope 6.969   centred: slope 3.989\n",
      "   100 steps  raw: slope 7.036   centred: slope 8.112\n",
      "  1000 steps  raw: slope 7.524   centred: slope 8.121\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 10000 steps  raw: slope 8.120   centred: slope 8.121\n"
     ]
    }
   ],
   "source": [
    "def descend(xs, ys, rate, steps):\n",
    "    b0 = b1 = 0.0\n",
    "    for _ in range(steps):\n",
    "        err = b0 + b1 * xs - ys\n",
    "        b0 -= rate * 2 * err.mean()\n",
    "        b1 -= rate * 2 * (err * xs).mean()\n",
    "    return b0, b1\n",
    "\n",
    "xk, yk = x / 1000, y / 1000          # thousands of dollars\n",
    "for steps in [10, 100, 1000, 10000]:\n",
    "    raw = descend(xk, yk, 0.005, steps)\n",
    "    cen = descend(xk - xk.mean(), yk, 0.005, steps)\n",
    "    print(f\"{steps:>6} steps  raw: slope {raw[1]:.3f}   centred: slope {cen[1]:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8313b26",
   "metadata": {},
   "source": [
    "## 5. Several inputs, and what leaving one out does"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f82717d6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.548620Z",
     "iopub.status.busy": "2026-12-05T03:22:38.548537Z",
     "iopub.status.idle": "2026-12-05T03:22:38.560247Z",
     "shell.execute_reply": "2026-12-05T03:22:38.559829Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>search only</th>\n",
       "      <th>all spend</th>\n",
       "      <th>all spend + demand</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Intercept</th>\n",
       "      <td>-11163.68</td>\n",
       "      <td>-30252.17</td>\n",
       "      <td>-125502.76</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>display_spend</th>\n",
       "      <td>NaN</td>\n",
       "      <td>3.84</td>\n",
       "      <td>1.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_search_spend</th>\n",
       "      <td>8.12</td>\n",
       "      <td>7.33</td>\n",
       "      <td>1.67</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>paid_social_spend</th>\n",
       "      <td>NaN</td>\n",
       "      <td>1.36</td>\n",
       "      <td>1.37</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>promotion_week</th>\n",
       "      <td>NaN</td>\n",
       "      <td>10996.03</td>\n",
       "      <td>8473.79</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>search_interest_index</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>1479.28</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       search only  all spend  all spend + demand\n",
       "Intercept                -11163.68  -30252.17          -125502.76\n",
       "display_spend                  NaN       3.84                1.06\n",
       "paid_search_spend             8.12       7.33                1.67\n",
       "paid_social_spend              NaN       1.36                1.37\n",
       "promotion_week                 NaN   10996.03             8473.79\n",
       "search_interest_index          NaN        NaN             1479.28"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spend = \"paid_search_spend + paid_social_spend + display_spend + promotion_week\"\n",
    "models = {\n",
    "    \"search only\": smf.ols(\"revenue ~ paid_search_spend\", weekly).fit(),\n",
    "    \"all spend\": smf.ols(f\"revenue ~ {spend}\", weekly).fit(),\n",
    "    \"all spend + demand\": smf.ols(f\"revenue ~ {spend} + search_interest_index\", weekly).fit(),\n",
    "}\n",
    "pd.DataFrame({name: m.params for name, m in models.items()}).round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "03783c39",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.561422Z",
     "iopub.status.busy": "2026-12-05T03:22:38.561331Z",
     "iopub.status.idle": "2026-12-05T03:22:38.565360Z",
     "shell.execute_reply": "2026-12-05T03:22:38.564883Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                             coef   std_err       t      ci_low     ci_high\n",
      "Intercept             -125502.760  4632.927 -27.089 -134656.986 -116348.535\n",
      "paid_search_spend           1.665     0.317   5.250       1.039       2.292\n",
      "paid_social_spend           1.375     0.210   6.559       0.961       1.789\n",
      "display_spend               1.058     0.382   2.768       0.303       1.813\n",
      "promotion_week           8473.788  1347.279   6.290    5811.692   11135.884\n",
      "search_interest_index    1479.279    61.287  24.137    1358.183    1600.376\n",
      "\n",
      "R² 0.947, adjusted R² 0.945, residual standard error 5,979, weeks 156\n",
      "degrees of freedom 150, t for 95%: 1.976\n"
     ]
    }
   ],
   "source": [
    "full = models[\"all spend + demand\"]\n",
    "table = pd.DataFrame({\"coef\": full.params, \"std_err\": full.bse, \"t\": full.tvalues,\n",
    "                      \"ci_low\": full.conf_int()[0], \"ci_high\": full.conf_int()[1]})\n",
    "print(table.round(3))\n",
    "print(f\"\\nR² {full.rsquared:.3f}, adjusted R² {full.rsquared_adj:.3f}, \"\n",
    "      f\"residual standard error {np.sqrt(full.mse_resid):,.0f}, weeks {int(full.nobs)}\")\n",
    "\n",
    "from scipy import stats\n",
    "t_crit = stats.t.ppf(0.975, full.df_resid)\n",
    "print(f\"degrees of freedom {full.df_resid:.0f}, t for 95%: {t_crit:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "82b2c721",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.566452Z",
     "iopub.status.busy": "2026-12-05T03:22:38.566375Z",
     "iopub.status.idle": "2026-12-05T03:22:38.568524Z",
     "shell.execute_reply": "2026-12-05T03:22:38.568065Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "search only          R² 0.667   residual standard error  14,761\n",
      "all spend            R² 0.740   residual standard error  13,171\n",
      "all spend + demand   R² 0.947   residual standard error   5,979\n"
     ]
    }
   ],
   "source": [
    "for name, m in models.items():\n",
    "    print(f\"{name:<20} R² {m.rsquared:.3f}   residual standard error {np.sqrt(m.mse_resid):>7,.0f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "455044ad",
   "metadata": {},
   "source": [
    "## 6. Omitted-variable bias, checked"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e2075ad7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.569491Z",
     "iopub.status.busy": "2026-12-05T03:22:38.569412Z",
     "iopub.status.idle": "2026-12-05T03:22:38.575387Z",
     "shell.execute_reply": "2026-12-05T03:22:38.574968Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "short regression: 7.333\n",
      "long regression:  1.665\n",
      "gamma 1479.28 x delta 0.00383 = 5.668\n",
      "long + bias = 7.333\n"
     ]
    }
   ],
   "source": [
    "short = models[\"all spend\"].params[\"paid_search_spend\"]\n",
    "long = full.params[\"paid_search_spend\"]\n",
    "gamma = full.params[\"search_interest_index\"]                       # demand -> revenue\n",
    "aux = smf.ols(f\"search_interest_index ~ {spend}\", weekly).fit()    # demand ~ spend\n",
    "delta = aux.params[\"paid_search_spend\"]\n",
    "\n",
    "print(f\"short regression: {short:.3f}\")\n",
    "print(f\"long regression:  {long:.3f}\")\n",
    "print(f\"gamma {gamma:.2f} x delta {delta:.5f} = {gamma * delta:.3f}\")\n",
    "print(f\"long + bias = {long + gamma * delta:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f290a9d6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.576388Z",
     "iopub.status.busy": "2026-12-05T03:22:38.576319Z",
     "iopub.status.idle": "2026-12-05T03:22:38.583949Z",
     "shell.execute_reply": "2026-12-05T03:22:38.583550Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "slope of leftover revenue on leftover search spend: 1.665\n"
     ]
    }
   ],
   "source": [
    "others = \"paid_social_spend + display_spend + promotion_week + search_interest_index\"\n",
    "r_rev = smf.ols(f\"revenue ~ {others}\", weekly).fit().resid\n",
    "r_search = smf.ols(f\"paid_search_spend ~ {others}\", weekly).fit().resid\n",
    "fwl = (r_rev * r_search).sum() / (r_search ** 2).sum()\n",
    "print(f\"slope of leftover revenue on leftover search spend: {fwl:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17993a98",
   "metadata": {},
   "source": [
    "## 7. Checking the assumptions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9e1f3091",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.585129Z",
     "iopub.status.busy": "2026-12-05T03:22:38.585049Z",
     "iopub.status.idle": "2026-12-05T03:22:38.587836Z",
     "shell.execute_reply": "2026-12-05T03:22:38.587509Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "all spend            lag-1 correlation of residuals 0.28   Durbin-Watson 1.44\n",
      "all spend + demand   lag-1 correlation of residuals -0.17   Durbin-Watson 2.32\n"
     ]
    }
   ],
   "source": [
    "from statsmodels.stats.stattools import durbin_watson\n",
    "\n",
    "for name in [\"all spend\", \"all spend + demand\"]:\n",
    "    e = models[name].resid\n",
    "    print(f\"{name:<20} lag-1 correlation of residuals {e.autocorr(1):.2f}   \"\n",
    "          f\"Durbin-Watson {durbin_watson(e):.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "a0cf87d2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.588917Z",
     "iopub.status.busy": "2026-12-05T03:22:38.588844Z",
     "iopub.status.idle": "2026-12-05T03:22:38.593357Z",
     "shell.execute_reply": "2026-12-05T03:22:38.593000Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "paid_search_spend        2.87\n",
       "paid_social_spend        1.02\n",
       "display_spend            1.42\n",
       "promotion_week           1.03\n",
       "search_interest_index    3.10\n",
       "dtype: float64"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from statsmodels.stats.outliers_influence import variance_inflation_factor\n",
    "\n",
    "exog = full.model.exog\n",
    "vif = {name: variance_inflation_factor(exog, i)\n",
    "       for i, name in enumerate(full.model.exog_names) if name != \"Intercept\"}\n",
    "pd.Series(vif).round(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2b44965",
   "metadata": {},
   "source": [
    "## 8. How sure are we? The bootstrap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "a1b78bdf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:38.594345Z",
     "iopub.status.busy": "2026-12-05T03:22:38.594280Z",
     "iopub.status.idle": "2026-12-05T03:22:41.154806Z",
     "shell.execute_reply": "2026-12-05T03:22:41.154319Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bootstrap: standard error 0.321, middle 95% 1.01 to 2.29\n",
      "formula:   standard error 0.317\n",
      "correlation of the search and demand estimates across resamples: -0.78\n"
     ]
    }
   ],
   "source": [
    "formula = f\"revenue ~ {spend} + search_interest_index\"\n",
    "rng = np.random.default_rng(42)\n",
    "boot = []\n",
    "for _ in range(1000):\n",
    "    sample = weekly.iloc[rng.integers(0, len(weekly), len(weekly))]\n",
    "    boot.append(smf.ols(formula, sample).fit().params)\n",
    "boot = pd.DataFrame(boot)\n",
    "\n",
    "b = boot[\"paid_search_spend\"]\n",
    "print(f\"bootstrap: standard error {b.std():.3f}, \"\n",
    "      f\"middle 95% {b.quantile(0.025):.2f} to {b.quantile(0.975):.2f}\")\n",
    "print(f\"formula:   standard error {full.bse['paid_search_spend']:.3f}\")\n",
    "print(f\"correlation of the search and demand estimates across resamples: \"\n",
    "      f\"{boot['paid_search_spend'].corr(boot['search_interest_index']):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4e66fbc",
   "metadata": {},
   "source": [
    "## 9. Testing on weeks the model has not seen"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "cd951003",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.155922Z",
     "iopub.status.busy": "2026-12-05T03:22:41.155837Z",
     "iopub.status.idle": "2026-12-05T03:22:41.169210Z",
     "shell.execute_reply": "2026-12-05T03:22:41.168851Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "all spend            train RMSE  12,107   test RMSE  16,649   test MAE 12,528   test R² 0.551\n",
      "all spend + demand   train RMSE   5,895   test RMSE   5,776   test MAE  4,940   test R² 0.946\n",
      "test weeks: 2025-06-30 to 2025-12-22\n"
     ]
    }
   ],
   "source": [
    "features = [\"paid_search_spend\", \"paid_social_spend\", \"display_spend\",\n",
    "            \"promotion_week\", \"search_interest_index\"]\n",
    "train, test = weekly.iloc[:130], weekly.iloc[130:]\n",
    "\n",
    "for name, cols in [(\"all spend\", features[:4]), (\"all spend + demand\", features)]:\n",
    "    lr = LinearRegression().fit(train[cols], train[\"revenue\"])\n",
    "    p_train = lr.predict(train[cols])\n",
    "    p_test = lr.predict(test[cols])\n",
    "    print(f\"{name:<20} train RMSE {mean_squared_error(train['revenue'], p_train) ** 0.5:>7,.0f}   \"\n",
    "          f\"test RMSE {mean_squared_error(test['revenue'], p_test) ** 0.5:>7,.0f}   \"\n",
    "          f\"test MAE {mean_absolute_error(test['revenue'], p_test):>6,.0f}   \"\n",
    "          f\"test R² {r2_score(test['revenue'], p_test):.3f}\")\n",
    "print(f\"test weeks: {test['week'].min():%Y-%m-%d} to {test['week'].max():%Y-%m-%d}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64ce417b",
   "metadata": {},
   "source": [
    "## 10. Overfitting: add columns of pure noise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "028161e5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.170393Z",
     "iopub.status.busy": "2026-12-05T03:22:41.170319Z",
     "iopub.status.idle": "2026-12-05T03:22:41.781124Z",
     "shell.execute_reply": "2026-12-05T03:22:41.780650Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>noise_columns</th>\n",
       "      <th>train_r2</th>\n",
       "      <th>test_r2</th>\n",
       "      <th>ridge_test_r2</th>\n",
       "      <th>ridge_alpha</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0.947</td>\n",
       "      <td>0.946</td>\n",
       "      <td>0.946</td>\n",
       "      <td>0.010</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>20</td>\n",
       "      <td>0.955</td>\n",
       "      <td>0.929</td>\n",
       "      <td>0.927</td>\n",
       "      <td>1.172</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>40</td>\n",
       "      <td>0.960</td>\n",
       "      <td>0.910</td>\n",
       "      <td>0.898</td>\n",
       "      <td>3.857</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>60</td>\n",
       "      <td>0.971</td>\n",
       "      <td>0.821</td>\n",
       "      <td>0.813</td>\n",
       "      <td>3.857</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>80</td>\n",
       "      <td>0.980</td>\n",
       "      <td>0.785</td>\n",
       "      <td>0.806</td>\n",
       "      <td>5.736</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>100</td>\n",
       "      <td>0.989</td>\n",
       "      <td>0.642</td>\n",
       "      <td>0.769</td>\n",
       "      <td>8.532</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   noise_columns  train_r2  test_r2  ridge_test_r2  ridge_alpha\n",
       "0              0     0.947    0.946          0.946        0.010\n",
       "1             20     0.955    0.929          0.927        1.172\n",
       "2             40     0.960    0.910          0.898        3.857\n",
       "3             60     0.971    0.821          0.813        3.857\n",
       "4             80     0.980    0.785          0.806        5.736\n",
       "5            100     0.989    0.642          0.769        8.532"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rng = np.random.default_rng(7)\n",
    "noise = pd.DataFrame(rng.normal(size=(len(weekly), 100)),\n",
    "                     columns=[f\"noise_{i}\" for i in range(100)])\n",
    "folds = TimeSeriesSplit(n_splits=5)\n",
    "\n",
    "rows = []\n",
    "for k in [0, 20, 40, 60, 80, 100]:\n",
    "    Xk = pd.concat([weekly[features], noise.iloc[:, :k]], axis=1)\n",
    "    ols = LinearRegression().fit(Xk.iloc[:130], weekly[\"revenue\"].iloc[:130])\n",
    "    ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 30), cv=folds))\n",
    "    ridge.fit(Xk.iloc[:130], weekly[\"revenue\"].iloc[:130])\n",
    "    rows.append({\"noise_columns\": k,\n",
    "                 \"train_r2\": r2_score(weekly[\"revenue\"].iloc[:130], ols.predict(Xk.iloc[:130])),\n",
    "                 \"test_r2\": r2_score(weekly[\"revenue\"].iloc[130:], ols.predict(Xk.iloc[130:])),\n",
    "                 \"ridge_test_r2\": r2_score(weekly[\"revenue\"].iloc[130:], ridge.predict(Xk.iloc[130:])),\n",
    "                 \"ridge_alpha\": ridge[-1].alpha_})\n",
    "pd.DataFrame(rows).round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75f61505",
   "metadata": {},
   "source": [
    "## 11. Ridge and lasso"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "bc9d511d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.782243Z",
     "iopub.status.busy": "2026-12-05T03:22:41.782155Z",
     "iopub.status.idle": "2026-12-05T03:22:41.826373Z",
     "shell.execute_reply": "2026-12-05T03:22:41.825842Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ridge alpha   0.01: CV RMSE   6,416   coefficients per SD   4,618   2,989   1,596   3,030  19,982\n",
      "ridge alpha      1: CV RMSE   6,437   coefficients per SD   4,883   2,954   1,696   3,015  19,558\n",
      "ridge alpha     10: CV RMSE   7,312   coefficients per SD   6,385   2,661   2,355   2,858  16,803\n",
      "ridge alpha    100: CV RMSE  14,438   coefficients per SD   6,872   1,291   3,474   1,620   9,592\n",
      "lasso alpha 3000 keeps: ['paid_search_spend', 'search_interest_index']\n"
     ]
    }
   ],
   "source": [
    "Xtr, ytr = train[features], train[\"revenue\"]\n",
    "for alpha in [0.01, 1, 10, 100]:\n",
    "    ridge = make_pipeline(StandardScaler(), Ridge(alpha=alpha))\n",
    "    rmse = -cross_val_score(ridge, Xtr, ytr, cv=folds,\n",
    "                            scoring=\"neg_root_mean_squared_error\").mean()\n",
    "    coefs = ridge.fit(Xtr, ytr)[-1].coef_\n",
    "    print(f\"ridge alpha {alpha:>6}: CV RMSE {rmse:>7,.0f}   coefficients per SD \"\n",
    "          + \" \".join(f\"{c:>7,.0f}\" for c in coefs))\n",
    "lasso = make_pipeline(StandardScaler(), Lasso(alpha=3000)).fit(Xtr, ytr)\n",
    "print(\"lasso alpha 3000 keeps:\", [f for f, c in zip(features, lasso[-1].coef_) if c != 0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c3c2d07",
   "metadata": {},
   "source": [
    "## 12. Predictions, intervals and extrapolation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "de4e2ba9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.827405Z",
     "iopub.status.busy": "2026-12-05T03:22:41.827328Z",
     "iopub.status.idle": "2026-12-05T03:22:41.833467Z",
     "shell.execute_reply": "2026-12-05T03:22:41.833064Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mean</th>\n",
       "      <th>mean_ci_lower</th>\n",
       "      <th>mean_ci_upper</th>\n",
       "      <th>obs_ci_lower</th>\n",
       "      <th>obs_ci_upper</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>search 9,500</th>\n",
       "      <td>64919</td>\n",
       "      <td>63887</td>\n",
       "      <td>65950</td>\n",
       "      <td>53059</td>\n",
       "      <td>76778</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>search 15,000</th>\n",
       "      <td>74078</td>\n",
       "      <td>70535</td>\n",
       "      <td>77620</td>\n",
       "      <td>61743</td>\n",
       "      <td>86412</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>search 30,000</th>\n",
       "      <td>99057</td>\n",
       "      <td>86226</td>\n",
       "      <td>111888</td>\n",
       "      <td>81615</td>\n",
       "      <td>116499</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                mean  mean_ci_lower  mean_ci_upper  obs_ci_lower  obs_ci_upper\n",
       "search 9,500   64919          63887          65950         53059         76778\n",
       "search 15,000  74078          70535          77620         61743         86412\n",
       "search 30,000  99057          86226         111888         81615        116499"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "typical = weekly[features].mean().to_frame().T.assign(promotion_week=0)\n",
    "cases = pd.concat([typical.assign(paid_search_spend=s) for s in [9500, 15000, 30000]])\n",
    "pred = full.get_prediction(cases).summary_frame(alpha=0.05)\n",
    "pred.index = [\"search 9,500\", \"search 15,000\", \"search 30,000\"]\n",
    "pred[[\"mean\", \"mean_ci_lower\", \"mean_ci_upper\", \"obs_ci_lower\", \"obs_ci_upper\"]].round(0).astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a4d5d15f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.834604Z",
     "iopub.status.busy": "2026-12-05T03:22:41.834535Z",
     "iopub.status.idle": "2026-12-05T03:22:41.836456Z",
     "shell.execute_reply": "2026-12-05T03:22:41.836064Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "search spend in the data: 3,910 to 15,280\n"
     ]
    }
   ],
   "source": [
    "print(f\"search spend in the data: {weekly['paid_search_spend'].min():,} to \"\n",
    "      f\"{weekly['paid_search_spend'].max():,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da00862a",
   "metadata": {},
   "source": [
    "## 13. One week's prediction, taken apart"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "bb634882",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.837330Z",
     "iopub.status.busy": "2026-12-05T03:22:41.837267Z",
     "iopub.status.idle": "2026-12-05T03:22:41.842315Z",
     "shell.execute_reply": "2026-12-05T03:22:41.841932Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "week of 2025-06-16, actual revenue 120,220\n",
      "average week             66283.0\n",
      "paid_search_spend         6467.0\n",
      "paid_social_spend        -5013.0\n",
      "display_spend               21.0\n",
      "promotion_week            7170.0\n",
      "search_interest_index    34954.0\n",
      "prediction 109,882\n"
     ]
    }
   ],
   "source": [
    "average = weekly[features].mean()\n",
    "week = weekly.loc[weekly[\"revenue\"].idxmax()]\n",
    "parts = {\"average week\": full.predict(average.to_frame().T).iloc[0]}\n",
    "for f in features:\n",
    "    parts[f] = full.params[f] * (week[f] - average[f])\n",
    "parts = pd.Series(parts)\n",
    "print(f\"week of {week['week']:%Y-%m-%d}, actual revenue {week['revenue']:,}\")\n",
    "print(parts.round(0).to_string())\n",
    "print(f\"prediction {parts.sum():,.0f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bb0d9fb",
   "metadata": {},
   "source": [
    "## 14. Linear regression in a few lines of scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "538f7b1a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.843222Z",
     "iopub.status.busy": "2026-12-05T03:22:41.843155Z",
     "iopub.status.idle": "2026-12-05T03:22:41.846332Z",
     "shell.execute_reply": "2026-12-05T03:22:41.845957Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "paid_search_spend           1.76\n",
       "paid_social_spend           1.33\n",
       "display_spend               1.06\n",
       "promotion_week           8232.41\n",
       "search_interest_index    1441.07\n",
       "dtype: float64"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = LinearRegression()\n",
    "model.fit(train[features], train[\"revenue\"])\n",
    "\n",
    "pd.Series(model.coef_, index=features).round(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06d1296a",
   "metadata": {},
   "source": [
    "## Appendix: the numbers behind the charts\n",
    "\n",
    "Run these cells after the ones above; the last cell saves everything to `linear_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "f1a5cb2f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.847216Z",
     "iopub.status.busy": "2026-12-05T03:22:41.847151Z",
     "iopub.status.idle": "2026-12-05T03:22:41.858435Z",
     "shell.execute_reply": "2026-12-05T03:22:41.858021Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "156 weeks\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "charts = {}\n",
    "r0 = lambda v: int(round(float(v)))\n",
    "r3 = lambda v: round(float(v), 3)\n",
    "\n",
    "fit_naive = models[\"search only\"].fittedvalues\n",
    "charts[\"weeks\"] = [{\"w\": f\"{r.week:%Y-%m-%d}\", \"s\": r0(r.paid_search_spend), \"so\": r0(r.paid_social_spend),\n",
    "                    \"di\": r0(r.display_spend), \"p\": int(r.promotion_week), \"d\": round(float(r.search_interest_index), 1),\n",
    "                    \"r\": r0(r.revenue), \"fs\": r0(fit_naive.iloc[i]), \"fa\": r0(models[\"all spend\"].fittedvalues.iloc[i]),\n",
    "                    \"ff\": r0(full.fittedvalues.iloc[i])}\n",
    "                   for i, r in enumerate(weekly.itertuples())]\n",
    "truth = {\"Intercept\": None, \"paid_search_spend\": 2.2, \"paid_social_spend\": 1.4, \"display_spend\": 0.6,\n",
    "         \"promotion_week\": 9000, \"search_interest_index\": None}\n",
    "charts[\"models\"] = {name: {p: {\"coef\": r3(m.params[p]), \"lo\": r3(m.conf_int().loc[p, 0]), \"hi\": r3(m.conf_int().loc[p, 1]),\n",
    "                                \"se\": r3(m.bse[p])} for p in m.params.index}\n",
    "                    for name, m in models.items()}\n",
    "charts[\"models_r2\"] = {name: r3(m.rsquared) for name, m in models.items()}\n",
    "charts[\"truth\"] = truth\n",
    "charts[\"partial\"] = [{\"x\": r0(a), \"y\": r0(b)} for a, b in zip(r_search, r_rev)]\n",
    "charts[\"fwl_slope\"] = r3(fwl)\n",
    "charts[\"short_slope\"] = r3(short)\n",
    "print(len(charts[\"weeks\"]), \"weeks\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "aa2cdfb6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:41.859427Z",
     "iopub.status.busy": "2026-12-05T03:22:41.859359Z",
     "iopub.status.idle": "2026-12-05T03:22:46.418622Z",
     "shell.execute_reply": "2026-12-05T03:22:46.418152Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "26 weeks: SD 0.887\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "52 weeks: SD 0.628\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "104 weeks: SD 0.405\n"
     ]
    }
   ],
   "source": [
    "# bootstrap with fewer weeks: how the spread shrinks with more data\n",
    "rng = np.random.default_rng(11)\n",
    "spread = {}\n",
    "for n in [26, 52, 104]:\n",
    "    draws = []\n",
    "    while len(draws) < 600:\n",
    "        sample = weekly.iloc[rng.integers(0, len(weekly), n)]\n",
    "        if sample[\"promotion_week\"].nunique() < 2:   # no promotion week drawn: skip\n",
    "            continue\n",
    "        draws.append(smf.ols(formula, sample).fit().params[\"paid_search_spend\"])\n",
    "    spread[n] = {\"draws\": [round(float(v), 2) for v in draws], \"sd\": r3(np.std(draws, ddof=1))}\n",
    "    print(n, \"weeks: SD\", spread[n][\"sd\"])\n",
    "spread[156] = {\"draws\": [round(float(v), 2) for v in b], \"sd\": r3(b.std())}   # the 1,000 resamples from section 8\n",
    "charts[\"spread\"] = spread\n",
    "charts[\"boot_joint\"] = {\"s\": [round(float(v), 3) for v in boot[\"paid_search_spend\"]],\n",
    "                        \"d\": [round(float(v), 1) for v in boot[\"search_interest_index\"]],\n",
    "                        \"corr\": round(float(boot[\"paid_search_spend\"].corr(boot[\"search_interest_index\"])), 2),\n",
    "                        \"se_s\": r3(b.std())}\n",
    "charts[\"diag\"] = {name: {\"lag1\": round(float(models[name].resid.autocorr(1)), 2),\n",
    "                         \"dw\": round(float(durbin_watson(models[name].resid)), 2)}\n",
    "                  for name in [\"all spend\", \"all spend + demand\"]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "5ff4ed24",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:46.419828Z",
     "iopub.status.busy": "2026-12-05T03:22:46.419753Z",
     "iopub.status.idle": "2026-12-05T03:22:46.477027Z",
     "shell.execute_reply": "2026-12-05T03:22:46.476665Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>short</th>\n",
       "      <th>short_lo</th>\n",
       "      <th>short_hi</th>\n",
       "      <th>full</th>\n",
       "      <th>full_lo</th>\n",
       "      <th>full_hi</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>26</td>\n",
       "      <td>6.099</td>\n",
       "      <td>3.588</td>\n",
       "      <td>8.609</td>\n",
       "      <td>1.842</td>\n",
       "      <td>0.522</td>\n",
       "      <td>3.163</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>39</td>\n",
       "      <td>5.922</td>\n",
       "      <td>4.071</td>\n",
       "      <td>7.773</td>\n",
       "      <td>1.656</td>\n",
       "      <td>0.586</td>\n",
       "      <td>2.725</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>52</td>\n",
       "      <td>6.947</td>\n",
       "      <td>5.468</td>\n",
       "      <td>8.425</td>\n",
       "      <td>1.602</td>\n",
       "      <td>0.611</td>\n",
       "      <td>2.592</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>65</td>\n",
       "      <td>6.894</td>\n",
       "      <td>5.674</td>\n",
       "      <td>8.114</td>\n",
       "      <td>1.550</td>\n",
       "      <td>0.580</td>\n",
       "      <td>2.521</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>78</td>\n",
       "      <td>7.355</td>\n",
       "      <td>6.213</td>\n",
       "      <td>8.497</td>\n",
       "      <td>1.584</td>\n",
       "      <td>0.723</td>\n",
       "      <td>2.444</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>91</td>\n",
       "      <td>7.207</td>\n",
       "      <td>6.130</td>\n",
       "      <td>8.284</td>\n",
       "      <td>1.523</td>\n",
       "      <td>0.683</td>\n",
       "      <td>2.362</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>104</td>\n",
       "      <td>7.149</td>\n",
       "      <td>6.142</td>\n",
       "      <td>8.155</td>\n",
       "      <td>1.445</td>\n",
       "      <td>0.645</td>\n",
       "      <td>2.246</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>117</td>\n",
       "      <td>7.007</td>\n",
       "      <td>6.078</td>\n",
       "      <td>7.935</td>\n",
       "      <td>1.564</td>\n",
       "      <td>0.788</td>\n",
       "      <td>2.341</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>130</td>\n",
       "      <td>7.331</td>\n",
       "      <td>6.415</td>\n",
       "      <td>8.248</td>\n",
       "      <td>1.764</td>\n",
       "      <td>1.053</td>\n",
       "      <td>2.475</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>143</td>\n",
       "      <td>7.253</td>\n",
       "      <td>6.287</td>\n",
       "      <td>8.219</td>\n",
       "      <td>1.618</td>\n",
       "      <td>0.957</td>\n",
       "      <td>2.280</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>156</td>\n",
       "      <td>7.333</td>\n",
       "      <td>6.406</td>\n",
       "      <td>8.261</td>\n",
       "      <td>1.665</td>\n",
       "      <td>1.039</td>\n",
       "      <td>2.292</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      n  short  short_lo  short_hi   full  full_lo  full_hi\n",
       "0    26  6.099     3.588     8.609  1.842    0.522    3.163\n",
       "1    39  5.922     4.071     7.773  1.656    0.586    2.725\n",
       "2    52  6.947     5.468     8.425  1.602    0.611    2.592\n",
       "3    65  6.894     5.674     8.114  1.550    0.580    2.521\n",
       "4    78  7.355     6.213     8.497  1.584    0.723    2.444\n",
       "5    91  7.207     6.130     8.284  1.523    0.683    2.362\n",
       "6   104  7.149     6.142     8.155  1.445    0.645    2.246\n",
       "7   117  7.007     6.078     7.935  1.564    0.788    2.341\n",
       "8   130  7.331     6.415     8.248  1.764    1.053    2.475\n",
       "9   143  7.253     6.287     8.219  1.618    0.957    2.280\n",
       "10  156  7.333     6.406     8.261  1.665    1.039    2.292"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# the estimate as weeks accumulate, with and without demand\n",
    "growing = []\n",
    "for n in range(26, 157, 13):\n",
    "    part = weekly.iloc[:n]\n",
    "    a = smf.ols(f\"revenue ~ {spend}\", part).fit()\n",
    "    f = smf.ols(formula, part).fit()\n",
    "    growing.append({\"n\": n, \"short\": r3(a.params[\"paid_search_spend\"]),\n",
    "                    \"short_lo\": r3(a.conf_int().loc[\"paid_search_spend\", 0]), \"short_hi\": r3(a.conf_int().loc[\"paid_search_spend\", 1]),\n",
    "                    \"full\": r3(f.params[\"paid_search_spend\"]),\n",
    "                    \"full_lo\": r3(f.conf_int().loc[\"paid_search_spend\", 0]), \"full_hi\": r3(f.conf_int().loc[\"paid_search_spend\", 1])})\n",
    "charts[\"growing\"] = growing\n",
    "pd.DataFrame(growing)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "111627a9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:46.478211Z",
     "iopub.status.busy": "2026-12-05T03:22:46.478138Z",
     "iopub.status.idle": "2026-12-05T03:22:46.491468Z",
     "shell.execute_reply": "2026-12-05T03:22:46.490997Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "all spend: 23 of 26 test weeks inside the 95% prediction interval\n",
      "all spend + demand: 25 of 26 test weeks inside the 95% prediction interval\n"
     ]
    }
   ],
   "source": [
    "# train on 130 weeks, predict all 156 with 95% prediction intervals\n",
    "tests = {}\n",
    "for name, f in [(\"all spend\", f\"revenue ~ {spend}\"), (\"all spend + demand\", formula)]:\n",
    "    m = smf.ols(f, train).fit()\n",
    "    fr = m.get_prediction(weekly).summary_frame(alpha=0.05)\n",
    "    p_test = fr[\"mean\"].iloc[130:]\n",
    "    tests[name] = {\"pred\": [r0(v) for v in fr[\"mean\"]], \"lo\": [r0(v) for v in fr[\"obs_ci_lower\"]],\n",
    "                   \"hi\": [r0(v) for v in fr[\"obs_ci_upper\"]],\n",
    "                   \"rmse\": r0(mean_squared_error(test[\"revenue\"], p_test) ** 0.5),\n",
    "                   \"r2\": r3(r2_score(test[\"revenue\"], p_test)),\n",
    "                   \"covered\": int(((test[\"revenue\"] >= fr[\"obs_ci_lower\"].iloc[130:]) &\n",
    "                                   (test[\"revenue\"] <= fr[\"obs_ci_upper\"].iloc[130:])).sum())}\n",
    "    print(f\"{name}: {tests[name]['covered']} of 26 test weeks inside the 95% prediction interval\")\n",
    "charts[\"test\"] = tests\n",
    "charts[\"test_start\"] = 130"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "2d43165e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:46.492510Z",
     "iopub.status.busy": "2026-12-05T03:22:46.492432Z",
     "iopub.status.idle": "2026-12-05T03:22:46.894526Z",
     "shell.execute_reply": "2026-12-05T03:22:46.894071Z"
    }
   },
   "outputs": [],
   "source": [
    "charts[\"overfit\"] = [{k: (r3(v) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]\n",
    "\n",
    "# ridge and lasso paths on standardised training data\n",
    "alphas = np.logspace(-2, 4, 25)\n",
    "Xs = StandardScaler().fit_transform(Xtr)\n",
    "paths = {\"alpha\": [r3(a) for a in alphas], \"ridge\": [], \"ridge_cv\": [], \"lasso\": [], \"lasso_cv\": []}\n",
    "for a in alphas:\n",
    "    paths[\"ridge\"].append([r0(c) for c in Ridge(alpha=a).fit(Xs, ytr).coef_])\n",
    "    paths[\"ridge_cv\"].append(r0(-cross_val_score(make_pipeline(StandardScaler(), Ridge(alpha=a)), Xtr, ytr, cv=folds,\n",
    "                                                  scoring=\"neg_root_mean_squared_error\").mean()))\n",
    "    la = a * 30   # lasso's penalty works on a different scale\n",
    "    paths[\"lasso\"].append([r0(c) for c in Lasso(alpha=la, max_iter=50000).fit(Xs, ytr).coef_])\n",
    "    paths[\"lasso_cv\"].append(r0(-cross_val_score(make_pipeline(StandardScaler(), Lasso(alpha=la, max_iter=50000)), Xtr, ytr, cv=folds,\n",
    "                                                  scoring=\"neg_root_mean_squared_error\").mean()))\n",
    "paths[\"lasso_alpha\"] = [r3(a * 30) for a in alphas]\n",
    "paths[\"features\"] = features\n",
    "charts[\"paths\"] = paths"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "38d83aff",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:46.895785Z",
     "iopub.status.busy": "2026-12-05T03:22:46.895708Z",
     "iopub.status.idle": "2026-12-05T03:22:46.904664Z",
     "shell.execute_reply": "2026-12-05T03:22:46.904213Z"
    }
   },
   "outputs": [],
   "source": [
    "# extrapolation: predicted revenue against search spend, other inputs at their averages\n",
    "grid = np.arange(0, 40001, 1000)\n",
    "fr = full.get_prediction(pd.concat([typical.assign(paid_search_spend=s) for s in grid])).summary_frame(alpha=0.05)\n",
    "charts[\"extrap\"] = {\"s\": grid.tolist(), \"mean\": [r0(v) for v in fr[\"mean\"]], \"ci_lo\": [r0(v) for v in fr[\"mean_ci_lower\"]],\n",
    "                    \"ci_hi\": [r0(v) for v in fr[\"mean_ci_upper\"]], \"pi_lo\": [r0(v) for v in fr[\"obs_ci_lower\"]],\n",
    "                    \"pi_hi\": [r0(v) for v in fr[\"obs_ci_upper\"]],\n",
    "                    \"min\": r0(weekly[\"paid_search_spend\"].min()), \"max\": r0(weekly[\"paid_search_spend\"].max())}\n",
    "charts[\"typical\"] = {k: round(float(v), 1) for k, v in typical.iloc[0].items()}\n",
    "charts[\"average\"] = {k: float(v) for k, v in average.items()}\n",
    "charts[\"average_pred\"] = r0(full.predict(average.to_frame().T).iloc[0])\n",
    "charts[\"full_coef\"] = {k: float(v) for k, v in full.params.items()}\n",
    "charts[\"full_rmse\"] = r0(np.sqrt(full.mse_resid))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "3807e442",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:22:46.905645Z",
     "iopub.status.busy": "2026-12-05T03:22:46.905576Z",
     "iopub.status.idle": "2026-12-05T03:22:46.910942Z",
     "shell.execute_reply": "2026-12-05T03:22:46.910599Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved weeks, models, models_r2, truth, partial, fwl_slope, short_slope, spread, boot_joint, diag, growing, test, test_start, overfit, paths, extrap, typical, average, average_pred, full_coef, full_rmse\n"
     ]
    }
   ],
   "source": [
    "with open(\"linear_charts.json\", \"w\") as f:\n",
    "    json.dump(charts, f, default=lambda o: o.item() if hasattr(o, \"item\") else str(o))\n",
    "print(\"saved\", \", \".join(charts))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
