Applied Health Economics, RWE & HTA
Overview / Module 1 / Day 10
Module 1 · Health system & data · Day 10 of 100

Capstone: The Analysis-Ready Cohort and a 3-Year Cost Dataset

Today you deliver what an RWE team, an HTA agency or a consultancy expects at the end of a data phase. The deliverable is a cohort and a cost dataset that anyone can rebuild with one command, with the documents that make it reviewable: attrition, Table 1, a cost summary, a data dictionary and a methods write-up whose numbers come straight from the data. Before anything leaves the secure environment, it must pass a set of release checks. Then R and SAS check it independently. Everything from Days 1–9 comes together here, and Module 2 (statistics for health data) and Module 3 (comparative effectiveness) will start from these files.

▶
Video for Day 10 coming soon

By the end of today you can

  • python day10/build_capstone.py builds all outputs, and a second run gives the same fingerprints
  • All six release checks pass
  • The R check and the SAS program reproduce the cost summary
  • My methods write-up is generated, not typed, and I can defend each limitation
  • Person-level files are git-ignored. The aggregate files, code and write-up are committed

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:30
10.1 The brief
0:30–1:15
10.2 One pipeline, one command
1:15–1:30
Break
1:30–2:10
10.3 Build it and read the outputs
2:10–2:50
10.4 Release checks
2:50–3:05
Break
3:05–3:25
10.5 Two windows that share a day
3:25–4:05
10.6 Check it in R and SAS
4:05–4:40
10.7 The methods write-up
4:40–5:00
10.8 Module 1 in review
5:00–5:30
Bloc français

In this lesson

10.1 The brief (30 min)

From: HEOR lead, Renavex project We need the study population and cost base for the Renavex evidence package. Adults 66+ with type 2 diabetes and CKD in Ontario and Quebec, not on dialysis, on 1 January 2025. Please give us three years of public payer costs per person (two years before index, and follow-up through 2025) in constant 2025 dollars, with the usual documentation. The analysts in Toronto work in R, and Montreal still runs SAS. We may move the index date later, so make it re-runnable.

Turn the brief into acceptance criteria before writing code:

The brief saysAcceptance criterion
"the study population"Cohort built by the Day 6 rules, with an attrition table and diagram
"three years of costs"One row per person and period, with days observed. The periods do not overlap, and they add up to the whole window
"constant 2025 dollars", "public payer"Costs from int_cost_items.payer_cost_2025 only (Day 7)
"the usual documentation"Table 1, cost summary, data dictionary, methods
"R and SAS"CSV and Parquet files. An R check and a SAS program reproduce the summary
"re-runnable", "may move the index date"One command with an --index parameter. A rebuild gives identical files
(unsaid, always true)No small cells in anything released. Person-level files stay in the secure environment

10.2 One pipeline, one command (45 min)

corridor/capstone.py reuses everything you built: build_base_cohort() (Day 6), the cost items (Day 7), table_one() and suppress rules (Days 2 and 6), and describe() (Day 6). Two things are new.

The three periods are rows of one small table, clipped to each person's registration and death. Writing them in one place is what makes them impossible to overlap:

def periods_sql(index_date, last_day):
    """The three windows as rows: (period, start, end) per person, clipped to registration and death."""
    i = f"DATE '{index_date}'"
    return f"""
        SELECT c.person_id, p.period,
               greatest(p.w_start, r.registry_start) AS w_start,
               least(p.w_end, c.end_date)            AS w_end
        FROM capstone_cohort c
        JOIN dim_person r USING (person_id)
        CROSS JOIN (VALUES
            ('baseline_2', ({i} - INTERVAL 730 DAY)::DATE, ({i} - INTERVAL 366 DAY)::DATE),
            ('baseline_1', ({i} - INTERVAL 365 DAY)::DATE, ({i} - INTERVAL 1 DAY)::DATE),
            ('follow_up',  {i},                            DATE '{last_day}')) p(period, w_start, w_end)"""

def costs_3yr_sql(index_date, last_day):
    return f"""
    WITH w AS ({periods_sql(index_date, last_day)}),
    c AS (
        SELECT w.person_id, w.period,
               sum(x.payer_cost_2025) FILTER (x.component = 'hospital')  AS hospital,
               sum(x.payer_cost_2025) FILTER (x.component = 'physician') AS physician,
               sum(x.payer_cost_2025) FILTER (x.component = 'drug')      AS drug
        FROM w JOIN int_cost_items x
          ON x.person_id = w.person_id AND x.cost_date BETWEEN w.w_start AND w.w_end
        GROUP BY ALL)
    SELECT w.person_id, w.period, greatest(date_diff('day', w.w_start, w.w_end) + 1, 0) AS days,
           round(coalesce(c.hospital, 0), 2) AS hospital, round(coalesce(c.physician, 0), 2) AS physician,
           round(coalesce(c.drug, 0), 2) AS drug,
           round(coalesce(c.hospital, 0) + coalesce(c.physician, 0) + coalesce(c.drug, 0), 2) AS total
    FROM w LEFT JOIN c USING (person_id, period)
    ORDER BY w.person_id, list_position({list(PERIODS)}, w.period)"""

The manifest records a fingerprint (SHA-256) of every output file. If you rebuild and every fingerprint is the same, nothing changed. If one differs, you know exactly which output to look at.

"""Day 10 capstone: one pipeline from the warehouse to an analysis-ready cohort and a 3-year cost dataset.

    python day10/build_capstone.py                    # index 2025-01-01, outputs in capstone/output/
    python day10/build_capstone.py --index 2025-10-01 --out capstone/output_oct

Person-level files (cohort.*, costs_3yr.*) stay in the secure environment: they are git-ignored.
Aggregate files (attrition, Table 1, cost summary, figure, dictionary, methods) are the deliverables.
"""

import datetime as dt
import hashlib
import os
from dataclasses import dataclass

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

from corridor.cohort import build_base_cohort  # noqa: E402
from corridor.dictionary import describe, to_markdown  # noqa: E402
from corridor.privacy import SMALL  # noqa: E402
from corridor.table_one import table_one  # noqa: E402

