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

Cohort Building I: Index Dates, Look-Back Windows and Case Definitions

A cohort study needs answers to three questions for every person. Who is in it: someone with diabetes, according to which definition? When does their follow-up start, the index date? And what could we see before that date? Today you validate case definitions for diabetes and kidney disease against the hidden truth. Then you define new users of a drug, and find the error that has misled more Canadian drug studies than any other: treating the start of drug coverage as the start of drug use.

▶
Video for Day 5 coming soon

By the end of today you can

  • define index date, look-back, wash-out and observability, and draw the timeline
  • validated four diabetes definitions and two CKD definitions, and can explain sensitivity and PPV
  • explain why one claim is not enough, and why CKD definitions miss early disease
  • check coverage during every wash-out, and I can explain the spike in new users at 65
  • know why incidence is biased in the first and last years of the data

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:35
5.1 The vocabulary of a cohort
0:35–1:25
5.2 Case definitions for diabetes
1:25–1:40
Break
1:40–2:15
5.3 Case definitions for kidney disease
2:15–3:00
5.4 New users and look-back windows
3:00–3:15
Break
3:15–3:40
5.5 The new users who weren't
3:40–4:40
5.6 Mini-project: new cases of diabetes per year
4:40–5:00
5.7 Save your work
5:00–5:30
Bloc français

In this lesson

5.1 The vocabulary of a cohort (35 min)

          look-back (baseline) window          index date             follow-up
   |---------------- 365 days ----------------|--------------------------------------------->
   characteristics are measured here           cohort entry           outcomes are counted here
   (and the wash-out is checked here)          (time zero)            until outcome, death, move or end of data
TermMeaningExample in this course
Case definitionThe rule, in codes, that says a person has a conditionOntario diabetes definition: 1 hospital stay with diabetes, or 2 physician claims within 2 years
Index dateThe day follow-up starts (time zero)1 January 2025, or the date of a first Renavex fill
Look-back windowThe period before the index date where you measure characteristics365 days before index
Wash-outA look-back with nothing in it: no earlier use of the drug, no earlier diagnosisNo SGLT2 claim in the 365 days before
ObservabilityWhether the person could have had a record in the windowRegistered and on a public drug plan all 365 days
Incident / prevalentNew in the period, or already presentFirst diabetes record in 2023 vs diagnosed in 2015

The last row of the vocabulary decides how much the wash-out is worth. A wash-out with no records means nothing if the person could not have had records in it.

Validation. How accurate is a case definition? In real research you compare it with a reference standard, usually primary care charts or a clinical registry. The answer is reported as sensitivity (what share of true cases it finds) and positive predictive value (PPV: what share of the people it finds are true cases). Ontario's diabetes definition was validated that way against primary care charts, and it is now the standard. In this course the generator's hidden truth plays the role of the charts. corridor/truth.py exposes it, for validation exercises only.


5.2 Case definitions for diabetes (50 min)

corridor/cohort.py writes each definition as SQL. The "two claims within two years" rule uses a window function: the case date is the first claim that has an earlier one within 730 days.

def _second_claim_sql(dx_code, end, start="2019-01-01"):
    """Date of the first physician claim with `dx_code` that has an earlier one within 730 days."""
    return f"""
        SELECT person_id, min(service_date) AS case_date FROM (
            SELECT person_id, service_date,
                   lag(service_date) OVER (PARTITION BY person_id ORDER BY service_date) AS previous
            FROM fct_physician_claims
            WHERE dx_code = '{dx_code}' AND service_date BETWEEN DATE '{start}' AND DATE '{end}')
        WHERE previous IS NOT NULL AND date_diff('day', previous, service_date) <= 730
        GROUP BY person_id"""

