{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "41fd5e16",
   "metadata": {},
   "source": [
    "# KNN for marketing: matched control groups for an event\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-matched-control-groups\n",
    "\n",
    "Put `northpine_event.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_event.csv). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "29551830",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:49.394939Z",
     "iopub.status.busy": "2026-12-05T03:47:49.394706Z",
     "iopub.status.idle": "2026-12-05T03:47:50.227661Z",
     "shell.execute_reply": "2026-12-05T03:47:50.227141Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3000, 9)\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>account_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>web_visits_before</th>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <th>content_downloads_before</th>\n",
       "      <th>has_named_contact</th>\n",
       "      <th>attended_event</th>\n",
       "      <th>opportunity_90d</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NE-00001</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>50</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NE-00002</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>30</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NE-00003</td>\n",
       "      <td>Retail</td>\n",
       "      <td>33</td>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NE-00004</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>47</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NE-00005</td>\n",
       "      <td>Education</td>\n",
       "      <td>342</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  account_id               industry  employees  web_visits_before  \\\n",
       "0   NE-00001  Professional services         50                  6   \n",
       "1   NE-00002  Professional services         30                  1   \n",
       "2   NE-00003                 Retail         33                  6   \n",
       "3   NE-00004  Professional services         47                  0   \n",
       "4   NE-00005              Education        342                  5   \n",
       "\n",
       "   pricing_page_visits_before  content_downloads_before  has_named_contact  \\\n",
       "0                           0                         0                  1   \n",
       "1                           0                         0                  0   \n",
       "2                           1                         0                  1   \n",
       "3                           0                         0                  0   \n",
       "4                           0                         1                  0   \n",
       "\n",
       "   attended_event  opportunity_90d  \n",
       "0               0                0  \n",
       "1               0                0  \n",
       "2               0                1  \n",
       "3               0                0  \n",
       "4               0                0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.neighbors import NearestNeighbors\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "events = pd.read_csv(\"northpine_event.csv\")\n",
    "print(events.shape)\n",
    "events.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c9875fcb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.228753Z",
     "iopub.status.busy": "2026-12-05T03:47:50.228669Z",
     "iopub.status.idle": "2026-12-05T03:47:50.232240Z",
     "shell.execute_reply": "2026-12-05T03:47:50.231781Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                accounts   rate\n",
      "attended_event                 \n",
      "0                   2447  0.131\n",
      "1                    553  0.311\n",
      "naive gap: +18.0 percentage points\n"
     ]
    }
   ],
   "source": [
    "rates = events.groupby(\"attended_event\")[\"opportunity_90d\"].agg(accounts=\"count\", rate=\"mean\")\n",
    "naive_gap = rates.loc[1, \"rate\"] - rates.loc[0, \"rate\"]\n",
    "print(rates.round(3))\n",
    "print(f\"naive gap: {naive_gap * 100:+.1f} percentage points\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4b79d661",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.233148Z",
     "iopub.status.busy": "2026-12-05T03:47:50.233080Z",
     "iopub.status.idle": "2026-12-05T03:47:50.237074Z",
     "shell.execute_reply": "2026-12-05T03:47:50.236709Z"
    }
   },
   "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>attended_event</th>\n",
       "      <th>0</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>employees</th>\n",
       "      <td>118.0</td>\n",
       "      <td>271.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>web_visits_before</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>content_downloads_before</th>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>has_named_contact</th>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "attended_event                  0      1\n",
       "employees                   118.0  271.0\n",
       "web_visits_before             3.0    5.0\n",
       "pricing_page_visits_before    0.0    1.0\n",
       "content_downloads_before      0.0    1.0\n",
       "has_named_contact             0.0    1.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "before = [\"employees\", \"web_visits_before\", \"pricing_page_visits_before\",\n",
    "          \"content_downloads_before\", \"has_named_contact\"]\n",
    "events.groupby(\"attended_event\")[before].median().T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f1c83b2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.238248Z",
     "iopub.status.busy": "2026-12-05T03:47:50.238167Z",
     "iopub.status.idle": "2026-12-05T03:47:50.247722Z",
     "shell.execute_reply": "2026-12-05T03:47:50.247242Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "553 attendees, 2,447 possible controls, 11 columns\n"
     ]
    }
   ],
   "source": [
    "X = events[before].copy()\n",
    "X[\"employees\"] = np.log10(X[\"employees\"])\n",
    "X = X.join(pd.get_dummies(events[\"industry\"], prefix=\"ind\", dtype=float))\n",
    "Z = pd.DataFrame(StandardScaler().fit_transform(X), columns=X.columns, index=X.index)\n",
    "\n",
    "treated = events[\"attended_event\"] == 1\n",
    "y = events[\"opportunity_90d\"]\n",
    "print(f\"{treated.sum()} attendees, {(~treated).sum():,} possible controls, {X.shape[1]} columns\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "854b7bae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.248930Z",
     "iopub.status.busy": "2026-12-05T03:47:50.248834Z",
     "iopub.status.idle": "2026-12-05T03:47:50.254254Z",
     "shell.execute_reply": "2026-12-05T03:47:50.253758Z"
    }
   },
   "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>before</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>employees</th>\n",
       "      <td>0.75</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>web_visits_before</th>\n",
       "      <td>0.55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <td>0.47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>content_downloads_before</th>\n",
       "      <td>0.42</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>has_named_contact</th>\n",
       "      <td>0.65</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Education</th>\n",
       "      <td>-0.12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Healthcare</th>\n",
       "      <td>-0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Manufacturing</th>\n",
       "      <td>0.07</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Professional services</th>\n",
       "      <td>-0.02</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Retail</th>\n",
       "      <td>-0.01</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Software</th>\n",
       "      <td>0.06</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            before\n",
       "employees                     0.75\n",
       "web_visits_before             0.55\n",
       "pricing_page_visits_before    0.47\n",
       "content_downloads_before      0.42\n",
       "has_named_contact             0.65\n",
       "ind_Education                -0.12\n",
       "ind_Healthcare               -0.00\n",
       "ind_Manufacturing             0.07\n",
       "ind_Professional services    -0.02\n",
       "ind_Retail                   -0.01\n",
       "ind_Software                  0.06"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sd = np.sqrt((X[treated].var() + X[~treated].var()) / 2)\n",
    "\n",
    "def smd(controls):\n",
    "    \"\"\"Gap between attendees and a control group, in standard deviations.\"\"\"\n",
    "    return (X[treated].mean() - controls.mean()) / sd\n",
    "\n",
    "balance = pd.DataFrame({\"before\": smd(X[~treated])})\n",
    "balance.round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ca74e556",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.255278Z",
     "iopub.status.busy": "2026-12-05T03:47:50.255211Z",
     "iopub.status.idle": "2026-12-05T03:47:50.263488Z",
     "shell.execute_reply": "2026-12-05T03:47:50.263063Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "distinct controls used: 426 for 553 attendees\n",
      "matched gap: +8.1 percentage points\n"
     ]
    }
   ],
   "source": [
    "nn = NearestNeighbors(n_neighbors=1).fit(Z[~treated])\n",
    "distance, index = nn.kneighbors(Z[treated])\n",
    "\n",
    "control_ids = Z[~treated].index[index[:, 0]]\n",
    "matched_gap = y[treated].mean() - y[control_ids].mean()\n",
    "print(f\"distinct controls used: {len(set(control_ids))} for {treated.sum()} attendees\")\n",
    "print(f\"matched gap: {matched_gap * 100:+.1f} percentage points\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "079597b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.264500Z",
     "iopub.status.busy": "2026-12-05T03:47:50.264434Z",
     "iopub.status.idle": "2026-12-05T03:47:50.268792Z",
     "shell.execute_reply": "2026-12-05T03:47:50.268192Z"
    }
   },
   "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>before</th>\n",
       "      <th>after</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>employees</th>\n",
       "      <td>0.75</td>\n",
       "      <td>0.17</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>web_visits_before</th>\n",
       "      <td>0.55</td>\n",
       "      <td>0.15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <td>0.47</td>\n",
       "      <td>0.09</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>content_downloads_before</th>\n",
       "      <td>0.42</td>\n",
       "      <td>0.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>has_named_contact</th>\n",
       "      <td>0.65</td>\n",
       "      <td>0.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Education</th>\n",
       "      <td>-0.12</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Healthcare</th>\n",
       "      <td>-0.00</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Manufacturing</th>\n",
       "      <td>0.07</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Professional services</th>\n",
       "      <td>-0.02</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Retail</th>\n",
       "      <td>-0.01</td>\n",
       "      <td>-0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Software</th>\n",
       "      <td>0.06</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            before  after\n",
       "employees                     0.75   0.17\n",
       "web_visits_before             0.55   0.15\n",
       "pricing_page_visits_before    0.47   0.09\n",
       "content_downloads_before      0.42   0.06\n",
       "has_named_contact             0.65   0.03\n",
       "ind_Education                -0.12   0.00\n",
       "ind_Healthcare               -0.00   0.00\n",
       "ind_Manufacturing             0.07   0.00\n",
       "ind_Professional services    -0.02   0.00\n",
       "ind_Retail                   -0.01  -0.00\n",
       "ind_Software                  0.06   0.00"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "balance[\"after\"] = smd(X.loc[control_ids])\n",
    "balance.round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b2a07c70",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.270489Z",
     "iopub.status.busy": "2026-12-05T03:47:50.270368Z",
     "iopub.status.idle": "2026-12-05T03:47:50.328331Z",
     "shell.execute_reply": "2026-12-05T03:47:50.327718Z"
    }
   },
   "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>k</th>\n",
       "      <th>caliper</th>\n",
       "      <th>attendees_kept</th>\n",
       "      <th>gap</th>\n",
       "      <th>worst_smd</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.081</td>\n",
       "      <td>0.170</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.072</td>\n",
       "      <td>0.228</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.085</td>\n",
       "      <td>0.251</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>10</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.083</td>\n",
       "      <td>0.278</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>20</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.095</td>\n",
       "      <td>0.319</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>50</td>\n",
       "      <td>inf</td>\n",
       "      <td>553</td>\n",
       "      <td>0.111</td>\n",
       "      <td>0.393</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>5</td>\n",
       "      <td>1.0</td>\n",
       "      <td>391</td>\n",
       "      <td>0.044</td>\n",
       "      <td>0.156</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>5</td>\n",
       "      <td>0.5</td>\n",
       "      <td>278</td>\n",
       "      <td>0.008</td>\n",
       "      <td>0.036</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    k  caliper  attendees_kept    gap  worst_smd\n",
       "0   1      inf             553  0.081      0.170\n",
       "1   3      inf             553  0.072      0.228\n",
       "2   5      inf             553  0.085      0.251\n",
       "3  10      inf             553  0.083      0.278\n",
       "4  20      inf             553  0.095      0.319\n",
       "5  50      inf             553  0.111      0.393\n",
       "6   5      1.0             391  0.044      0.156\n",
       "7   5      0.5             278  0.008      0.036"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_controls = y[~treated].to_numpy()\n",
    "X_controls = X[~treated].to_numpy()\n",
    "\n",
    "def match(k, caliper=np.inf):\n",
    "    dist, idx = NearestNeighbors(n_neighbors=k).fit(Z[~treated]).kneighbors(Z[treated])\n",
    "    close = dist <= caliper                       # matches near enough to count\n",
    "    kept = close.any(axis=1)                      # attendees with at least one\n",
    "    w = close[kept] / close[kept].sum(axis=1, keepdims=True)\n",
    "    control_rate = (y_controls[idx[kept]] * w).sum(axis=1)\n",
    "    diffs = y[treated].to_numpy()[kept] - control_rate\n",
    "    control_means = (X_controls[idx[kept]] * w[:, :, None]).sum(axis=1).mean(axis=0)\n",
    "    worst = np.abs((X[treated][kept].mean() - control_means) / sd).max()\n",
    "    return {\"k\": k, \"caliper\": caliper, \"attendees_kept\": int(kept.sum()),\n",
    "            \"gap\": diffs.mean(), \"worst_smd\": worst, \"diffs\": diffs}\n",
    "\n",
    "settings = [match(k) for k in [1, 3, 5, 10, 20, 50]] + [match(5, c) for c in [1.0, 0.5]]\n",
    "pd.DataFrame(settings).drop(columns=\"diffs\").round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "97017012",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.329791Z",
     "iopub.status.busy": "2026-12-05T03:47:50.329683Z",
     "iopub.status.idle": "2026-12-05T03:47:50.339443Z",
     "shell.execute_reply": "2026-12-05T03:47:50.339026Z"
    }
   },
   "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>before</th>\n",
       "      <th>after</th>\n",
       "      <th>after_k5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>employees</th>\n",
       "      <td>0.75</td>\n",
       "      <td>0.17</td>\n",
       "      <td>0.25</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>web_visits_before</th>\n",
       "      <td>0.55</td>\n",
       "      <td>0.15</td>\n",
       "      <td>0.19</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <td>0.47</td>\n",
       "      <td>0.09</td>\n",
       "      <td>0.18</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>content_downloads_before</th>\n",
       "      <td>0.42</td>\n",
       "      <td>0.06</td>\n",
       "      <td>0.15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>has_named_contact</th>\n",
       "      <td>0.65</td>\n",
       "      <td>0.03</td>\n",
       "      <td>0.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Education</th>\n",
       "      <td>-0.12</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Healthcare</th>\n",
       "      <td>-0.00</td>\n",
       "      <td>0.00</td>\n",
       "      <td>-0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Manufacturing</th>\n",
       "      <td>0.07</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Professional services</th>\n",
       "      <td>-0.02</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Retail</th>\n",
       "      <td>-0.01</td>\n",
       "      <td>-0.00</td>\n",
       "      <td>-0.01</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ind_Software</th>\n",
       "      <td>0.06</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            before  after  after_k5\n",
       "employees                     0.75   0.17      0.25\n",
       "web_visits_before             0.55   0.15      0.19\n",
       "pricing_page_visits_before    0.47   0.09      0.18\n",
       "content_downloads_before      0.42   0.06      0.15\n",
       "has_named_contact             0.65   0.03      0.03\n",
       "ind_Education                -0.12   0.00      0.00\n",
       "ind_Healthcare               -0.00   0.00     -0.00\n",
       "ind_Manufacturing             0.07   0.00      0.00\n",
       "ind_Professional services    -0.02   0.00      0.00\n",
       "ind_Retail                   -0.01  -0.00     -0.01\n",
       "ind_Software                  0.06   0.00      0.00"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dist5, idx5 = NearestNeighbors(n_neighbors=5).fit(Z[~treated]).kneighbors(Z[treated])\n",
    "balance[\"after_k5\"] = smd(X[~treated].iloc[idx5.ravel()])\n",
    "balance.round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d9dee14c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.340625Z",
     "iopub.status.busy": "2026-12-05T03:47:50.340548Z",
     "iopub.status.idle": "2026-12-05T03:47:50.357946Z",
     "shell.execute_reply": "2026-12-05T03:47:50.357550Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matched gap (k=5): +8.5 points, 95% interval +4.6 to +12.4\n"
     ]
    }
   ],
   "source": [
    "best = match(5)\n",
    "rng = np.random.default_rng(42)\n",
    "n = len(best[\"diffs\"])\n",
    "boot = np.array([best[\"diffs\"][rng.integers(0, n, n)].mean() for _ in range(2000)])\n",
    "low, high = np.percentile(boot, [2.5, 97.5])\n",
    "print(f\"matched gap (k=5): {best['gap'] * 100:+.1f} points, \"\n",
    "      f\"95% interval {low * 100:+.1f} to {high * 100:+.1f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "43f7e3a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.359111Z",
     "iopub.status.busy": "2026-12-05T03:47:50.359027Z",
     "iopub.status.idle": "2026-12-05T03:47:50.363839Z",
     "shell.execute_reply": "2026-12-05T03:47:50.363490Z"
    }
   },
   "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>account_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>web_visits_before</th>\n",
       "      <th>pricing_page_visits_before</th>\n",
       "      <th>has_named_contact</th>\n",
       "      <th>attended_event</th>\n",
       "      <th>opportunity_90d</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>Software</td>\n",
       "      <td>90</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1013</th>\n",
       "      <td>NE-01014</td>\n",
       "      <td>Software</td>\n",
       "      <td>71</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1592</th>\n",
       "      <td>NE-01593</td>\n",
       "      <td>Software</td>\n",
       "      <td>64</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.31</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>234</th>\n",
       "      <td>NE-00235</td>\n",
       "      <td>Software</td>\n",
       "      <td>92</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0.34</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1654</th>\n",
       "      <td>NE-01655</td>\n",
       "      <td>Software</td>\n",
       "      <td>82</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.68</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>769</th>\n",
       "      <td>NE-00770</td>\n",
       "      <td>Software</td>\n",
       "      <td>99</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.68</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     account_id  industry  employees  web_visits_before  \\\n",
       "5      NE-00006  Software         90                  6   \n",
       "1013   NE-01014  Software         71                  6   \n",
       "1592   NE-01593  Software         64                  6   \n",
       "234    NE-00235  Software         92                  5   \n",
       "1654   NE-01655  Software         82                  4   \n",
       "769    NE-00770  Software         99                  4   \n",
       "\n",
       "      pricing_page_visits_before  has_named_contact  attended_event  \\\n",
       "5                              0                  1               1   \n",
       "1013                           0                  1               0   \n",
       "1592                           0                  1               0   \n",
       "234                            0                  1               0   \n",
       "1654                           0                  1               0   \n",
       "769                            0                  1               0   \n",
       "\n",
       "      opportunity_90d  distance  \n",
       "5                   0      0.00  \n",
       "1013                0      0.21  \n",
       "1592                0      0.31  \n",
       "234                 1      0.34  \n",
       "1654                0      0.68  \n",
       "769                 0      0.68  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "one = 0                                            # the first attendee in the file\n",
    "pair = pd.concat([events[treated].iloc[[one]],\n",
    "                  events[~treated].iloc[idx5[one]]])\n",
    "show = [\"account_id\", \"industry\", \"employees\", \"web_visits_before\",\n",
    "        \"pricing_page_visits_before\", \"has_named_contact\", \"attended_event\", \"opportunity_90d\"]\n",
    "pair[show].assign(distance=np.r_[0, dist5[one]].round(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "010e96a0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.364952Z",
     "iopub.status.busy": "2026-12-05T03:47:50.364886Z",
     "iopub.status.idle": "2026-12-05T03:47:50.371352Z",
     "shell.execute_reply": "2026-12-05T03:47:50.370993Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2765, 3)\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>attendee</th>\n",
       "      <th>control</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>NE-01014</td>\n",
       "      <td>0.213</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>NE-01593</td>\n",
       "      <td>0.306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>NE-00235</td>\n",
       "      <td>0.339</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>NE-01655</td>\n",
       "      <td>0.681</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NE-00006</td>\n",
       "      <td>NE-00770</td>\n",
       "      <td>0.682</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>NE-00011</td>\n",
       "      <td>NE-02455</td>\n",
       "      <td>0.011</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   attendee   control  distance\n",
       "0  NE-00006  NE-01014     0.213\n",
       "1  NE-00006  NE-01593     0.306\n",
       "2  NE-00006  NE-00235     0.339\n",
       "3  NE-00006  NE-01655     0.681\n",
       "4  NE-00006  NE-00770     0.682\n",
       "5  NE-00011  NE-02455     0.011"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pairs = pd.DataFrame({\n",
    "    \"attendee\": np.repeat(events.loc[treated, \"account_id\"].to_numpy(), 5),\n",
    "    \"control\": events.loc[~treated, \"account_id\"].to_numpy()[idx5.ravel()],\n",
    "    \"distance\": dist5.ravel().round(3),\n",
    "})\n",
    "pairs.to_csv(\"event_matched_controls.csv\", index=False)\n",
    "print(pairs.shape)\n",
    "pairs.head(6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7128154b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.372541Z",
     "iopub.status.busy": "2026-12-05T03:47:50.372459Z",
     "iopub.status.idle": "2026-12-05T03:47:50.380946Z",
     "shell.execute_reply": "2026-12-05T03:47:50.380565Z"
    }
   },
   "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>gap_in_points</th>\n",
       "      <th>extra_opportunities</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Naive: attendees vs everyone else</th>\n",
       "      <td>18.0</td>\n",
       "      <td>100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Rule: compare within size bands</th>\n",
       "      <td>16.2</td>\n",
       "      <td>89</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Regression adjustment</th>\n",
       "      <td>3.8</td>\n",
       "      <td>21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN matching, k=1</th>\n",
       "      <td>8.1</td>\n",
       "      <td>45</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN matching, k=5</th>\n",
       "      <td>8.5</td>\n",
       "      <td>47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN matching, k=5, bias-corrected</th>\n",
       "      <td>5.3</td>\n",
       "      <td>29</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   gap_in_points  extra_opportunities\n",
       "Naive: attendees vs everyone else           18.0                  100\n",
       "Rule: compare within size bands             16.2                   89\n",
       "Regression adjustment                        3.8                   21\n",
       "KNN matching, k=1                            8.1                   45\n",
       "KNN matching, k=5                            8.5                   47\n",
       "KNN matching, k=5, bias-corrected            5.3                   29"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "design = X.assign(attended=treated.astype(float))\n",
    "adjusted = LinearRegression().fit(design, y).coef_[-1]\n",
    "\n",
    "def strata_gap():\n",
    "    big = events[\"employees\"] >= 250\n",
    "    gaps = [y[treated & g].mean() - y[~treated & g].mean() for g in (big, ~big)]\n",
    "    weights = [(treated & big).sum(), (treated & ~big).sum()]\n",
    "    return np.average(gaps, weights=weights)\n",
    "\n",
    "# bias-corrected matching: subtract what a regression on the controls\n",
    "# expects for each account, so small leftover differences in the matches cancel\n",
    "mu0 = LinearRegression().fit(X[~treated], y[~treated])\n",
    "resid_controls = y_controls - mu0.predict(X[~treated])\n",
    "corrected = (y[treated] - mu0.predict(X[treated])).to_numpy() - resid_controls[idx5].mean(axis=1)\n",
    "\n",
    "estimates = pd.Series({\n",
    "    \"Naive: attendees vs everyone else\": naive_gap,\n",
    "    \"Rule: compare within size bands\": strata_gap(),\n",
    "    \"Regression adjustment\": adjusted,\n",
    "    \"KNN matching, k=1\": matched_gap,\n",
    "    \"KNN matching, k=5\": best[\"gap\"],\n",
    "    \"KNN matching, k=5, bias-corrected\": corrected.mean(),\n",
    "})\n",
    "pd.DataFrame({\"gap_in_points\": (estimates * 100).round(1),\n",
    "              \"extra_opportunities\": (estimates * treated.sum()).round(0).astype(int)})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4baa52f6",
   "metadata": {},
   "source": [
    "## Appendix: the numbers behind the charts\n",
    "\n",
    "The guide's interactive charts are drawn from the numbers computed below. Run these cells after the ones above; the last cell saves everything to `knn_match_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "da3310b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.381996Z",
     "iopub.status.busy": "2026-12-05T03:47:50.381929Z",
     "iopub.status.idle": "2026-12-05T03:47:50.462141Z",
     "shell.execute_reply": "2026-12-05T03:47:50.461720Z"
    }
   },
   "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>k</th>\n",
       "      <th>caliper</th>\n",
       "      <th>kept</th>\n",
       "      <th>gap</th>\n",
       "      <th>worst_smd</th>\n",
       "      <th>ci</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.0814</td>\n",
       "      <td>0.1705</td>\n",
       "      <td>[0.0344, 0.1284]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.0717</td>\n",
       "      <td>0.2284</td>\n",
       "      <td>[0.0313, 0.1115]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.0850</td>\n",
       "      <td>0.2506</td>\n",
       "      <td>[0.0456, 0.1244]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>10</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.0834</td>\n",
       "      <td>0.2781</td>\n",
       "      <td>[0.0456, 0.1212]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>20</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.0947</td>\n",
       "      <td>0.3195</td>\n",
       "      <td>[0.0575, 0.1321]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>50</td>\n",
       "      <td>NaN</td>\n",
       "      <td>553</td>\n",
       "      <td>0.1106</td>\n",
       "      <td>0.3932</td>\n",
       "      <td>[0.0745, 0.1481]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>5</td>\n",
       "      <td>1.0</td>\n",
       "      <td>391</td>\n",
       "      <td>0.0436</td>\n",
       "      <td>0.1558</td>\n",
       "      <td>[-0.0028, 0.0932]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>5</td>\n",
       "      <td>0.5</td>\n",
       "      <td>278</td>\n",
       "      <td>0.0077</td>\n",
       "      <td>0.0357</td>\n",
       "      <td>[-0.0498, 0.0636]</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    k  caliper  kept     gap  worst_smd                 ci\n",
       "0   1      NaN   553  0.0814     0.1705   [0.0344, 0.1284]\n",
       "1   3      NaN   553  0.0717     0.2284   [0.0313, 0.1115]\n",
       "2   5      NaN   553  0.0850     0.2506   [0.0456, 0.1244]\n",
       "3  10      NaN   553  0.0834     0.2781   [0.0456, 0.1212]\n",
       "4  20      NaN   553  0.0947     0.3195   [0.0575, 0.1321]\n",
       "5  50      NaN   553  0.1106     0.3932   [0.0745, 0.1481]\n",
       "6   5      1.0   391  0.0436     0.1558  [-0.0028, 0.0932]\n",
       "7   5      0.5   278  0.0077     0.0357  [-0.0498, 0.0636]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "def boot_ci(diffs, seed=42, reps=2000):\n",
    "    r = np.random.default_rng(seed)\n",
    "    m = len(diffs)\n",
    "    b = np.array([diffs[r.integers(0, m, m)].mean() for _ in range(reps)])\n",
    "    return [round(float(v), 4) for v in np.percentile(b, [2.5, 97.5])]\n",
    "\n",
    "charts = {\n",
    "    \"n_attendees\": int(treated.sum()), \"n_controls\": int((~treated).sum()),\n",
    "    \"rate_attended\": round(float(rates.loc[1, \"rate\"]), 4),\n",
    "    \"rate_not\": round(float(rates.loc[0, \"rate\"]), 4),\n",
    "    \"naive_gap\": round(float(naive_gap), 4),\n",
    "    \"matched_gap_k1\": round(float(matched_gap), 4),\n",
    "    \"matched_gap_k5\": round(float(best[\"gap\"]), 4),\n",
    "    \"ci_k5\": [round(float(low), 4), round(float(high), 4)],\n",
    "    \"true_effect\": 0.05,\n",
    "}\n",
    "# matching settings, each with its own bootstrap interval\n",
    "charts[\"settings\"] = [{\"k\": s[\"k\"], \"caliper\": None if np.isinf(s[\"caliper\"]) else s[\"caliper\"],\n",
    "                       \"kept\": s[\"attendees_kept\"], \"gap\": round(float(s[\"gap\"]), 4),\n",
    "                       \"worst_smd\": round(float(s[\"worst_smd\"]), 4), \"ci\": boot_ci(s[\"diffs\"])}\n",
    "                      for s in settings]\n",
    "pd.DataFrame(charts[\"settings\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e836c9ba",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.463471Z",
     "iopub.status.busy": "2026-12-05T03:47:50.463389Z",
     "iopub.status.idle": "2026-12-05T03:47:50.468165Z",
     "shell.execute_reply": "2026-12-05T03:47:50.467553Z"
    }
   },
   "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>col</th>\n",
       "      <th>before</th>\n",
       "      <th>k1</th>\n",
       "      <th>k5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>employees</td>\n",
       "      <td>0.7489</td>\n",
       "      <td>0.1705</td>\n",
       "      <td>0.2506</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>web_visits_before</td>\n",
       "      <td>0.5470</td>\n",
       "      <td>0.1467</td>\n",
       "      <td>0.1939</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>pricing_page_visits_before</td>\n",
       "      <td>0.4656</td>\n",
       "      <td>0.0897</td>\n",
       "      <td>0.1762</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>content_downloads_before</td>\n",
       "      <td>0.4239</td>\n",
       "      <td>0.0648</td>\n",
       "      <td>0.1475</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>has_named_contact</td>\n",
       "      <td>0.6490</td>\n",
       "      <td>0.0267</td>\n",
       "      <td>0.0259</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>ind_Education</td>\n",
       "      <td>-0.1189</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.0046</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>ind_Healthcare</td>\n",
       "      <td>-0.0041</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>-0.0043</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>ind_Manufacturing</td>\n",
       "      <td>0.0666</td>\n",
       "      <td>0.0049</td>\n",
       "      <td>0.0039</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>ind_Professional services</td>\n",
       "      <td>-0.0200</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.0009</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>ind_Retail</td>\n",
       "      <td>-0.0115</td>\n",
       "      <td>-0.0048</td>\n",
       "      <td>-0.0067</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>ind_Software</td>\n",
       "      <td>0.0637</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.0017</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                           col  before      k1      k5\n",
       "0                    employees  0.7489  0.1705  0.2506\n",
       "1            web_visits_before  0.5470  0.1467  0.1939\n",
       "2   pricing_page_visits_before  0.4656  0.0897  0.1762\n",
       "3     content_downloads_before  0.4239  0.0648  0.1475\n",
       "4            has_named_contact  0.6490  0.0267  0.0259\n",
       "5                ind_Education -0.1189  0.0000  0.0046\n",
       "6               ind_Healthcare -0.0041  0.0000 -0.0043\n",
       "7            ind_Manufacturing  0.0666  0.0049  0.0039\n",
       "8    ind_Professional services -0.0200  0.0000  0.0009\n",
       "9                   ind_Retail -0.0115 -0.0048 -0.0067\n",
       "10                ind_Software  0.0637  0.0000  0.0017"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# balance before and after matching, for k = 1 and k = 5 (steps 5, 7 and 8)\n",
    "charts[\"balance\"] = [{\"col\": c, \"before\": round(float(balance.loc[c, \"before\"]), 4),\n",
    "                      \"k1\": round(float(balance.loc[c, \"after\"]), 4),\n",
    "                      \"k5\": round(float(balance.loc[c, \"after_k5\"]), 4)}\n",
    "                     for c in X.columns]\n",
    "pd.DataFrame(charts[\"balance\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "78c4446b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.469930Z",
     "iopub.status.busy": "2026-12-05T03:47:50.469817Z",
     "iopub.status.idle": "2026-12-05T03:47:50.842310Z",
     "shell.execute_reply": "2026-12-05T03:47:50.841790Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "88 of 2,000 re-estimates at or below +5.0 points\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bias-corrected, in extra opportunities: 29, 95% interval 8 to 51\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>name</th>\n",
       "      <th>gap</th>\n",
       "      <th>ci</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Naive comparison</td>\n",
       "      <td>0.1803</td>\n",
       "      <td>[0.1402, 0.2227]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Within size bands</td>\n",
       "      <td>0.1618</td>\n",
       "      <td>None</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Regression adjustment</td>\n",
       "      <td>0.0381</td>\n",
       "      <td>[-0.0025, 0.0831]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>KNN matching, k=1</td>\n",
       "      <td>0.0814</td>\n",
       "      <td>[0.0344, 0.1284]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>KNN matching, k=5</td>\n",
       "      <td>0.0850</td>\n",
       "      <td>[0.0456, 0.1244]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>KNN matching, bias-corrected</td>\n",
       "      <td>0.0531</td>\n",
       "      <td>[0.0139, 0.0926]</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                           name     gap                 ci\n",
       "0              Naive comparison  0.1803   [0.1402, 0.2227]\n",
       "1             Within size bands  0.1618               None\n",
       "2         Regression adjustment  0.0381  [-0.0025, 0.0831]\n",
       "3             KNN matching, k=1  0.0814   [0.0344, 0.1284]\n",
       "4             KNN matching, k=5  0.0850   [0.0456, 0.1244]\n",
       "5  KNN matching, bias-corrected  0.0531   [0.0139, 0.0926]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# the bootstrap distribution of the k=5 estimate, as a histogram\n",
    "edges = np.round(np.arange(0.0, 0.2001, 0.005), 3)\n",
    "counts, _ = np.histogram(boot, bins=edges)\n",
    "charts[\"boot\"] = {\"edges\": edges.tolist(), \"counts\": counts.tolist(), \"reps\": len(boot),\n",
    "                  \"below_true\": int((boot <= 0.05).sum())}\n",
    "print(f\"{charts['boot']['below_true']} of {len(boot):,} re-estimates at or below +5.0 points\")\n",
    "\n",
    "# every method from step 12, with a bootstrap interval (resampling accounts)\n",
    "def method_cis(reps=500, seed=7):\n",
    "    r = np.random.default_rng(seed)\n",
    "    out = {\"naive\": [], \"adjusted\": []}\n",
    "    for _ in range(reps):\n",
    "        s = r.integers(0, len(events), len(events))\n",
    "        ys, ts, Xs = y.to_numpy()[s], treated.to_numpy()[s], X.to_numpy()[s]\n",
    "        out[\"naive\"].append(ys[ts].mean() - ys[~ts].mean())\n",
    "        out[\"adjusted\"].append(LinearRegression().fit(np.c_[Xs, ts], ys).coef_[-1])\n",
    "    return {k: [round(float(v), 4) for v in np.percentile(v_, [2.5, 97.5])] for k, v_ in out.items()}\n",
    "\n",
    "cis = method_cis()\n",
    "charts[\"methods\"] = [\n",
    "    {\"name\": \"Naive comparison\", \"gap\": round(float(naive_gap), 4), \"ci\": cis[\"naive\"]},\n",
    "    {\"name\": \"Within size bands\", \"gap\": round(float(strata_gap()), 4), \"ci\": None},\n",
    "    {\"name\": \"Regression adjustment\", \"gap\": round(float(adjusted), 4), \"ci\": cis[\"adjusted\"]},\n",
    "    {\"name\": \"KNN matching, k=1\", \"gap\": round(float(matched_gap), 4), \"ci\": boot_ci(y[treated].to_numpy() - y[control_ids].to_numpy())},\n",
    "    {\"name\": \"KNN matching, k=5\", \"gap\": round(float(best[\"gap\"]), 4), \"ci\": [round(float(low), 4), round(float(high), 4)]},\n",
    "    {\"name\": \"KNN matching, bias-corrected\", \"gap\": round(float(corrected.mean()), 4), \"ci\": boot_ci(corrected)},\n",
    "]\n",
    "bc_ci = charts[\"methods\"][-1][\"ci\"]\n",
    "print(f\"bias-corrected, in extra opportunities: {corrected.mean() * treated.sum():.0f}, \"\n",
    "      f\"95% interval {bc_ci[0] * treated.sum():.0f} to {bc_ci[1] * treated.sum():.0f}\")\n",
    "pd.DataFrame(charts[\"methods\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e452df0d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.843389Z",
     "iopub.status.busy": "2026-12-05T03:47:50.843298Z",
     "iopub.status.idle": "2026-12-05T03:47:50.854789Z",
     "shell.execute_reply": "2026-12-05T03:47:50.854250Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "475 points, 40 attendees\n"
     ]
    }
   ],
   "source": [
    "# playground: a sample of attendees with their real matches (found on all columns),\n",
    "# drawn on two of them: company size and pre-event engagement\n",
    "engagement = (events[\"web_visits_before\"] + events[\"pricing_page_visits_before\"]\n",
    "              + events[\"content_downloads_before\"])\n",
    "pick = np.random.default_rng(3).choice(treated.sum(), 40, replace=False)\n",
    "att_rows = events.index[treated][pick]\n",
    "ctrl_pos = idx5[pick]                                  # positions among non-attendees\n",
    "ctrl_rows = events.index[~treated][np.unique(ctrl_pos)]\n",
    "bg_rows = events.index[~treated][np.random.default_rng(4).choice((~treated).sum(), 260, replace=False)]\n",
    "rows = pd.Index(att_rows).union(ctrl_rows).union(bg_rows)\n",
    "\n",
    "def point(i):\n",
    "    return {\"id\": events.at[i, \"account_id\"], \"e\": int(events.at[i, \"employees\"]), \"g\": int(engagement[i]),\n",
    "            \"t\": int(treated[i]), \"y\": int(y[i]), \"c\": int(events.at[i, \"has_named_contact\"])}\n",
    "\n",
    "charts[\"playground\"] = {\n",
    "    \"points\": [point(i) for i in rows],\n",
    "    \"pairs\": [{\"a\": events.at[a, \"account_id\"],\n",
    "               \"m\": [events.at[events.index[~treated][p], \"account_id\"] for p in ps]}\n",
    "              for a, ps in zip(att_rows, ctrl_pos)],\n",
    "}\n",
    "print(len(charts[\"playground\"][\"points\"]), \"points,\", len(charts[\"playground\"][\"pairs\"]), \"attendees\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "87a0fdf7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:47:50.856152Z",
     "iopub.status.busy": "2026-12-05T03:47:50.856064Z",
     "iopub.status.idle": "2026-12-05T03:47:50.869013Z",
     "shell.execute_reply": "2026-12-05T03:47:50.868408Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 15 chart datasets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/private/tmp/claude-501/s/450039274331/scratchpad/ml/.venv/lib/python3.12/site-packages/numpy/_core/fromnumeric.py:54: FutureWarning: Downcasting behavior in Series and DataFrame methods 'where', 'mask', and 'clip' is deprecated. In a future version this will not infer object dtypes or cast all-round floats to integers. Instead call result.infer_objects(copy=False) for object inference, or cast round floats explicitly. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n",
      "  return bound(*args, **kwds)\n"
     ]
    }
   ],
   "source": [
    "# distributions of each column: attendees, all non-attendees, and matched controls (k=5)\n",
    "matched5 = events[~treated].iloc[idx5.ravel()]\n",
    "dists = {}\n",
    "for col, bins in [(\"employees\", np.round(np.logspace(np.log10(5), np.log10(5000), 16), 1)),\n",
    "                  (\"web_visits_before\", np.arange(-0.5, 21.5, 2)),\n",
    "                  (\"pricing_page_visits_before\", np.arange(-0.5, 9.5, 1)),\n",
    "                  (\"content_downloads_before\", np.arange(-0.5, 8.5, 1))]:\n",
    "    share = lambda v: (np.histogram(np.clip(v, bins[0], bins[-1] - 1e-9), bins=bins)[0] / len(v)).round(4).tolist()\n",
    "    dists[col] = {\"edges\": [float(b) for b in bins],\n",
    "                  \"attended\": share(events.loc[treated, col]),\n",
    "                  \"everyone\": share(events.loc[~treated, col]),\n",
    "                  \"matched\": share(matched5[col])}\n",
    "charts[\"distributions\"] = dists\n",
    "with open(\"knn_match_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\", len(charts), \"chart datasets\")"
   ]
  }
 ],
 "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
}