PERIODS = ("baseline_2", "baseline_1", "follow_up")
PERSON_LEVEL = ("cohort.parquet", "cohort.csv", "costs_3yr.parquet", "costs_3yr.csv")

COHORT_DESCRIPTIONS = {
    "person_id": "Encrypted person key (links to every warehouse table)",
    "province": "Province of residence (registry)",
    "region": "Health region (registry); see regions lookup",
    "sex": "Sex recorded in the registry",
    "age": "Age in whole years on the index date",
    "income_quintile": "Neighbourhood income quintile, 1 = lowest",
    "rural": "Lives in a rural area (registry)",
    "index_date": "Cohort entry date",
    "heart_failure": "Claim 428 or hospital diagnosis I50* in the 365 days before index",
    "hypertension": "Claim 401 or hospital diagnosis I10 in the 365 days before index",
    "copd": "Claim 496 or hospital diagnosis J44* in the 365 days before index",
    "prior_stays": "Hospital admissions in the 365 days before index",
    "physician_visits": "Physician claims in the 365 days before index, excluding dialysis supervision",
    "nephrology_visit": "Any nephrology claim in the 365 days before index",
    "metformin": "Public drug claim for ATC A10BA* in the 365 days before index",
    "sglt2": "Public drug claim for ATC A10BK* in the 365 days before index",
    "insulin": "Public drug claim for ATC A10A* in the 365 days before index",
    "ace_inhibitor": "Public drug claim for ATC C09* in the 365 days before index",
    "statin": "Public drug claim for ATC C10* in the 365 days before index",
    "drug_classes": "Distinct ATC level-4 classes dispensed in the 365 days before index",
    "end_date": "Last day of follow-up: death or the end of the data (2025-12-31)",
    "died": "Died during follow-up",
}
COST_DESCRIPTIONS = {
    "person_id": "Encrypted person key",
    "period": "baseline_2 = days 730-366 before index; baseline_1 = days 365-1 before index; "
              "follow_up = index to end_date",
    "days": "Days observed in the period (0 if the person was not yet registered)",
    "hospital": "Hospital stays admitted in the period: RIW x cost per weighted case of the admission year, "
                "2025 dollars",
    "physician": "Physician claims in the period (amount paid), 2025 dollars",
    "drug": "Public drug plan paid in the period, 2025 dollars",
    "total": "hospital + physician + drug, 2025 dollars (public payer perspective)",
}

@dataclass(frozen=True)
class Config:
    index_date: str = "2025-01-01"
    last_day: str = "2025-12-31"
    out_dir: str = "capstone/output"

def periods_sql(index_date, last_day):
    """The three windows as rows: (period, start, end) per person, clipped to registration and death."""
    i = f"DATE '{index_date}'"
    return f"""
        SELECT c.person_id, p.period,
               greatest(p.w_start, r.registry_start) AS w_start,
               least(p.w_end, c.end_date)            AS w_end
        FROM capstone_cohort c
        JOIN dim_person r USING (person_id)
        CROSS JOIN (VALUES
            ('baseline_2', ({i} - INTERVAL 730 DAY)::DATE, ({i} - INTERVAL 366 DAY)::DATE),
            ('baseline_1', ({i} - INTERVAL 365 DAY)::DATE, ({i} - INTERVAL 1 DAY)::DATE),
            ('follow_up',  {i},                            DATE '{last_day}')) p(period, w_start, w_end)"""

def costs_3yr_sql(index_date, last_day):
    return f"""
    WITH w AS ({periods_sql(index_date, last_day)}),
    c AS (
        SELECT w.person_id, w.period,
               sum(x.payer_cost_2025) FILTER (x.component = 'hospital')  AS hospital,
               sum(x.payer_cost_2025) FILTER (x.component = 'physician') AS physician,
               sum(x.payer_cost_2025) FILTER (x.component = 'drug')      AS drug
        FROM w JOIN int_cost_items x
          ON x.person_id = w.person_id AND x.cost_date BETWEEN w.w_start AND w.w_end
        GROUP BY ALL)
    SELECT w.person_id, w.period, greatest(date_diff('day', w.w_start, w.w_end) + 1, 0) AS days,
           round(coalesce(c.hospital, 0), 2) AS hospital, round(coalesce(c.physician, 0), 2) AS physician,
           round(coalesce(c.drug, 0), 2) AS drug,
           round(coalesce(c.hospital, 0) + coalesce(c.physician, 0) + coalesce(c.drug, 0), 2) AS total
    FROM w LEFT JOIN c USING (person_id, period)
    ORDER BY w.person_id, list_position({list(PERIODS)}, w.period)"""