def diabetes_case_dates(con, definition="ontario", end="2025-12-31", start="2019-01-01"):
    """person_id and the date each person first meets a diabetes definition (data from `start` to `end`).

    one_claim        1 physician claim with ICD-9 250
    two_claims       2 such claims within 2 years (date of the second)
    ontario          1 hospital stay with E11 in any position, or 2 claims within 2 years
    ontario_or_drug  the Ontario definition, or 1 public drug claim for an A10 drug
    """
    window = f"BETWEEN DATE '{start}' AND DATE '{end}'"
    one = f"""SELECT person_id, min(service_date) AS case_date FROM fct_physician_claims
              WHERE dx_code = '{DIABETES_DX9}' AND service_date {window} GROUP BY 1"""
    two = _second_claim_sql(DIABETES_DX9, end, start)
    hosp = f"""SELECT person_id, min(admit_date) AS case_date FROM fct_hospital_diagnoses
               WHERE code LIKE '{DIABETES_DX10}%' AND admit_date {window} GROUP BY 1"""
    drug = f"""SELECT person_id, min(dispense_date) AS case_date FROM fct_drug_dispensations
               WHERE atc LIKE '{DIABETES_ATC}%' AND dispense_date {window} GROUP BY 1"""
    parts = {"one_claim": [one], "two_claims": [two], "ontario": [two, hosp], "ontario_or_drug": [two, hosp, drug]}
    union = "\nUNION ALL\n".join(parts[definition])
    return f"SELECT person_id, min(case_date) AS case_date FROM ({union}) GROUP BY person_id"
def validate(con, found_sql, truth_sql, population_sql):
    """Compare a definition with the truth in a population: counts and accuracy measures."""
    tp, fp, fn, tn = con.sql(f"""
        WITH pop AS ({population_sql}), found AS ({found_sql}), truth AS ({truth_sql})
        SELECT count_if(f.person_id IS NOT NULL AND t.person_id IS NOT NULL),
               count_if(f.person_id IS NOT NULL AND t.person_id IS NULL),
               count_if(f.person_id IS NULL AND t.person_id IS NOT NULL),
               count_if(f.person_id IS NULL AND t.person_id IS NULL)
        FROM pop p LEFT JOIN found f USING (person_id) LEFT JOIN truth t USING (person_id)""").fetchall()[0]
    n = tp + fp + fn + tn
    return {
        "found": tp + fp, "true_cases": tp + fn,
        "sensitivity": tp / (tp + fn) if tp + fn else float("nan"),
        "specificity": tn / (tn + fp) if tn + fp else float("nan"),
        "ppv": tp / (tp + fp) if tp + fp else float("nan"),
        "npv": tn / (tn + fn) if tn + fn else float("nan"),
        "prevalence_found": (tp + fp) / n, "prevalence_true": (tp + fn) / n,
    }
