{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "60321c7d",
   "metadata": {},
   "source": [
    "# Who is going to miss their appointment?\n",
    "\n",
    "No-show risk model for an outpatient clinic in Colombia. A [Telar](https://telar.site) case study: the clinic and the data are synthetic; the method is the one we would use with real data.\n",
    "\n",
    "**Business question.** About one in five appointments goes empty because the patient neither shows up nor cancels. The front desk can call around 30 patients a day to confirm. Which ones should they call?\n",
    "\n",
    "**Design decisions.**\n",
    "- Time-based split: we train on appointments up to May 2026 and evaluate on June onward, the way the model would be used in practice.\n",
    "- We compare a logistic regression, which can be explained factor by factor, with a *gradient boosting* model.\n",
    "- We check calibration (that a 30% risk really means 30%) and behavior across insurance plans (Colombia's contributory, subsidized and private-pay patients).\n",
    "\n",
    "Column names in the dataset are in Spanish: `fecha` date, `hora` hour, `especialidad` specialty, `edad` age, `regimen` insurance plan, `dias_anticipacion` days booked in advance, `inasistencias_previas` previous no-shows, `confirmo_whatsapp` confirmed on WhatsApp, `primera_vez` first visit, `distancia_km` distance, `lluvia` rain, `no_asistio` missed (target)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b8e1aace",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:42.810872Z",
     "iopub.status.busy": "2026-10-30T02:21:42.810726Z",
     "iopub.status.idle": "2026-10-30T02:21:44.385467Z",
     "shell.execute_reply": "2026-10-30T02:21:44.384446Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20,503 appointments between 2025-03-01 and 2026-10-21\n",
      "No-show rate: 20.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>fecha</th>\n",
       "      <th>dia_semana</th>\n",
       "      <th>hora</th>\n",
       "      <th>especialidad</th>\n",
       "      <th>edad</th>\n",
       "      <th>sexo</th>\n",
       "      <th>regimen</th>\n",
       "      <th>dias_anticipacion</th>\n",
       "      <th>primera_vez</th>\n",
       "      <th>inasistencias_previas</th>\n",
       "      <th>confirmo_whatsapp</th>\n",
       "      <th>distancia_km</th>\n",
       "      <th>lluvia</th>\n",
       "      <th>no_asistio</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>17</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>63</td>\n",
       "      <td>F</td>\n",
       "      <td>Contributivo</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>6.4</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>8</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>44</td>\n",
       "      <td>F</td>\n",
       "      <td>Contributivo</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>6.8</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>13</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>75</td>\n",
       "      <td>F</td>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>17</td>\n",
       "      <td>Ginecología</td>\n",
       "      <td>53</td>\n",
       "      <td>F</td>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>16.3</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>9</td>\n",
       "      <td>Nutrición</td>\n",
       "      <td>65</td>\n",
       "      <td>F</td>\n",
       "      <td>Particular</td>\n",
       "      <td>11</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>3.7</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       fecha  dia_semana  hora      especialidad  edad sexo       regimen  \\\n",
       "0 2025-03-01           5    17  Medicina general    63    F  Contributivo   \n",
       "1 2025-03-01           5     8  Medicina general    44    F  Contributivo   \n",
       "2 2025-03-01           5    13  Medicina general    75    F    Subsidiado   \n",
       "3 2025-03-01           5    17       Ginecología    53    F    Subsidiado   \n",
       "4 2025-03-01           5     9         Nutrición    65    F    Particular   \n",
       "\n",
       "   dias_anticipacion  primera_vez  inasistencias_previas  confirmo_whatsapp  \\\n",
       "0                  4            0                      1                  0   \n",
       "1                  6            0                      0                  0   \n",
       "2                  3            0                      1                  1   \n",
       "3                  5            0                      0                  0   \n",
       "4                 11            0                      0                  0   \n",
       "\n",
       "   distancia_km  lluvia  no_asistio  \n",
       "0           6.4       0           0  \n",
       "1           6.8       0           0  \n",
       "2           4.1       0           0  \n",
       "3          16.3       0           1  \n",
       "4           3.7       0           0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import HistGradientBoostingClassifier\n",
    "from sklearn.metrics import roc_auc_score, brier_score_loss, average_precision_score\n",
    "\n",
    "df = pd.read_csv('citas_historico.csv', parse_dates=['fecha'])\n",
    "print(f'{len(df):,} appointments between {df.fecha.min():%Y-%m-%d} and {df.fecha.max():%Y-%m-%d}')\n",
    "print(f'No-show rate: {df.no_asistio.mean():.1%}')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8b8cc7e",
   "metadata": {},
   "source": [
    "## Features\n",
    "\n",
    "We turn each appointment into features the front desk knows the day before. Age, hour and weekday are grouped into bands because their effect is not linear: very young patients and the first slot of the morning miss more often."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "991ca447",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.387854Z",
     "iopub.status.busy": "2026-10-30T02:21:44.387678Z",
     "iopub.status.idle": "2026-10-30T02:21:44.426413Z",
     "shell.execute_reply": "2026-10-30T02:21:44.425222Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training: 15,678 appointments · Test: 4,825 appointments\n"
     ]
    }
   ],
   "source": [
    "def variables(d: pd.DataFrame) -> pd.DataFrame:\n",
    "    X = pd.DataFrame(index=d.index)\n",
    "    X['dias_anticipacion'] = d.dias_anticipacion\n",
    "    X['inasistencias_previas'] = d.inasistencias_previas.clip(upper=4)\n",
    "    X['falto_antes'] = (d.inasistencias_previas >= 1).astype(int)\n",
    "    X['confirmo_whatsapp'] = d.confirmo_whatsapp\n",
    "    X['primera_vez'] = d.primera_vez\n",
    "    X['distancia_km'] = d.distancia_km\n",
    "    X['lluvia'] = d.lluvia\n",
    "    X['hora_7am'] = (d.hora <= 7).astype(int)\n",
    "    X['hora_tarde'] = (d.hora >= 16).astype(int)\n",
    "    X['lunes'] = (d.dia_semana == 0).astype(int)\n",
    "    X['sabado'] = (d.dia_semana == 5).astype(int)\n",
    "    X['edad_menor_25'] = (d.edad < 25).astype(int)\n",
    "    X['edad_65_mas'] = (d.edad >= 65).astype(int)\n",
    "    X['hombre'] = (d.sexo == 'M').astype(int)\n",
    "    for e in ['Odontología', 'Psicología', 'Pediatría', 'Ginecología', 'Nutrición', 'Fisioterapia']:\n",
    "        X['esp_' + e] = (d.especialidad == e).astype(int)\n",
    "    X['reg_Subsidiado'] = (d.regimen == 'Subsidiado').astype(int)\n",
    "    X['reg_Particular'] = (d.regimen == 'Particular').astype(int)\n",
    "    return X\n",
    "\n",
    "corte = pd.Timestamp('2026-06-01')\n",
    "tr, te = df[df.fecha < corte], df[df.fecha >= corte]\n",
    "Xtr, Xte, ytr, yte = variables(tr), variables(te), tr.no_asistio, te.no_asistio\n",
    "print(f'Training: {len(tr):,} appointments · Test: {len(te):,} appointments')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba541c2d",
   "metadata": {},
   "source": [
    "## Two models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5187ddf2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.428376Z",
     "iopub.status.busy": "2026-10-30T02:21:44.428162Z",
     "iopub.status.idle": "2026-10-30T02:21:44.852021Z",
     "shell.execute_reply": "2026-10-30T02:21:44.850475Z"
    }
   },
   "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>auc</th>\n",
       "      <th>ap</th>\n",
       "      <th>brier</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Logistic regression</th>\n",
       "      <td>0.715</td>\n",
       "      <td>0.416</td>\n",
       "      <td>0.149</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gradient boosting</th>\n",
       "      <td>0.704</td>\n",
       "      <td>0.396</td>\n",
       "      <td>0.151</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       auc     ap  brier\n",
       "Logistic regression  0.715  0.416  0.149\n",
       "Gradient boosting    0.704  0.396  0.151"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lr = LogisticRegression(C=1.0, max_iter=2000).fit(Xtr, ytr)\n",
    "gb_cols = ['dias_anticipacion', 'inasistencias_previas', 'confirmo_whatsapp', 'primera_vez', 'distancia_km', 'lluvia']\n",
    "Gtr = tr[gb_cols + ['hora', 'dia_semana', 'edad']].assign(sexo=(tr.sexo == 'M').astype(int), esp=tr.especialidad.astype('category').cat.codes, reg=tr.regimen.astype('category').cat.codes)\n",
    "Gte = te[gb_cols + ['hora', 'dia_semana', 'edad']].assign(sexo=(te.sexo == 'M').astype(int), esp=te.especialidad.astype('category').cat.codes, reg=te.regimen.astype('category').cat.codes)\n",
    "gb = HistGradientBoostingClassifier(max_iter=300, learning_rate=.05, max_leaf_nodes=15, categorical_features=[Gtr.columns.get_loc('esp'), Gtr.columns.get_loc('reg')], random_state=0).fit(Gtr, ytr)\n",
    "\n",
    "p_lr, p_gb = lr.predict_proba(Xte)[:, 1], gb.predict_proba(Gte)[:, 1]\n",
    "metricas = {}\n",
    "for nombre, p in [('Regresión logística', p_lr), ('Gradient boosting', p_gb)]:\n",
    "    metricas[nombre] = dict(auc=roc_auc_score(yte, p), ap=average_precision_score(yte, p), brier=brier_score_loss(yte, p))\n",
    "pd.DataFrame(metricas).T.round(3).rename(index={'Regresión logística': 'Logistic regression'})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b44ba44",
   "metadata": {},
   "source": [
    "Both models discriminate almost equally well. We keep the logistic regression: the difference is tiny, and in exchange we can tell the receptionist why an appointment was flagged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9573d501",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.854735Z",
     "iopub.status.busy": "2026-10-30T02:21:44.854484Z",
     "iopub.status.idle": "2026-10-30T02:21:44.878824Z",
     "shell.execute_reply": "2026-10-30T02:21:44.875442Z"
    }
   },
   "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>predicho</th>\n",
       "      <th>observado</th>\n",
       "      <th>n</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>decil</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.060</td>\n",
       "      <td>0.066</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.082</td>\n",
       "      <td>0.077</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.104</td>\n",
       "      <td>0.133</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.128</td>\n",
       "      <td>0.114</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.155</td>\n",
       "      <td>0.153</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.185</td>\n",
       "      <td>0.203</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.220</td>\n",
       "      <td>0.228</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.267</td>\n",
       "      <td>0.280</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.338</td>\n",
       "      <td>0.349</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.486</td>\n",
       "      <td>0.511</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       predicho  observado    n\n",
       "decil                          \n",
       "0         0.060      0.066  483\n",
       "1         0.082      0.077  482\n",
       "2         0.104      0.133  483\n",
       "3         0.128      0.114  482\n",
       "4         0.155      0.153  483\n",
       "5         0.185      0.203  482\n",
       "6         0.220      0.228  482\n",
       "7         0.267      0.280  483\n",
       "8         0.338      0.349  482\n",
       "9         0.486      0.511  483"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "calib = (pd.DataFrame({'p': p_lr, 'y': yte.values}).assign(decil=lambda d: pd.qcut(d.p, 10, labels=False))\n",
    "         .groupby('decil').agg(predicho=('p', 'mean'), observado=('y', 'mean'), n=('y', 'size')))\n",
    "calib.round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63928a98",
   "metadata": {},
   "source": [
    "## How many calls, and how many appointments saved?\n",
    "\n",
    "For each risk threshold we compute the share of appointments that would be flagged for a call (`marcadas`), the share of those that really were going to miss (precision) and the share of all no-shows that get covered (`sensibilidad`, recall)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e9d44979",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.880647Z",
     "iopub.status.busy": "2026-10-30T02:21:44.880432Z",
     "iopub.status.idle": "2026-10-30T02:21:44.905831Z",
     "shell.execute_reply": "2026-10-30T02:21:44.904743Z"
    }
   },
   "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>umbral</th>\n",
       "      <th>marcadas</th>\n",
       "      <th>precision</th>\n",
       "      <th>sensibilidad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.10</td>\n",
       "      <td>0.766</td>\n",
       "      <td>0.252</td>\n",
       "      <td>0.913</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.15</td>\n",
       "      <td>0.566</td>\n",
       "      <td>0.295</td>\n",
       "      <td>0.790</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>0.20</td>\n",
       "      <td>0.403</td>\n",
       "      <td>0.340</td>\n",
       "      <td>0.648</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>0.25</td>\n",
       "      <td>0.279</td>\n",
       "      <td>0.383</td>\n",
       "      <td>0.505</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>0.30</td>\n",
       "      <td>0.201</td>\n",
       "      <td>0.428</td>\n",
       "      <td>0.407</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>0.35</td>\n",
       "      <td>0.131</td>\n",
       "      <td>0.493</td>\n",
       "      <td>0.306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>0.40</td>\n",
       "      <td>0.087</td>\n",
       "      <td>0.530</td>\n",
       "      <td>0.219</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>0.45</td>\n",
       "      <td>0.058</td>\n",
       "      <td>0.553</td>\n",
       "      <td>0.153</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>0.50</td>\n",
       "      <td>0.034</td>\n",
       "      <td>0.640</td>\n",
       "      <td>0.103</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>45</th>\n",
       "      <td>0.55</td>\n",
       "      <td>0.020</td>\n",
       "      <td>0.602</td>\n",
       "      <td>0.058</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>0.60</td>\n",
       "      <td>0.012</td>\n",
       "      <td>0.667</td>\n",
       "      <td>0.037</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>55</th>\n",
       "      <td>0.65</td>\n",
       "      <td>0.005</td>\n",
       "      <td>0.731</td>\n",
       "      <td>0.019</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    umbral  marcadas  precision  sensibilidad\n",
       "0     0.10     0.766      0.252         0.913\n",
       "5     0.15     0.566      0.295         0.790\n",
       "10    0.20     0.403      0.340         0.648\n",
       "15    0.25     0.279      0.383         0.505\n",
       "20    0.30     0.201      0.428         0.407\n",
       "25    0.35     0.131      0.493         0.306\n",
       "30    0.40     0.087      0.530         0.219\n",
       "35    0.45     0.058      0.553         0.153\n",
       "40    0.50     0.034      0.640         0.103\n",
       "45    0.55     0.020      0.602         0.058\n",
       "50    0.60     0.012      0.667         0.037\n",
       "55    0.65     0.005      0.731         0.019"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "umbrales = []\n",
    "for u in np.round(np.arange(.10, .66, .01), 2):\n",
    "    m = p_lr >= u\n",
    "    umbrales.append(dict(umbral=float(u), marcadas=float(m.mean()), precision=float(yte[m].mean()) if m.any() else 0.0,\n",
    "                         sensibilidad=float((m & (yte == 1)).sum() / (yte == 1).sum())))\n",
    "pd.DataFrame(umbrales).iloc[::5].round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44b8a21e",
   "metadata": {},
   "source": [
    "## Fairness across insurance plans\n",
    "\n",
    "Patients on the subsidized plan miss more often in the data, and the model uses the plan as a feature. We check that this does not lead to over-flagging those patients relative to their actual risk. A phone call is not a penalty, but if the clinic used the model to overbook, this would need close watching."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0cc437ee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.907569Z",
     "iopub.status.busy": "2026-10-30T02:21:44.907376Z",
     "iopub.status.idle": "2026-10-30T02:21:44.918826Z",
     "shell.execute_reply": "2026-10-30T02:21:44.917413Z"
    }
   },
   "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>regimen</th>\n",
       "      <th>citas</th>\n",
       "      <th>tasa_real</th>\n",
       "      <th>riesgo_promedio</th>\n",
       "      <th>marcadas</th>\n",
       "      <th>precision</th>\n",
       "      <th>sensibilidad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Contributivo</td>\n",
       "      <td>2651</td>\n",
       "      <td>0.197</td>\n",
       "      <td>0.191</td>\n",
       "      <td>0.107</td>\n",
       "      <td>0.458</td>\n",
       "      <td>0.249</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>1599</td>\n",
       "      <td>0.247</td>\n",
       "      <td>0.238</td>\n",
       "      <td>0.197</td>\n",
       "      <td>0.530</td>\n",
       "      <td>0.423</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Particular</td>\n",
       "      <td>575</td>\n",
       "      <td>0.177</td>\n",
       "      <td>0.157</td>\n",
       "      <td>0.059</td>\n",
       "      <td>0.441</td>\n",
       "      <td>0.147</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        regimen  citas  tasa_real  riesgo_promedio  marcadas  precision  \\\n",
       "0  Contributivo   2651      0.197            0.191     0.107      0.458   \n",
       "1    Subsidiado   1599      0.247            0.238     0.197      0.530   \n",
       "2    Particular    575      0.177            0.157     0.059      0.441   \n",
       "\n",
       "   sensibilidad  \n",
       "0         0.249  \n",
       "1         0.423  \n",
       "2         0.147  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "U = .35\n",
    "equidad = []\n",
    "for r in ['Contributivo', 'Subsidiado', 'Particular']:\n",
    "    s = (te.regimen == r).values\n",
    "    m = p_lr[s] >= U; y = yte.values[s]\n",
    "    equidad.append(dict(regimen=r, citas=int(s.sum()), tasa_real=float(y.mean()), riesgo_promedio=float(p_lr[s].mean()),\n",
    "                        marcadas=float(m.mean()), precision=float(y[m].mean()), sensibilidad=float((m & (y == 1)).sum() / (y == 1).sum())))\n",
    "pd.DataFrame(equidad).round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb294a74",
   "metadata": {},
   "source": [
    "## Export the model\n",
    "\n",
    "We save the coefficients so the front-desk tool can score risk in the browser, without sending patient data to any server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0fac07f9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T02:21:44.920628Z",
     "iopub.status.busy": "2026-10-30T02:21:44.920416Z",
     "iopub.status.idle": "2026-10-30T02:21:44.933443Z",
     "shell.execute_reply": "2026-10-30T02:21:44.932458Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "confirmo_whatsapp        0.38\n",
       "edad_65_mas              0.71\n",
       "esp_Pediatría            0.73\n",
       "reg_Particular           0.73\n",
       "esp_Ginecología          1.00\n",
       "dias_anticipacion        1.03\n",
       "hombre                   1.03\n",
       "distancia_km             1.04\n",
       "esp_Fisioterapia         1.08\n",
       "reg_Subsidiado           1.16\n",
       "esp_Nutrición            1.18\n",
       "lluvia                   1.22\n",
       "lunes                    1.23\n",
       "esp_Odontología          1.25\n",
       "primera_vez              1.30\n",
       "hora_7am                 1.36\n",
       "hora_tarde               1.37\n",
       "sabado                   1.45\n",
       "inasistencias_previas    1.45\n",
       "esp_Psicología           1.47\n",
       "falto_antes              1.53\n",
       "edad_menor_25            1.58\n",
       "Name: odds ratio, dtype: float64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coef = dict(zip(Xtr.columns, lr.coef_[0].round(5)))\n",
    "modelo = dict(intercepto=float(lr.intercept_[0]), coeficientes={k: float(v) for k, v in coef.items()},\n",
    "              media_entrenamiento={k: float(v) for k, v in Xtr.mean().round(4).items()},\n",
    "              metricas={k: {m: round(float(v), 4) for m, v in d.items()} for k, d in metricas.items()},\n",
    "              calibracion=calib.reset_index().round(4).to_dict('records'), umbrales=umbrales, equidad=equidad, umbral_equidad=U,\n",
    "              n_entrenamiento=len(tr), n_prueba=len(te), tasa_base=float(df.no_asistio.mean()),\n",
    "              periodo=[f'{df.fecha.min():%Y-%m-%d}', f'{df.fecha.max():%Y-%m-%d}'], corte=f'{corte:%Y-%m-%d}')\n",
    "json.dump(modelo, open('no_show_model.json', 'w'), ensure_ascii=False, indent=1)\n",
    "pd.Series(np.exp(lr.coef_[0]), index=Xtr.columns).sort_values().round(2).rename('odds ratio')"
   ]
  }
 ],
 "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.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