def sha256(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()[:16]

def _attrition_figure(steps, path):
    fig, ax = plt.subplots(figsize=(7.2, 0.95 * len(steps) + 0.4))
    ax.set_xlim(0, 8.6)
    ax.set_ylim(-len(steps) + 0.4, 0.8)
    ax.axis("off")
    for i, label, n, removed in steps:
        text = f"{'Everyone in the registry, 2019-2025' if i == 0 else label}\nn = {n:,}"
        ax.text(3.6, -i, text, ha="center", va="center", fontsize=8.5,
                bbox=dict(boxstyle="round,pad=0.4", fc="#eef2ff", ec="#2563eb"))
        if i:
            ax.annotate("", xy=(3.6, -i + 0.3), xytext=(3.6, -i + 0.7), arrowprops=dict(arrowstyle="->", color="#555"))
            ax.text(6.5, -i + 0.5, f"excluded {removed:,}", ha="left", va="center", fontsize=8, color="#b91c1c")
    fig.tight_layout()
    fig.savefig(path, dpi=130, metadata={"Software": None})
    plt.close(fig)

def run(con, config=Config(), root="."):
    """Build every capstone output. Returns a dict of results used in the methods write-up."""
    out = os.path.join(root, config.out_dir)
    os.makedirs(out, exist_ok=True)
    q = lambda p: os.path.join(out, p).replace("\\", "/")  # noqa: E731

    # 1. cohort (Day 6 rules) with follow-up end (Day 7)
    attrition = build_base_cohort(con, index_date=config.index_date, table="cohort_cap")
    con.execute(f"""
        CREATE OR REPLACE TEMP TABLE capstone_cohort AS
        SELECT c.*, least(coalesce(p.death_date, DATE '{config.last_day}'), DATE '{config.last_day}') AS end_date,
               coalesce(p.death_date <= DATE '{config.last_day}', false) AS died
        FROM cohort_cap c JOIN dim_person p USING (person_id)
        ORDER BY c.person_id""")

    # 2. three-year costs, one row per person and period
    con.execute(f"CREATE OR REPLACE TEMP TABLE capstone_costs AS {costs_3yr_sql(config.index_date, config.last_day)}")

    # 3. person-level files (stay in the secure environment)
    con.execute(f"COPY (SELECT * FROM capstone_cohort ORDER BY person_id) TO '{q('cohort.parquet')}' (FORMAT parquet)")
    con.execute(f"""COPY (SELECT * REPLACE (rural::INT AS rural, heart_failure::INT AS heart_failure,
                                 hypertension::INT AS hypertension, copd::INT AS copd,
                                 nephrology_visit::INT AS nephrology_visit, metformin::INT AS metformin,
                                 sglt2::INT AS sglt2, insulin::INT AS insulin, ace_inhibitor::INT AS ace_inhibitor,
                                 statin::INT AS statin, died::INT AS died)
                    FROM capstone_cohort ORDER BY person_id) TO '{q('cohort.csv')}' (HEADER)""")
    con.execute(f"COPY capstone_costs TO '{q('costs_3yr.parquet')}' (FORMAT parquet)")
    con.execute(f"COPY capstone_costs TO '{q('costs_3yr.csv')}' (HEADER)")

    # 4. aggregate deliverables
    steps = attrition.table_rows()
    with open(q("attrition.csv"), "w", encoding="utf-8") as f:
        f.write("step,criterion,remaining,excluded\n")
        for i, label, n, removed in steps:
            f.write(f'{i},"{label}",{n},{removed if i else 0}\n')
    _attrition_figure(steps, q("attrition.png"))

    df = con.sql("""SELECT *, sex = 'F' AS female, income_quintile = 1 AS lowest_income_quintile,
                           prior_stays > 0 AS any_hospital_stay FROM capstone_cohort""").df()
    t1 = table_one(df, "province",
                   binary=["female", "lowest_income_quintile", "rural", "heart_failure", "hypertension", "copd",
                           "any_hospital_stay", "nephrology_visit", "metformin", "sglt2", "insulin",
                           "ace_inhibitor", "statin"],
                   continuous=["age", "physician_visits", "drug_classes"])
    t1.to_csv(q("table_one.csv"), index=False)

    summary = con.sql(f"""
        SELECT period, coalesce(c.province, 'All') AS province, count(*) AS people,
               round(sum(days) / 365.25, 1) AS person_years,
               round(sum(total) / count(*), 2) AS cost_per_person,
               round(sum(total) / (sum(days) / 365.25), 2) AS cost_per_person_year,
               round(sum(hospital) / (sum(days) / 365.25), 2) AS hospital_per_py,
               round(sum(physician) / (sum(days) / 365.25), 2) AS physician_per_py,
               round(sum(drug) / (sum(days) / 365.25), 2) AS drug_per_py,
               round(median(total), 2) AS median_cost
        FROM capstone_costs k JOIN capstone_cohort c USING (person_id)
        GROUP BY GROUPING SETS ((period, c.province), (period))
        ORDER BY list_position({list(PERIODS)}, period), grouping(c.province), c.province""").df()
    summary.to_csv(q("cost_summary.csv"), index=False)

    cohort_dict = describe(con.sql("SELECT * FROM capstone_cohort").df(), COHORT_DESCRIPTIONS)
    cost_dict = describe(con.sql("SELECT * FROM capstone_costs").df(), COST_DESCRIPTIONS)
    with open(q("data_dictionary.md"), "w", encoding="utf-8") as f:
        f.write(to_markdown(cohort_dict, f"cohort (index {config.index_date})"))
        f.write("\n")
        f.write(to_markdown(cost_dict, "costs_3yr (one row per person and period)"))

    # 5. results for the methods write-up
    fu = summary[(summary.period == "follow_up")].set_index("province")
    b1 = summary[(summary.period == "baseline_1")].set_index("province")
    deaths, fu_py = con.sql("""SELECT count_if(died), sum(days) / 365.25 FROM capstone_cohort
                               JOIN capstone_costs USING (person_id) WHERE period = 'follow_up'""").fetchall()[0]
    results = {
        "index_date": config.index_date, "last_day": config.last_day,
        "registry_n": steps[0][2], "cohort_n": steps[-1][2],
        "n_on": int(fu.loc["ON", "people"]), "n_qc": int(fu.loc["QC", "people"]),
        "deaths": deaths, "fu_py": fu_py,
        "fu_ppy_all": fu.loc["All", "cost_per_person_year"], "fu_ppy_on": fu.loc["ON", "cost_per_person_year"],
        "fu_ppy_qc": fu.loc["QC", "cost_per_person_year"], "b1_ppy_all": b1.loc["All", "cost_per_person_year"],
        "fu_median": fu.loc["All", "median_cost"], "fu_mean": fu.loc["All", "cost_per_person"],
        "hospital_share": 100 * fu.loc["All", "hospital_per_py"] / fu.loc["All", "cost_per_person_year"],
        "mean_age": df.age.mean(), "rural_smd": t1.loc[t1.characteristic == "rural, n (%)", "smd"].iloc[0],
        "steps": steps,
    }
    with open(os.path.join(root, "capstone", "methods_template.md"), encoding="utf-8") as f:
        template = f.read()
    step_lines = "\n".join(f"| {i} | {label} | {n:,} | {removed:,} |" if i else f"| 0 | Everyone in the registry | {n:,} | |"
                           for i, label, n, removed in steps)
    fields = {k: v for k, v in results.items() if k != "steps"}
    with open(q("methods.md"), "w", encoding="utf-8") as f:
        f.write(template.format(attrition_rows=step_lines, small_minus_one=SMALL - 1, **fields))

    # 6. manifest: a fingerprint of every output, to show a rebuild gives the same files
    names = sorted(n for n in os.listdir(out) if n != "MANIFEST.txt")
    with open(q("MANIFEST.txt"), "w", encoding="utf-8") as f:
        for n in names:
            kind = "person-level (do not release)" if n in PERSON_LEVEL else "aggregate"
            f.write(f"{sha256(q(n))}  {n:<22}{kind}\n")
    return results

The command-line wrapper:

"""Day 10.3: build the capstone - one command, every output.

    python day10/build_capstone.py [--index YYYY-MM-DD] [--out capstone/output]
"""

import argparse
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.capstone import Config, run  # noqa: E402
from corridor.db import ROOT, warehouse  # noqa: E402

parser = argparse.ArgumentParser(description="Build the Module 1 capstone outputs.")
parser.add_argument("--index", default="2025-01-01", help="index date (default 2025-01-01)")
parser.add_argument("--out", default="capstone/output", help="output folder, relative to the repository")
args = parser.parse_args()

config = Config(index_date=args.index, out_dir=args.out)
results = run(warehouse(), config, root=ROOT)
print(f"Capstone built: index {config.index_date}, {results['cohort_n']:,} people, outputs in {config.out_dir}/\n")
print(open(os.path.join(ROOT, config.out_dir, "MANIFEST.txt"), encoding="utf-8").read())

10.3 Build it and read the outputs (40 min)

python day10/build_capstone.py
Capstone built: index 2025-01-01, 6,224 people, outputs in capstone/output/

3856a1b661c7a778  attrition.csv         aggregate
e8b16df27bcff4b4  attrition.png         aggregate
57b99d31319051cc  cohort.csv            person-level (do not release)
996fc0f69c26cfeb  cohort.parquet        person-level (do not release)
d050819bdbc3f116  cost_summary.csv      aggregate
50bca1e5825ec40e  costs_3yr.csv         person-level (do not release)
8fdf345c6c939672  costs_3yr.parquet     person-level (do not release)
630319078ebf3acc  data_dictionary.md    aggregate
48657d203ec6bdbb  methods.md            aggregate
8705b3e17ab8e1dc  table_one.csv         aggregate

The fingerprints will match yours if your package versions match the course's. A different version of DuckDB or matplotlib can write the same data with different bytes. Within one project, pin the versions (Module 8 does this with renv and lock files).

The cost summary (cost_summary.csv):

period,province,people,person_years,cost_per_person,cost_per_person_year,hospital_per_py,physician_per_py,drug_per_py,median_cost
baseline_2,ON,3956,3936.9,4716.79,4739.71,3236.27,549.33,954.1,1551.22
baseline_2,QC,2268,2253.7,4530.28,4559.0,3291.47,535.72,731.8,1249.38
baseline_2,All,6224,6190.6,4648.83,4673.92,3256.37,544.38,873.17,1443.87
baseline_1,ON,3956,3953.3,5644.39,5648.26,3929.99,580.15,1138.12,1860.74
baseline_1,QC,2268,2266.4,5181.46,5185.01,3746.34,569.26,869.41,1497.68
baseline_1,All,6224,6219.7,5475.7,5479.45,3863.07,576.18,1040.2,1729.92
follow_up,ON,3956,3825.0,5397.21,5582.1,3930.48,562.44,1089.19,1729.33
follow_up,QC,2268,2178.8,4794.76,4991.0,3646.69,547.39,796.92,1290.95
follow_up,All,6224,6003.8,5177.68,5367.59,3827.49,556.98,983.12,1567.23

Read it as a three-year trajectory:

  • Costs rise towards the index date. The cohort cost $4,674 per person-year two years before index, then $5,479 in the year before, then $5,368 in follow-up. That is not chance. To enter the cohort, people had to have been diagnosed and coded before the index date, so the selection itself picks people whose disease was becoming visible. Keep this in mind in Module 3: "costs before and after starting a drug" always has this shape, with or without the drug.
  • Ontario costs more than Quebec in every period, mainly through drugs (Day 7.5).
  • Medians are about a third of means in every period (Day 7.6). Module 2 starts here.

Table 1 (table_one.csv) is Day 6's, now a file:

characteristic,ON,QC,overall,smd
People,"3,956","2,268","6,224",
"age, mean (SD)",79.3 (8.5),79.1 (8.4),79.2 (8.5),0.02
"physician_visits, mean (SD)",11.3 (4.3),11.3 (4.3),11.3 (4.3),-0.00
"drug_classes, mean (SD)",4.0 (1.2),3.9 (1.2),3.9 (1.2),0.05
"female, n (%)","1,908 (48.2%)","1,091 (48.1%)","2,999 (48.2%)",0.00
"lowest_income_quintile, n (%)",928 (23.5%),549 (24.2%),"1,477 (23.7%)",-0.02
"rural, n (%)",468 (11.8%),452 (19.9%),920 (14.8%),-0.22
"heart_failure, n (%)",605 (15.3%),346 (15.3%),951 (15.3%),0.00
"hypertension, n (%)","2,789 (70.5%)","1,620 (71.4%)","4,409 (70.8%)",-0.02
"copd, n (%)",238 (6.0%),154 (6.8%),392 (6.3%),-0.03
"any_hospital_stay, n (%)","1,279 (32.3%)",741 (32.7%),"2,020 (32.5%)",-0.01
"nephrology_visit, n (%)","1,693 (42.8%)",962 (42.4%),"2,655 (42.7%)",0.01
"metformin, n (%)","3,359 (84.9%)","1,893 (83.5%)","5,252 (84.4%)",0.04
"sglt2, n (%)","1,648 (41.7%)",865 (38.1%),"2,513 (40.4%)",0.07
"insulin, n (%)","1,067 (27.0%)",568 (25.0%),"1,635 (26.3%)",0.04
"ace_inhibitor, n (%)","2,383 (60.2%)","1,417 (62.5%)","3,800 (61.1%)",-0.05
"statin, n (%)","3,093 (78.2%)","1,761 (77.6%)","4,854 (78.0%)",0.01

The data dictionary documents both person-level files. Here is its second half:

# costs_3yr (one row per person and period)

| column | type | description | missing | values |
|---|---|---|---|---|
| person_id | str | Encrypted person key | 0 | 6,224 distinct values |
| period | str | baseline_2 = days 730-366 before index; baseline_1 = days 365-1 before index; follow_up = index to end_date | 0 | baseline_1, baseline_2, follow_up |
| days | int64 | Days observed in the period (0 if the person was not yet registered) | 0 | 1 to 365 |
| hospital | float64 | Hospital stays admitted in the period: RIW x cost per weighted case of the admission year, 2025 dollars | 0 | 0 to 73778.1 |
| physician | float64 | Physician claims in the period (amount paid), 2025 dollars | 0 | 0 to 2055 |
| drug | float64 | Public drug plan paid in the period, 2025 dollars | 0 | 0 to 9159.06 |
| total | float64 | hospital + physician + drug, 2025 dollars (public payer perspective) | 0 | 0 to 76708.7 |

10.4 Release checks (40 min)

Before a file leaves the secure environment (to a client, a journal or GitHub), run the checks that catch the mistakes made all week:

"""Day 10.5: checks before anything leaves the secure environment."""

import csv
import os
import shutil
import sys
import tempfile

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.capstone import PERSON_LEVEL, Config, periods_sql, run, sha256  # noqa: E402
from corridor.db import ROOT, warehouse  # noqa: E402
from corridor.privacy import SMALL  # noqa: E402

OUT = os.path.join(ROOT, "capstone", "output").replace("\\", "/")
con = warehouse()
con.execute(f"CREATE TEMP VIEW capstone_cohort AS SELECT * FROM read_parquet('{OUT}/cohort.parquet')")
con.execute(f"CREATE TEMP VIEW costs AS SELECT * FROM read_parquet('{OUT}/costs_3yr.parquet')")
results = []

def check(name, ok, detail):
    results.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name:<52}{detail}")