"""Day 5.2-5.3: how accurate are case definitions for diabetes and CKD?

Population: everyone alive and registered on 2024-12-31. Data: 2019-2024 claims.
Truth: the hidden health states (a stand-in for a chart-review validation study).
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor import truth  # noqa: E402
from corridor.cohort import ckd_case_dates, diabetes_case_dates, validate  # noqa: E402
from corridor.db import warehouse  # noqa: E402

con = warehouse()
truth.register(con)
END = "2024-12-31"
POP = f"""SELECT person_id, province,
                 CASE WHEN age_on(birth_date, DATE '{END}') >= 66 THEN '66+' ELSE '18-65' END AS age_group
          FROM dim_person
          WHERE registry_start <= DATE '{END}' AND (death_date IS NULL OR death_date > DATE '{END}')"""
TRUE_DM = f"SELECT person_id FROM truth_history WHERE diabetes_from <= DATE '{END}'"
TRUE_CKD = "SELECT person_id FROM truth_history WHERE ckd_from_year <= 2024"

def row(label, r):
    print(f"{label:<34}{r['found']:>8,}{r['true_cases']:>8,}{r['sensitivity']:>8.3f}{r['specificity']:>8.4f}"
          f"{r['ppv']:>8.3f}{100 * r['prevalence_found']:>8.2f}{100 * r['prevalence_true']:>8.2f}")

HEAD = f"{'definition':<34}{'found':>8}{'true':>8}{'sens':>8}{'spec':>8}{'ppv':>8}{'prev%':>8}{'true%':>8}"

print("--- Diabetes, all adults (data 2019-2024)")
print(HEAD)
for d in ("one_claim", "two_claims", "ontario", "ontario_or_drug"):
    row(d, validate(con, diabetes_case_dates(con, d, END), TRUE_DM, POP))

print("\n--- Diabetes by age group: does adding drug claims help?")
print(HEAD)
for group in ("18-65", "66+"):
    pop = f"SELECT person_id FROM ({POP}) WHERE age_group = '{group}'"
    for d in ("ontario", "ontario_or_drug"):
        row(f"{d}, age {group}", validate(con, diabetes_case_dates(con, d, END), TRUE_DM, pop))

print("\n--- Diabetes, Ontario definition, by province")
print(HEAD)
for prov in ("ON", "QC"):
    pop = f"SELECT person_id FROM ({POP}) WHERE province = '{prov}'"
    row(f"ontario, {prov}", validate(con, diabetes_case_dates(con, "ontario", END), TRUE_DM, pop))

print("\n--- Chronic kidney disease (any stage)")
print(HEAD)
for d in ("one_claim", "two_claims_or_hospital"):
    row(d, validate(con, ckd_case_dates(con, d, END), TRUE_CKD, POP))

print("\n--- Who does the CKD definition miss? Sensitivity by true stage")
for stage in ("3a", "3b", "4", "5"):
    t = f"""SELECT h.person_id FROM truth_history h
            JOIN (SELECT person_id, ckd_stage FROM read_csv('{truth.TRUTH}/persons_truth.csv')
                  UNION ALL SELECT person_id, ckd_stage FROM read_csv('{truth.TRUTH}/persons_truth_deceased.csv'))
            USING (person_id) WHERE ckd_from_year <= 2024 AND ckd_stage = '{stage}'"""
    r = validate(con, ckd_case_dates(con, "two_claims_or_hospital", END), t, POP)
    print(f"  stage {stage:<3} true cases {r['true_cases']:>6,}   sensitivity {r['sensitivity']:.3f}")
--- Diabetes, all adults (data 2019-2024)
definition                           found    true    sens    spec     ppv   prev%   true%
one_claim                           50,292  27,867   0.995  0.8973   0.551   20.32   11.26
two_claims                          28,110  27,867   0.976  0.9958   0.968   11.36   11.26
ontario                             28,239  27,867   0.981  0.9958   0.968   11.41   11.26
ontario_or_drug                     28,564  27,867   0.992  0.9958   0.968   11.54   11.26

--- Diabetes by age group: does adding drug claims help?
definition                           found    true    sens    spec     ppv   prev%   true%
ontario, age 18-65                  12,598  12,214   0.978  0.9963   0.948    6.68    6.48
ontario_or_drug, age 18-65          12,664  12,214   0.984  0.9963   0.949    6.71    6.48
ontario, age 66+                    15,641  15,653   0.982  0.9939   0.983   26.54   26.56
ontario_or_drug, age 66+            15,900  15,653   0.999  0.9939   0.983   26.98   26.56

--- Diabetes, Ontario definition, by province
definition                           found    true    sens    spec     ppv   prev%   true%
ontario, ON                         17,547  17,318   0.982  0.9960   0.969   11.42   11.28
ontario, QC                         10,692  10,549   0.978  0.9955   0.965   11.38   11.23

Read the first block:

  • One claim finds 99.5% of true cases, but only 55.1% of the people it finds have diabetes. It nearly doubles the prevalence (20.3% vs 11.3%), because rule-out visits are billed with the code being ruled out.
  • Two claims within two years keeps almost all the sensitivity (97.6%), and the PPV jumps to 96.8%. A second claim is strong evidence.
  • Adding hospital diagnoses (the Ontario definition) finds a few more cases at the same PPV.
  • Adding drug claims helps only where drug claims exist. At 66+ (everyone on a public plan in Ontario, most in Quebec), sensitivity reaches 99.9%. Under 66, it barely moves (Day 2's coverage gap again).

The definition works equally well in both provinces. That matters for Module 4, where you will compare them.

Try it (10 min). How much history does a definition need? Validate two_claims and ontario using only 2021–2024, 2023–2024 and 2024 data.

Solution
"""Day 5 exercise: what if we only had two years of data (2023-2024)?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor import truth  # noqa: E402
from corridor.cohort import diabetes_case_dates, validate  # noqa: E402
from corridor.db import warehouse  # noqa: E402

con = warehouse()
truth.register(con)
END = "2024-12-31"
POP = f"""SELECT person_id FROM dim_person
          WHERE registry_start <= DATE '{END}' AND (death_date IS NULL OR death_date > DATE '{END}')"""
TRUE_DM = f"SELECT person_id FROM truth_history WHERE diabetes_from <= DATE '{END}'"
print(f"{'data window':<26}{'definition':<18}{'found':>8}{'sens':>8}{'ppv':>8}")
for start in ("2019-01-01", "2021-01-01", "2023-01-01", "2024-01-01"):
    for d in ("two_claims", "ontario"):
        r = validate(con, diabetes_case_dates(con, d, END, start), TRUE_DM, POP)
        print(f"{start[:4]}-2024{'':<17}{d:<18}{r['found']:>8,}{r['sensitivity']:>8.3f}{r['ppv']:>8.3f}")
data window               definition           found    sens     ppv
2019-2024                 two_claims          28,110   0.976   0.968
2019-2024                 ontario             28,239   0.981   0.968
2021-2024                 two_claims          27,609   0.976   0.985
2021-2024                 ontario             27,741   0.980   0.985
2023-2024                 two_claims          27,006   0.969   1.000
2023-2024                 ontario             27,216   0.977   1.000
2024-2024                 two_claims          23,870   0.857   1.000
2024-2024                 ontario             24,700   0.886   1.000

With one year of data, the Ontario definition misses 11% of people with diabetes. Someone with well-controlled diabetes may see their doctor about it once a year, so they never get two claims within one year. PPV rises with shorter windows only because there are fewer years in which two stray rule-out claims can pile up. The usual choice in Canadian studies is at least two years of history.


5.3 Case definitions for kidney disease (35 min)

def ckd_case_dates(con, definition="two_claims_or_hospital", end="2025-12-31"):
    """person_id and the first date a CKD definition is met.

    one_claim               1 physician claim with ICD-9 585
    two_claims_or_hospital  2 such claims within 2 years, or 1 hospital stay with N18/Z491, or a dialysis fee
    """
    one = f"""SELECT person_id, min(service_date) AS case_date FROM fct_physician_claims
              WHERE dx_code = '{CKD_DX9}' AND service_date <= DATE '{end}' GROUP BY 1"""
    two = _second_claim_sql(CKD_DX9, end)
    hosp = f"""SELECT person_id, min(admit_date) AS case_date FROM fct_hospital_diagnoses
               WHERE (code LIKE '{CKD_DX10}%' OR code = '{DIALYSIS_DX10}') AND admit_date <= DATE '{end}'
               GROUP BY 1"""
    fees = ", ".join(f"'{f}'" for f in DIALYSIS_FEES)
    dial = f"""SELECT person_id, min(service_date) AS case_date FROM fct_physician_claims
               WHERE fee_code IN ({fees}) AND service_date <= DATE '{end}' GROUP BY 1"""
    parts = {"one_claim": [one], "two_claims_or_hospital": [two, hosp, dial]}
    union = "\nUNION ALL\n".join(parts[definition])
    return f"SELECT person_id, min(case_date) AS case_date FROM ({union}) GROUP BY person_id"
--- Chronic kidney disease (any stage)
definition                           found    true    sens    spec     ppv   prev%   true%
one_claim                           19,680  14,522   0.937  0.9739   0.691    7.95    5.87
two_claims_or_hospital              12,827  14,522   0.872  0.9993   0.987    5.18    5.87

--- Who does the CKD definition miss? Sensitivity by true stage
  stage 3a  true cases  7,298   sensitivity 0.792
  stage 3b  true cases  4,052   sensitivity 0.928
  stage 4   true cases  2,177   sensitivity 0.978
  stage 5   true cases    995   sensitivity 0.987

Kidney disease is harder. Two claims or a hospital diagnosis gives an excellent PPV (98.7%) but misses 13% of cases. The misses are concentrated in early disease: only 79% of stage 3a cases are found, against 98–99% at stages 4 and 5. Early CKD is mostly an abnormal lab result, followed in primary care without a CKD code on the claim. Canadian CKD studies therefore use laboratory eGFR values where they can. You will add lab data in Module 2.