# 1. the cohort matches the last attrition step
with open(os.path.join(OUT, "attrition.csv"), encoding="utf-8") as f:
    last = list(csv.DictReader(f))[-1]
n = con.sql("SELECT count(*) FROM capstone_cohort").fetchall()[0][0]
check("cohort size = last attrition step", n == int(last["remaining"]), f"{n:,} people")

# 2. exactly three periods per person
bad = con.sql("""SELECT count(*) FROM (SELECT person_id, count(*) AS k FROM costs GROUP BY 1 HAVING k <> 3)""").fetchall()[0][0]
check("three periods per person", bad == 0, f"{bad} people with another number")

# 3. the periods add up to a direct sum over the whole window
direct = con.sql(f"""
    WITH w AS ({periods_sql('2025-01-01', '2025-12-31')}),
    whole AS (SELECT person_id, min(w_start) AS a, max(w_end) AS b FROM w GROUP BY 1)
    SELECT sum(x.payer_cost_2025) FROM whole JOIN int_cost_items x
      ON x.person_id = whole.person_id AND x.cost_date BETWEEN whole.a AND whole.b""").fetchall()[0][0]
periods = con.sql("SELECT sum(total) FROM costs").fetchall()[0][0]
check("periods add up to the whole window", abs(direct - periods) < 1.0, f"${periods:,.2f} vs ${direct:,.2f}")