Why it matters at work: Renavex's indication is CKD in type 2 diabetes. A claims-only definition makes the study population sicker than the label population, so effects and costs will not transfer directly. A CDA-AMC reviewer would raise this.

Where you'll meet this: the "population" section of every RWE protocol · generalizability arguments · budget impact models (how many eligible patients?)


5.4 New users and look-back windows (45 min)

To compare two drugs fairly (Module 3), you follow people from the day they start a drug: the new-user design. People who have taken a drug for years are survivors of its early side effects and committed to it. Mixing them with starters biases every comparison.

So who is a new SGLT2 user in 2025? Index date = first SGLT2 claim in 2025. Wash-out = no SGLT2 claim in the 365 days before. And observability: was the person on a public drug plan for all of those 365 days?

"""Day 5: look-back windows - was the person observable before the index date?"""

def covered_days_sql(index_table, days=365):
    """Days of public drug plan coverage in the `days` before each person's index date.

    index_table must have person_id and index_date.
    """
    return f"""
        SELECT i.person_id,
               coalesce(sum(date_diff('day',
                    greatest(e.start_date, i.index_date - INTERVAL {days} DAY)::DATE,
                    least(coalesce(e.end_date, i.index_date - INTERVAL 1 DAY), i.index_date - INTERVAL 1 DAY)::DATE) + 1)
                    FILTER (e.person_id IS NOT NULL), 0) AS covered_days
        FROM {index_table} i
        LEFT JOIN stg_drug_plan_eligibility e
          ON e.person_id = i.person_id
         AND e.start_date <= i.index_date - INTERVAL 1 DAY
         AND coalesce(e.end_date, DATE '9999-12-31') >= i.index_date - INTERVAL {days} DAY
        GROUP BY i.person_id"""
"""Day 5.4: new users of SGLT2 inhibitors in 2025 - and how a look-back can fool you."""

import os
import sys

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

con = warehouse()
truth.register(con)

# index date = first SGLT2 claim in 2025; wash-out = no SGLT2 claim in the 365 days before
con.execute("""
    CREATE TEMP TABLE first_2025 AS
    SELECT r.person_id, any_value(r.province) AS province, min(r.dispense_date) AS index_date
    FROM fct_drug_dispensations r
    WHERE r.atc LIKE 'A10BK%' AND r.dispense_year = 2025
    GROUP BY r.person_id""")
con.execute("""
    CREATE TEMP TABLE candidates AS
    SELECT f.*, age_on(p.birth_date, f.index_date) AS age,
           NOT EXISTS (SELECT 1 FROM fct_drug_dispensations r
                       WHERE r.person_id = f.person_id AND r.atc LIKE 'A10BK%'
                         AND r.dispense_date >= f.index_date - INTERVAL 365 DAY
                         AND r.dispense_date < f.index_date)                     AS no_prior_claim
    FROM first_2025 f JOIN dim_person p USING (person_id)""")
con.execute(f"CREATE TEMP TABLE cov AS {covered_days_sql('candidates')}")
con.execute("""
    CREATE TEMP TABLE users AS
    SELECT c.*, v.covered_days,
           EXISTS (SELECT 1 FROM truth_drug_starts t
                   WHERE t.person_id = c.person_id AND t.ingredient IN ('empagliflozin', 'dapagliflozin')
                     AND t.start_date > c.index_date - INTERVAL 365 DAY
                     AND t.start_date <= c.index_date)                           AS truly_new
    FROM candidates c JOIN cov v USING (person_id)""")

print("--- 'New users' in 2025 under three definitions (truth: really started in the past year)")
show(con, """
    SELECT 'A: no SGLT2 claim in the 365 days before' AS definition,
           count(*) AS people, count_if(truly_new) AS truly_new,
           round(100 * avg(truly_new::INT), 1) AS pct_truly_new
    FROM users WHERE no_prior_claim
    UNION ALL
    SELECT 'B: A + on a public plan all 365 days before', count(*), count_if(truly_new),
           round(100 * avg(truly_new::INT), 1)
    FROM users WHERE no_prior_claim AND covered_days >= 365
    UNION ALL
    SELECT 'C: B + age 66 or older (Ontario-style)', count(*), count_if(truly_new),
           round(100 * avg(truly_new::INT), 1)
    FROM users WHERE no_prior_claim AND covered_days >= 365 AND age >= 66""")

print("\n--- Definition B by province")
show(con, """
    SELECT province, count(*) AS people, round(100 * avg(truly_new::INT), 1) AS pct_truly_new
    FROM users WHERE no_prior_claim AND covered_days >= 365 GROUP BY 1 ORDER BY 1""")
--- 'New users' in 2025 under three definitions (truth: really started in the past year)
                                 definition  people  truly_new  pct_truly_new
   A: no SGLT2 claim in the 365 days before    1183       1052           88.9
B: A + on a public plan all 365 days before    1025       1014           98.9
     C: B + age 66 or older (Ontario-style)     890        879           98.8

--- Definition B by province
province  people  pct_truly_new
      ON     625           98.7
      QC     400           99.3

Definition A, a wash-out with no observability check, calls 1,183 people new users, and 11% of them are not. Requiring a full year on a public plan (B) brings the share of true new users to 98.9%. The remaining errors come from people who had a gap in filling their prescriptions longer than a year.


5.5 The new users who weren't (25 min)

Bug of the day. Where do definition A's false new users come from? Count them by age on the index date:

"""Day 5 bug of the day: 'new users' who are really old users we could not see.

Count people whose first public SGLT2 claim in 2025 had no claim in the year before
(definition A only), by age on the index date.
"""

import os
import sys

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

con = warehouse()
truth.register(con)
show(con, """
    WITH first_2025 AS (
        SELECT person_id, any_value(province) AS province, min(dispense_date) AS index_date
        FROM fct_drug_dispensations WHERE atc LIKE 'A10BK%' AND dispense_year = 2025 GROUP BY 1),
    naive AS (
        SELECT f.*, age_on(p.birth_date, f.index_date) AS age,
               EXISTS (SELECT 1 FROM truth_drug_starts t
                       WHERE t.person_id = f.person_id AND t.ingredient IN ('empagliflozin', 'dapagliflozin')
                         AND t.start_date > f.index_date - INTERVAL 365 DAY
                         AND t.start_date <= f.index_date) AS truly_new
        FROM first_2025 f JOIN dim_person p USING (person_id)
        WHERE NOT EXISTS (SELECT 1 FROM fct_drug_dispensations r
                          WHERE r.person_id = f.person_id AND r.atc LIKE 'A10BK%'
                            AND r.dispense_date >= f.index_date - INTERVAL 365 DAY
                            AND r.dispense_date < f.index_date))
    SELECT age,
           count_if(province = 'ON') AS ontario_new_users, count_if(province = 'ON' AND truly_new) AS ontario_truly_new,
           count_if(province = 'QC') AS quebec_new_users, count_if(province = 'QC' AND truly_new) AS quebec_truly_new
    FROM naive WHERE age BETWEEN 60 AND 70 GROUP BY age ORDER BY age""")
 age  ontario_new_users  ontario_truly_new  quebec_new_users  quebec_truly_new
  60                  2                  2                 3                 3
  61                  3                  3                 3                 3
  62                  2                  2                 9                 9
  63                  1                  1                 5                 5
  64                  1                  1                 8                 8
  65                123                 26                37                14
  66                 24                 24                17                17
  67                 22                 21                13                13
  68                 23                 23                11                11
  69                 30                 30                10                10
  70                 33                 33                16                16

At 65, Ontario's "new users" jump from a handful to 123, and only 26 of them really started. These are people who took an SGLT2 inhibitor for years through a workplace plan. At 65 they moved to ODB, and their first public claim looks like a new start. Quebec shows the same jump, smaller, because many Quebecers aged 25–64 are already on RAMQ.

This is why Ontario drug studies so often start at age 66. One year after ODB eligibility begins, everyone has a full year of observable drug history. The rule generalizes: a wash-out window is only as good as the person's coverage during it.


5.6 Mini-project: new cases of diabetes per year (60 min)