# 4. no small cells in the released tables
small = 0
for name in ("table_one.csv", "cost_summary.csv"):
    with open(os.path.join(OUT, name), encoding="utf-8") as f:
        for row in csv.DictReader(f):
            for key, value in row.items():
                head = value.split(" ")[0].replace(",", "")
                if key in ("people", "ON", "QC", "overall") and head.isdigit() and 0 < int(head) < SMALL:
                    small += 1
check(f"no released count from 1 to {SMALL - 1}", small == 0, f"{small} small cells")

# 5. person-level files are listed as such, and git-ignored
ignore = open(os.path.join(ROOT, ".gitignore"), encoding="utf-8").read()
check("person-level files are git-ignored", all(f"capstone/output*/{p}" in ignore for p in PERSON_LEVEL),
      ", ".join(PERSON_LEVEL))

# 6. a rebuild gives byte-identical files
tmp = tempfile.mkdtemp()
try:
    os.makedirs(os.path.join(tmp, "capstone"))
    shutil.copy(os.path.join(ROOT, "capstone", "methods_template.md"), os.path.join(tmp, "capstone"))
    run(warehouse(), Config(out_dir="capstone/output"), root=tmp)
    again = os.path.join(tmp, "capstone", "output")
    differ = [f for f in sorted(os.listdir(OUT)) if sha256(os.path.join(OUT, f)) != sha256(os.path.join(again, f))]
finally:
    shutil.rmtree(tmp)
check("a rebuild gives identical files", not differ, f"{len(os.listdir(OUT))} files compared" if not differ
      else f"differ: {', '.join(differ)}")

print(f"\n{sum(results)} of {len(results)} checks passed.")
PASS  cohort size = last attrition step                   6,224 people
PASS  three periods per person                            0 people with another number
PASS  periods add up to the whole window                  $95,240,930.15 vs $95,240,930.15
PASS  no released count from 1 to 5                       0 small cells
PASS  person-level files are git-ignored                  cohort.parquet, cohort.csv, costs_3yr.parquet, costs_3yr.csv
PASS  a rebuild gives identical files                     11 files compared