Count new (incident) cases of diabetes per year from 2019 to 2025. A person's incidence date is their first diabetes record of any kind (claim, hospital diagnosis or A10 drug), among people who meet the Ontario definition. Compare three versions with the truth: no wash-out, and wash-outs of one and two years (the person must have been observable for that long before their first record).

"""Day 5 mini-project: new cases of diabetes per year - and why the first years lie.

A person's 'incidence date' is their first diabetes record (claim 250, hospital E11 or an
A10 drug) among people who meet the Ontario definition. A wash-out of W years counts the
case only if the person was observable for W years before that first record.
"""

import os
import sys

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

con = warehouse()
truth.register(con)
con.execute(f"CREATE TEMP TABLE cases AS {diabetes_case_dates(con, 'ontario', '2025-12-31')}")
con.execute("""
    CREATE TEMP TABLE first_record AS
    SELECT c.person_id, min(d) AS first_date
    FROM cases c JOIN (
        SELECT person_id, service_date AS d FROM fct_physician_claims WHERE dx_code = '250'
        UNION ALL SELECT person_id, admit_date FROM fct_hospital_diagnoses WHERE code LIKE 'E11%'
        UNION ALL SELECT person_id, dispense_date FROM fct_drug_dispensations WHERE atc LIKE 'A10%') r
      USING (person_id)
    GROUP BY c.person_id""")
con.execute("""
    CREATE TEMP TABLE inc AS
    SELECT f.person_id, f.first_date, year(f.first_date) AS year,
           date_diff('day', greatest(p.registry_start, DATE '2019-01-01'), f.first_date) AS lookback_days
    FROM first_record f JOIN dim_person p USING (person_id)""")

show(con, """
    WITH years AS (SELECT unnest(range(2019, 2026)) AS year),
    true_new AS (
        SELECT year(t.diabetes_from) AS year, count(*) AS n
        FROM truth_history t JOIN dim_person p USING (person_id)
        WHERE t.diabetes_from >= p.registry_start
          AND (p.death_date IS NULL OR t.diabetes_from <= p.death_date)
        GROUP BY 1)
    SELECT y.year,
           coalesce(t.n, 0)                                                          AS truly_new,
           (SELECT count(*) FROM inc WHERE inc.year = y.year)                          AS no_washout,
           CASE WHEN y.year >= 2020 THEN
               (SELECT count(*) FROM inc WHERE inc.year = y.year AND lookback_days >= 365) END AS washout_1y,
           CASE WHEN y.year >= 2021 THEN
               (SELECT count(*) FROM inc WHERE inc.year = y.year AND lookback_days >= 730) END AS washout_2y
    FROM years y LEFT JOIN true_new t USING (year) ORDER BY y.year""")
 year  truly_new  no_washout  washout_1y  washout_2y
 2019       2303       17758        <NA>        <NA>
 2020       2049        3102        2914        <NA>
 2021       2441        3105        2901        2865
 2022       2779        3203        2944        2915
 2023       3469        3637        3323        3292
 2024       4119        3739        3461        3372
 2025       4141        3122        3118        3082

What it shows:

  • Without a wash-out, the first year is nonsense. 17,758 "new" cases in 2019, against 2,303 real ones. Everyone with long-standing diabetes has their first record in 2019, because that is when the data start.
  • Wash-outs help but do not fix it. Even with two years, 2021 shows 2,865 cases against 2,441 real ones. Some people with long-standing diabetes go more than two years without a diabetes claim.
  • The last year is too low (3,082 against 4,141). People diagnosed late in 2025 have not yet had a second claim. A definition that needs two events lags the truth.
  • The middle years are close. For incidence, use the middle of your data. Report the wash-out you used, and expect the first and last years to be biased.

5.7 Save your work

python -m pytest -q
git add .
git commit -m "Day 5: case definitions, new users, incidence"

Day 5 checklist

  • I can define index date, look-back, wash-out and observability, and draw the timeline
  • I validated four diabetes definitions and two CKD definitions, and can explain sensitivity and PPV
  • I can explain why one claim is not enough, and why CKD definitions miss early disease
  • I check coverage during every wash-out, and I can explain the spike in new users at 65
  • I know why incidence is biased in the first and last years of the data