6 of 6 checks passed.
CheckCatches
Cohort size = last attrition stepAn attrition table from a different run
Three periods per personA join that drops or duplicates periods (Day 4's fan-out)
Periods add up to the whole windowOverlapping or gapped windows (10.5)
No counts from 1 to 5A privacy breach (Day 2)
Person-level files git-ignoredPushing personal data to GitHub
A rebuild gives identical filesHidden randomness, unordered output, stale files

The .gitignore entries that keep person-level files out:

# Day 10: person-level capstone files never leave the secure environment
capstone/output*/cohort.parquet
capstone/output*/cohort.csv
capstone/output*/costs_3yr.parquet
capstone/output*/costs_3yr.csv

10.5 Two windows that share a day (20 min)

Bug of the day. A colleague ends the baseline year on the index date ("costs up to index") and starts follow-up on the index date too:

"""Day 10 bug of the day: two windows that share a day.

A colleague ends the baseline year ON the index date ("up to index") and starts follow-up
on the index date too.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import ROOT, show, warehouse  # noqa: E402

OUT = os.path.join(ROOT, "capstone", "output").replace("\\", "/")
con = warehouse()
con.execute(f"CREATE TEMP VIEW c AS SELECT * FROM read_parquet('{OUT}/cohort.parquet')")
show(con, """
    WITH items AS (
        SELECT x.person_id, x.cost_date, x.payer_cost_2025, x.component
        FROM int_cost_items x JOIN c USING (person_id)
        WHERE x.cost_date BETWEEN c.index_date - INTERVAL 365 DAY AND c.end_date)
    SELECT 'baseline ends the day before index' AS rule,
           round(sum(payer_cost_2025) FILTER (cost_date < DATE '2025-01-01')) AS baseline,
           round(sum(payer_cost_2025) FILTER (cost_date >= DATE '2025-01-01')) AS follow_up,
           round(sum(payer_cost_2025) FILTER (cost_date < DATE '2025-01-01')
                 + sum(payer_cost_2025) FILTER (cost_date >= DATE '2025-01-01')) AS sum_of_periods,
           round(sum(payer_cost_2025)) AS whole_window
    FROM items
    UNION ALL
    SELECT 'colleague: baseline ends ON index',
           round(sum(payer_cost_2025) FILTER (cost_date <= DATE '2025-01-01')),
           round(sum(payer_cost_2025) FILTER (cost_date >= DATE '2025-01-01')),
           round(sum(payer_cost_2025) FILTER (cost_date <= DATE '2025-01-01')
                 + sum(payer_cost_2025) FILTER (cost_date >= DATE '2025-01-01')),
           round(sum(payer_cost_2025))
    FROM items""")
show(con, """SELECT component, count(*) AS items_on_index_day, round(sum(payer_cost_2025)) AS cost
             FROM int_cost_items x JOIN c USING (person_id)
             WHERE x.cost_date = DATE '2025-01-01' GROUP BY 1 ORDER BY 1""")
                              rule  baseline  follow_up  sum_of_periods  whole_window
baseline ends the day before index  34080773   32225857        66306629      66306629
 colleague: baseline ends ON index  34165521   32225857        66391378      66306629
component  items_on_index_day  cost
     drug                 604  9248
 hospital                   7 64614
physician                 211 10887

Every cost on 1 January 2025 is counted twice: 604 drug claims, 211 physician claims and 7 hospital admissions, $84,749 in all. That is small against $66 million, which is exactly why nobody notices. But the same mistake in a before–after comparison adds the index-day costs to both sides. The index date is often the day of a hospital discharge or a first prescription, so those costs are not small. The release check "periods add up to the whole window" fails immediately. The design fix is in 10.2: each period starts the day after the previous one ends, written once, in one table.


10.6 Check it in R and SAS (40 min)

R checks the capstone two ways. It re-aggregates the cost file and compares the result with cost_summary.csv. Then it recomputes follow-up costs directly from the cost items, a different route to the same number:

# Day 10.6: an independent check of the capstone in R.
# 1. Re-aggregate the 3-year cost file and compare with cost_summary.csv.
# 2. Recompute follow-up costs from the cost items (warehouse/export) - a second route to the same number.
source("r/corridor.R")
con <- corridor_connect()
out <- "capstone/output"
invisible(dbExecute(con, sprintf("CREATE VIEW cap_cohort AS SELECT * FROM read_parquet('%s/cohort.parquet')", out)))
invisible(dbExecute(con, sprintf("CREATE VIEW cap_costs AS SELECT * FROM read_parquet('%s/costs_3yr.parquet')", out)))
summary_py <- read.csv(file.path(out, "cost_summary.csv"))

by_period <- tbl(con, "cap_costs") |>
  inner_join(tbl(con, "cap_cohort") |> select(person_id, province), by = "person_id") |>
  group_by(period, province) |>
  summarise(people = n(), py = sum(days, na.rm = TRUE) / 365.25, cost = sum(total, na.rm = TRUE)) |>
  collect() |>
  mutate(cost_per_person_year = round(cost / py, 2)) |>
  arrange(period, province)
check1 <- merge(by_period[, c("period", "province", "people", "cost_per_person_year")],
                summary_py[, c("period", "province", "people", "cost_per_person_year")],
                by = c("period", "province"), suffixes = c("_r", "_python"))
show(check1)
stopifnot(all(check1$people_r == check1$people_python),
          isTRUE(all.equal(check1$cost_per_person_year_r, check1$cost_per_person_year_python, tolerance = 1e-9)))
cat("\n1. Re-aggregation matches cost_summary.csv for all", nrow(check1), "period-province rows.\n\n")

fu_direct <- tbl(con, "cap_cohort") |>
  select(person_id, province, index_date, end_date) |>
  inner_join(tbl(con, "int_cost_items") |> select(person_id, cost_date, payer_cost_2025), by = "person_id") |>
  filter(cost_date >= index_date, cost_date <= end_date) |>
  group_by(province) |>
  summarise(cost = sum(payer_cost_2025, na.rm = TRUE)) |>
  collect()
fu_file <- by_period |> ungroup() |> filter(period == "follow_up") |> select(province, cost)
check2 <- merge(fu_direct, fu_file, by = "province", suffixes = c("_from_items", "_from_file"))
check2$difference <- round(check2$cost_from_items - check2$cost_from_file, 2)
show(check2 |> mutate(across(starts_with("cost"), round)))
stopifnot(all(abs(check2$difference) < 1))
cat("\n2. Follow-up costs from the cost items match the capstone file (rounding differences under $1).\n")
     period province people_r cost_per_person_year_r people_python cost_per_person_year_python
 baseline_1       ON     3956                5648.26          3956                     5648.26
 baseline_1       QC     2268                5185.01          2268                     5185.01
 baseline_2       ON     3956                4739.71          3956                     4739.71
 baseline_2       QC     2268                4559.00          2268                     4559.00
  follow_up       ON     3956                5582.10          3956                     5582.10
  follow_up       QC     2268                4991.00          2268                     4991.00

1. Re-aggregation matches cost_summary.csv for all 6 period-province rows.

 province cost_from_items cost_from_file difference
       ON        21351344       21351344          0
       QC        10874513       10874513          0

2. Follow-up costs from the cost items match the capstone file (rounding differences under $1).

SAS. Upload capstone/output/cohort.csv and costs_3yr.csv to your corridor folder and run:

/* Day 10.6: the capstone's cost summary in SAS, from the capstone's own CSV files.
   Upload capstone/output/cohort.csv and costs_3yr.csv to your corridor folder first. */
%let path = /home/u00000000/corridor;
libname corr "&path";

data corr.cap_cohort;
  infile "&path/cohort.csv" dsd firstobs=2 truncover;
  length person_id $11 province $2 region $6 sex $1;
  input person_id $ province $ region $ sex $ age income_quintile rural
        index_date :yymmdd10. heart_failure hypertension copd prior_stays physician_visits
        nephrology_visit metformin sglt2 insulin ace_inhibitor statin drug_classes
        end_date :yymmdd10. died;
  format index_date end_date yymmdd10.;
run;

data corr.cap_costs;
  infile "&path/costs_3yr.csv" dsd firstobs=2;
  length person_id $11 period $10;
  input person_id $ period $ days hospital physician drug total;
run;

/* cost per person and per person-year, by period and province, then for everyone */
proc sql;
  create table work.summary as
  select k.period, c.province, count(*) as people,
         sum(k.days) / 365.25 as person_years format=comma10.1,
         sum(k.total) / count(*) as cost_per_person format=dollar12.2,
         sum(k.total) / (sum(k.days) / 365.25) as cost_per_person_year format=dollar12.2
  from corr.cap_costs as k inner join corr.cap_cohort as c on k.person_id = c.person_id
  group by k.period, c.province
  union all
  select k.period, 'All' as province, count(*) as people,
         sum(k.days) / 365.25 as person_years format=comma10.1,
         sum(k.total) / count(*) as cost_per_person format=dollar12.2,
         sum(k.total) / (sum(k.days) / 365.25) as cost_per_person_year format=dollar12.2
  from corr.cap_costs as k
  group by k.period;
quit;

proc sort data=work.summary;
  by period province;
run;

proc print data=work.summary noobs;
run;

/* the median, which the mean hides */
proc means data=corr.cap_costs median maxdec=2;
  class period;
  var total;
run;

proc freq data=corr.cap_cohort;
  tables province*died / nocol nopercent;
run;

ods excel file="&path/capstone_summary_sas.xlsx" options(sheet_name="Costs");
proc print data=work.summary noobs;
run;
ods excel close;

Expected results (computed from the same files with DuckDB; the course tests also check this program's INPUT statements against the CSV headers):

--- PROC PRINT of work.summary (sorted by period, then province)
    period province  people  person_years  cost_per_person  cost_per_person_year
baseline_1      All    6224        6219.7          5475.70               5479.45
baseline_1       ON    3956        3953.3          5644.39               5648.26
baseline_1       QC    2268        2266.4          5181.46               5185.01
baseline_2      All    6224        6190.6          4648.83               4673.92
baseline_2       ON    3956        3936.9          4716.79               4739.71
baseline_2       QC    2268        2253.7          4530.28               4559.00
 follow_up      All    6224        6003.8          5177.68               5367.59
 follow_up       ON    3956        3825.0          5397.21               5582.10
 follow_up       QC    2268        2178.8          4794.76               4991.00

--- PROC MEANS: median total cost by period
    period    n  median
baseline_1 6224 1729.92
baseline_2 6224 1443.87
 follow_up 6224 1567.23

--- PROC FREQ: deaths during follow-up by province
province  died_0  died_1  pct_died
      ON    3691     265      6.70
      QC    2101     167      7.36

Three languages, one set of numbers: Ontario $5,582.10 and Quebec $4,991.00 per person-year in follow-up, the same as Day 7.

Try it (15 min). The HEOR lead asks: "What if the index date is Ontario's listing day, 1 October 2025?" Rebuild into a second folder and compare.

Solution
"""Day 10 exercise: rebuild the capstone with the index on Ontario's Renavex listing day."""

import os
import sys

import pandas as pd

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.capstone import Config, run  # noqa: E402
from corridor.db import ROOT, warehouse  # noqa: E402

r = run(warehouse(), Config(index_date="2025-10-01", out_dir="capstone/output_oct"), root=ROOT)
s = pd.read_csv(os.path.join(ROOT, "capstone", "output_oct", "cost_summary.csv"))
print(f"Index 2025-10-01: {r['cohort_n']:,} people, {r['fu_py']:.1f} follow-up person-years, {r['deaths']} deaths\n")
print(s[s.province == "All"][["period", "people", "person_years", "cost_per_person", "cost_per_person_year"]]
      .to_string(index=False))
Index 2025-10-01: 6,705 people, 1675.2 follow-up person-years, 115 deaths

    period  people  person_years  cost_per_person  cost_per_person_year
baseline_2    6705        6682.2          4864.52               4881.13
baseline_1    6705        6700.4          4996.55               4999.98
 follow_up    6705        1675.2          1290.88               5166.60

The October cohort is larger (Day 6's exercise). Its follow-up is only three months: 1,675 person-years, with 115 deaths. Per person, follow-up costs look tiny ($1,291), but per person-year ($5,167) they are in line with the January cohort. The brief's "may move the index date later" now costs one command. The question to send back to the HEOR lead: with only three months of follow-up, is the October cohort useful for 2025 costs, or should it wait for 2026 data?


10.7 The methods write-up (35 min)

The write-up is a template (capstone/methods_template.md) with placeholders such as {cohort_n:,} and {fu_ppy_all:,.0f}. The pipeline fills them from the results. No number is typed by hand, so the write-up cannot disagree with the data. If the index date moves, the write-up changes with it.

# Analysis-ready cohort and 3-year costs: methods

*Corridor Health course, Module 1 capstone. Synthetic data: no real person is described. Numbers are filled in by the pipeline (`python day10/build_capstone.py`); do not edit them by hand.*

## Data sources

Corridor Health's administrative-style tables, 2019–2025, built into a DuckDB warehouse with dbt: the registry of insured persons (including people who died), physician claims (ICD-9 diagnosis, fee code, amount paid), hospital discharge abstracts (ICD-10 diagnoses, case-mix group, resource intensity weight), public drug plan claims (DIN, ATC, amount paid by the plan) and public drug plan eligibility periods.

## Population

Adults aged 66 or older on the index date (2025-01-01) with type 2 diabetes and chronic kidney disease, followed to death or 2025-12-31.

| Step | Criterion | Remaining | Excluded |
|---|---|---|---|
| 0 | Everyone in the registry | 262,711 | |
| 1 | Alive and registered on the index date | 247,521 | 15,190 |
| 2 | Registered for at least 365 days before the index date | 246,147 | 1,374 |
| 3 | Aged 66 or older on the index date | 58,608 | 187,539 |
| 4 | Diabetes before the index date (Ontario definition) | 15,574 | 43,034 |
| 5 | Chronic kidney disease before the index date | 6,664 | 8,910 |
| 6 | On a public drug plan for all 365 days before the index date | 6,521 | 143 |
| 7 | No dialysis before the index date | 6,224 | 297 |

- **Diabetes:** one hospital stay with ICD-10 E11 in any diagnosis position, or two physician claims with ICD-9 250 within 730 days (the Ontario definition), before the index date.
- **Chronic kidney disease:** two physician claims with ICD-9 585 within 730 days, one hospital stay with N18 or Z49.1, or one dialysis supervision claim, before the index date.
- **Observability:** registered for 365 days and on a public drug plan for all 365 days before the index date (age 66+ guarantees a full year of public drug history in Ontario).
- **Exclusion:** any dialysis before the index date.

The cohort has 6,224 people (3,956 in Ontario, 2,268 in Quebec), with a mean age of 79.2. The provinces are balanced on all baseline characteristics except rurality (standardized difference -0.22).

## Baseline characteristics

Comorbidities, hospital stays, physician visits and drug use were measured in the 365 days before the index date, never after it.

## Costs

- **Perspective:** publicly funded health care payer (hospital care, physician services, public drug plans). Patient co-payments are excluded.
- **Hospital stays:** resource intensity weight × the province's cost per weighted case in the year of admission.
- **Physician services:** amount paid. **Drugs:** amount paid by the public plan.
- **Price year:** all costs in 2025 dollars, using a health care price index.
- **Periods:** baseline year 2 (days 730–366 before index), baseline year 1 (days 365–1 before index), and follow-up (index to death or 2025-12-31). Costs are assigned by admission, service or dispensing date. Periods do not overlap.

## Results in brief

- Follow-up: 6,003.8 person-years and 432 deaths.
- Public payer cost per person-year in follow-up: **$5,368** (Ontario $5,582, Quebec $4,991), against $5,479 in the baseline year.
- Hospital care accounts for 71% of follow-up costs.
- Costs are right-skewed: a mean of $5,178 per person against a median of $1,567.

## Quality checks

The cost items reconcile to the source claims to the cent (dbt test). The three periods add up to a direct sum over the whole window. Every person has three periods. Released tables contain no counts from 1 to 5, and a rebuild produces byte-identical files (see `MANIFEST.txt`).

## Limitations

- Claims-based CKD definitions miss early disease (stage 3a), so the cohort is sicker than the label population of a CKD drug.
- Costs are expected costs by case mix, not actual costs. Home care, long-term care, private drug spending and productivity are not included.
- Corridor Health is synthetic. Its amounts, codes and rates are course values.

This is a writing sample for your portfolio. It is about two pages, it says what was done and what it cannot tell you, and every number can be traced. Read it as a reviewer would. Can someone rebuild the cohort from it alone? Are the limitations the real ones?

Day 10 checklist

  • python day10/build_capstone.py builds all outputs, and a second run gives the same fingerprints
  • All six release checks pass
  • The R check and the SAS program reproduce the cost summary
  • My methods write-up is generated, not typed, and I can defend each limitation
  • Person-level files are git-ignored. The aggregate files, code and write-up are committed
python -m pytest -q
git add .
git commit -m "Day 10: Module 1 capstone"
git tag v1.0-module1
git push --tags

10.8 Module 1 in review (20 min)

DayYou builtThe bug you will not repeat
1Cost-sharing rules for five public drug plansA monthly deductible applied once a year
2Person-time, coverage gaps, small-cell suppressionCounting claims instead of people
3Code lists across ICD-10, ICD-9, ATC, fee codes; costing a stayDotted ICD codes; DINs that lose their leading zero
4A tested dbt warehouse, 2019–2025A join that copies rows
5Validated case definitions, new users, incidenceNew users who were old users on a private plan
6The base cohort, Table 1, data dictionaryA baseline window that looks into the future
7Cost items in 2025 dollars, cohort costsThe wrong column for the perspective
8The cohort in R, checked against PythonNA treated as FALSE
9The cohort in SASPROC IMPORT and the leading zero
10A re-runnable, checked, documented deliverableTwo windows that share a day

Next: Module 2, biostatistics and econometrics for health data. Day 11 starts from costs_3yr. A mean three times the median, a long right tail and people with no costs at all: ordinary regression handles this badly, and you will see by how much.