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

The Codes: Diagnoses, Interventions, Drugs, Fees and Case Mix

Administrative data speak in codes. A hospital stay is a diagnosis code, an intervention code, a case-mix group and a resource weight. A doctor's visit is a fee code and a three-digit diagnosis. A prescription is a DIN. Today you learn to read each system, connect codes across systems, and turn a resource weight into dollars. You also meet two bugs that have quietly ruined real studies. The day ends with a code list, the first building block of the case definitions on Day 5.

▶
Video for Day 3 coming soon

By the end of today you can

  • read an ICD-10 code, an ICD-9 claim code, a CCI code, a fee code, a DIN and an ATC code, and say where each comes from
  • know the difference between the MRDx and other diagnoses, and I unpivot diagnosis columns
  • cost a hospital stay as RIW × CPWC and explain why cost per day misleads
  • check every code pattern against the lookup, and read every code column as text
  • My code list finds people in three sources, and I can explain why the sources disagree

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:45
3.1 Diagnoses and interventions in hospital abstracts
0:45–1:25
3.2 Physician claims: diagnosis and fee codes
1:25–1:40
Break
1:40–2:25
3.3 Drugs: DIN and ATC
2:25–3:05
3.4 What does a hospital stay cost?
3:05–3:20
Break
3:20–3:45
3.5 Two code bugs
3:45–4:45
3.6 Mini-project: one code list, three sources
4:45–5:00
3.7 Save your work
5:00–5:30
Bloc français

In this lesson

The systems at a glance

SystemWhereWhat it codesShape in this course
ICD-10-CAHospital and ED abstractsDiagnosesLetter + digits, no dot: E112, N184
ICD-9 (3-digit)Physician claims, Ontario and QuebecThe visit's main diagnosisThree digits as text: 250, 585
CCIHospital abstractsInterventions1.PZ.21.^^ (section.group.intervention.qualifiers)
Fee codesPhysician claimsWhat the doctor was paid forOHIP A007, K030; course codes CH…, Q…
DINDrug claimsOne specific product8 digits as text: 09900066
ATCDrug lookupGroups of drugsA10BK03 (5 levels)
CMG and RIWHospital abstractsGroups of similar stays, and their expected resource useCH01, RIW 1.4554

ICD-10-CA is Canada's version of the WHO's ICD-10, maintained by CIHI. It extends some WHO codes with extra characters (diabetes is an example). This course uses WHO-level codes to keep the tables short. For real studies, take code lists from CIHI's classification and from published, validated algorithms.


3.1 Diagnoses and interventions in hospital abstracts (45 min)

Each hospital abstract has one most responsible diagnosis (MRDx): the condition that accounted for most of the stay. It then lists other diagnoses. In real DAD data each of these has a diagnosis type (for example, a comorbidity present before admission, or one that arose after admission). Corridor Health keeps only their position: dx2 to dx4.

"""Day 3.1: ICD-10 codes in hospital discharge abstracts."""

import os
import sys

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

con = connect()

print("--- Ten most common most-responsible diagnoses (MRDx)")
show(con, """
    SELECT h.mrdx, i.description, count(*) AS stays
    FROM hospital_discharges h LEFT JOIN icd10 i ON i.code = h.mrdx
    GROUP BY ALL ORDER BY stays DESC, h.mrdx LIMIT 10""")

print("\n--- Stays by ICD-10 chapter (first letter of the MRDx)")
show(con, """
    SELECT left(mrdx, 1) AS chapter, c.name, count(*) AS stays
    FROM hospital_discharges h LEFT JOIN icd10_chapters c ON c.chapter = left(h.mrdx, 1)
    GROUP BY ALL ORDER BY stays DESC""")

print("\n--- Diabetes in hospital: main reason or one of the other diagnoses?")
show(con, """
    SELECT count(*)                                                        AS all_stays,
           count_if(mrdx LIKE 'E11%')                                      AS mrdx_type2_diabetes,
           count_if(mrdx LIKE 'E11%' OR dx2 LIKE 'E11%' OR dx3 LIKE 'E11%' OR dx4 LIKE 'E11%')
                                                                           AS any_type2_diabetes,
           count(DISTINCT person_id) FILTER (mrdx LIKE 'E11%')             AS people_mrdx,
           count(DISTINCT person_id) FILTER (mrdx LIKE 'E11%' OR dx2 LIKE 'E11%'
                                            OR dx3 LIKE 'E11%' OR dx4 LIKE 'E11%') AS people_any
    FROM hospital_discharges""")

print("\n--- Same question with an unpivoted (long) diagnosis table")
show(con, """
    WITH dx AS (
        UNPIVOT (SELECT abstract_id, person_id, mrdx, dx2, dx3, dx4 FROM hospital_discharges)
        ON mrdx, dx2, dx3, dx4 INTO NAME position VALUE code)
    SELECT position, count(*) AS rows, count_if(code LIKE 'E11%') AS type2_diabetes,
           count_if(code LIKE 'N18%') AS ckd
    FROM dx GROUP BY 1 ORDER BY 1""")

print("\n--- Interventions (CCI-style course codes) and their section")
show(con, """
    SELECT h.main_intervention, c.description, s.name AS section, count(*) AS stays
    FROM hospital_discharges h
    JOIN cci c ON c.code = h.main_intervention
    JOIN cci_sections s ON s.section = c.section
    GROUP BY ALL ORDER BY stays DESC""")
--- Ten most common most-responsible diagnoses (MRDx)
mrdx                                                   description  stays
J189                                        Pneumonia, unspecified   5781
R074                                       Chest pain, unspecified   4360
N390                   Urinary tract infection, site not specified   3834
I500                                      Congestive heart failure   2453
A419                                           Sepsis, unspecified   2290
S720                                     Fracture of neck of femur   2067
K358                     Acute appendicitis, other and unspecified   1570
J441 Chronic obstructive pulmonary disease with acute exacerbation   1082
I639                              Cerebral infarction, unspecified   1078
N179                             Acute kidney failure, unspecified    905

--- Stays by ICD-10 chapter (first letter of the MRDx)
chapter                                                                          name  stays
      J                                  Diseases of the respiratory system (J00-J99)   6863
      N                                Diseases of the genitourinary system (N00-N99)   5728
      R                               Symptoms, signs and abnormal findings (R00-R99)   4360
      I                                  Diseases of the circulatory system (I00-I99)   3585
      A                           Certain infectious and parasitic diseases (A00-B99)   2290
      S Injury, poisoning and certain other consequences of external causes (S00-T98)   2067
      K                                    Diseases of the digestive system (K00-K93)   1570
      E                       Endocrine, nutritional and metabolic diseases (E00-E90)   1156

--- Diabetes in hospital: main reason or one of the other diagnoses?
 all_stays  mrdx_type2_diabetes  any_type2_diabetes  people_mrdx  people_any
     27619                 1156                7323         1129        6155

--- Same question with an unpivoted (long) diagnosis table
position  rows  type2_diabetes  ckd
     dx2 13973            6167 1210
     dx3  5947               0 2950
     dx4  2411               0    0
    mrdx 27619            1156  989

--- Interventions (CCI-style course codes) and their section
main_intervention                                         description                                          section  stays
       1.VA.53.^^        Implantation of hip prosthesis (course code) Physical/physiological therapeutic interventions   2067
       1.NT.87.^^                  Excision of appendix (course code) Physical/physiological therapeutic interventions   1570
       1.PZ.21.^^                              Dialysis (course code) Physical/physiological therapeutic interventions    189
       3.IP.10.^^ X-ray of heart with coronary arteries (course code)                 Diagnostic imaging interventions    164
       1.IJ.50.^^         Dilation of coronary arteries (course code) Physical/physiological therapeutic interventions     54

Three habits to build now:

  1. Always join to the lookup, so that you read "Congestive heart failure" rather than I500.
  2. Decide which positions count. Only 1,156 stays have type 2 diabetes as the main reason, but 7,323 mention it somewhere: six times as many. "Hospitalized for diabetes" and "hospitalized with diabetes" are different questions.
  3. Unpivot wide diagnosis columns into a long table (one row per stay and diagnosis). Every later query then becomes a simple filter.

Interventions use CCI, the Canadian Classification of Health Interventions. The first character is the section (1 = therapeutic, 2 = diagnostic, 3 = diagnostic imaging, and so on). The next characters name the body system, the type of intervention, and qualifiers for approach and device. The course's CCI-style codes are illustrative. Real CCI codes are longer and come from CIHI.


3.2 Physician claims: diagnosis and fee codes (40 min)

Physician claims in both provinces carry one three-digit ICD-9-based diagnosis code, the main reason for the visit. The doctor picks it when billing, and only one fits on a claim. So a visit for diabetes and hypertension shows up as one or the other.

The fee code says what the province paid for. In Ontario, A007 is an intermediate assessment by a family doctor, and K030 a diabetic management assessment. The course fees are invented. In real work, look codes up in the OHIP Schedule of Benefits or RAMQ's billing manuals, and check the version for your study years. Codes and fees change.

"""Day 3.2: diagnosis and fee codes in physician claims."""

import os
import sys

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

con = connect()

print("--- Diagnosis codes on physician claims (3-digit ICD-9)")
show(con, """
    SELECT c.dx_code, d.description, count(*) AS claims, count(DISTINCT person_id) AS people
    FROM physician_claims c LEFT JOIN icd9_dx d USING (dx_code)
    GROUP BY ALL ORDER BY claims DESC""")

print("\n--- Fee codes: what was billed and paid in 2024")
show(con, """
    SELECT c.province, c.fee_code, f.description, count(*) AS claims,
           round(sum(c.paid_amount)) AS paid, f.source
    FROM physician_claims c JOIN fee_codes f USING (province, fee_code)
    GROUP BY ALL ORDER BY c.province, paid DESC""")

print("\n--- Who billed: claims and payments by specialty")
show(con, """
    SELECT specialty, count(*) AS claims, round(sum(paid_amount)) AS paid,
           round(100 * sum(paid_amount) / sum(sum(paid_amount)) OVER (), 1) AS pct_paid
    FROM physician_claims GROUP BY 1 ORDER BY paid DESC""")

print("\n--- The same disease in two coding systems: chronic kidney disease")
show(con, """
    SELECT 'physician claims, ICD-9 585' AS source, count(DISTINCT person_id) AS people
    FROM physician_claims WHERE dx_code = '585'
    UNION ALL
    SELECT 'hospital, ICD-10 N18 (any position)', count(DISTINCT person_id)
    FROM hospital_discharges
    WHERE mrdx LIKE 'N18%' OR dx2 LIKE 'N18%' OR dx3 LIKE 'N18%' OR dx4 LIKE 'N18%'
    UNION ALL
    SELECT 'both', count(*) FROM (
        SELECT person_id FROM physician_claims WHERE dx_code = '585'
        INTERSECT
        SELECT person_id FROM hospital_discharges
        WHERE mrdx LIKE 'N18%' OR dx2 LIKE 'N18%' OR dx3 LIKE 'N18%' OR dx4 LIKE 'N18%')""")
--- Diagnosis codes on physician claims (3-digit ICD-9)
dx_code                                                    description  claims  people
    460                            Acute nasopharyngitis (common cold)  155302  109525
    780                                               General symptoms  141216  102433
    724                        Other and unspecified disorders of back  127165   94810
    585                                         Chronic kidney disease  120370   11690
    250                                              Diabetes mellitus  101218   27648
    300                 Anxiety, dissociative and somatoform disorders   99518   78942
    786 Symptoms involving respiratory system and other chest symptoms   99058   78650
    401                                         Essential hypertension   95101   51347
    311                  Depressive disorder, not elsewhere classified   85378   69697
    428                                                  Heart failure   24706    5444
    496           Chronic airway obstruction, not elsewhere classified    8848    4192
    410                                    Acute myocardial infarction     279     215

--- Fee codes: what was billed and paid in 2024
province fee_code                                                  description  claims     paid                source
      ON     A007                                      Intermediate assessment  311982 12479280 OHIP code, course fee
      ON     A003                                           General assessment  101556  9140040 OHIP code, course fee
      ON    CH103                                 Dialysis session supervision   58152  5524440           course code
      ON     A001                                             Minor assessment  133252  3331300 OHIP code, course fee
      ON     K030                               Diabetic management assessment   30920  1391400 OHIP code, course fee
      ON    CH102                                   Specialist follow-up visit   15469  1160175           course code
      ON    CH101                                      Specialist consultation    5057   809120           course code
      QC    Q0001                            Visite ordinaire (ordinary visit)  252969  8095008           course code
      QC    Q0002                        Examen complet (complete examination)   61904  5261840           course code
      QC    Q0103             Supervision d'hémodialyse (dialysis supervision)   35885  3229650           course code
      QC    Q0003 Suivi de clientèle vulnérable (vulnerable patient follow-up)   38744  1937200           course code
      QC    Q0102          Visite de suivi, spécialiste (specialist follow-up)    9230   646100           course code
      QC    Q0101    Consultation par un spécialiste (specialist consultation)    3039   455850           course code

--- Who billed: claims and payments by specialty
        specialty  claims     paid  pct_paid
  family_medicine  931327 41636068      77.9
       nephrology  105637  9847805      18.4
internal_medicine   10558   988930       1.8
       cardiology   10637   988600       1.8

--- The same disease in two coding systems: chronic kidney disease
                             source  people
        physician claims, ICD-9 585   11690
hospital, ICD-10 N18 (any position)    4185
                               both    3305

What to notice:

  • Dialysis dominates kidney claims. Code 585 has 120,370 claims but only 11,690 people, because people on dialysis generate a supervision claim three times a week. That is why nephrology gets 18.4% of physician payments.
  • Codes do not map one-to-one between systems. 11,690 people have an ICD-9 585 claim and 4,185 have an ICD-10 N18 hospital diagnosis, but only 3,305 have both. Each source finds people the other misses (3.6 builds on this).
  • Not every doctor bills fee-for-service. In real data, doctors paid by salary or alternative plans may submit "shadow billing" claims, or none at all. Visit counts then understate care for their patients, and the gap differs by region and specialty.

3.3 Drugs: DIN and ATC (45 min)

Health Canada assigns each drug product a Drug Identification Number (DIN): eight digits that identify one manufacturer's product at one strength in one form. Metformin 500 mg and metformin 850 mg have different DINs. So does each generic version. Provincial plans also create pseudo-DINs (PINs) for products without one, which this course leaves out.

To group products, you use the WHO's Anatomical Therapeutic Chemical (ATC) classification. It has five levels:

A        Alimentary tract and metabolism            (level 1, anatomical group)
A10      Drugs used in diabetes                     (level 2, therapeutic group)
A10B     Blood glucose lowering drugs, excl. insulins (level 3)
A10BK    SGLT2 inhibitors                           (level 4, chemical subgroup)
A10BK03  empagliflozin                              (level 5, substance)

So atc LIKE 'A10BK%' means "any SGLT2 inhibitor", whatever the product, strength or manufacturer.

"""Day 3.3: DINs identify products; ATC codes group them."""

import os
import sys

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

con = connect()

print("--- The ATC path of one product: empagliflozin")
show(con, """
    SELECT a.level, a.atc, a.name
    FROM drugs d JOIN atc a ON starts_with(d.atc, a.atc)
    WHERE d.ingredient = 'empagliflozin' ORDER BY a.level""")

print("\n--- 2024 public drug claims grouped at ATC level 4 (chemical subgroup)")
show(con, """
    SELECT left(d.atc, 5) AS atc4, a.name, count(*) AS claims,
           count(DISTINCT r.person_id) AS people, round(sum(r.total_cost)) AS total_cost
    FROM drug_claims r JOIN drugs d USING (din) JOIN atc a ON a.atc = left(d.atc, 5)
    GROUP BY ALL ORDER BY total_cost DESC""")

print("\n--- Everything under 'Drugs used in diabetes' (A10), by plan")
show(con, """
    SELECT r.plan_id, count(DISTINCT r.person_id) AS people, count(*) AS claims,
           round(sum(r.plan_paid)) AS plan_paid, round(sum(r.patient_paid)) AS patient_paid
    FROM drug_claims r JOIN drugs d USING (din)
    WHERE d.atc LIKE 'A10%' GROUP BY 1 ORDER BY 1""")

print("\n--- SGLT2 inhibitor users (A10BK) and what else they take")
show(con, """
    WITH sglt2 AS (SELECT DISTINCT person_id FROM drug_claims JOIN drugs USING (din)
                   WHERE atc LIKE 'A10BK%')
    SELECT d.ingredient, count(DISTINCT r.person_id) AS sglt2_users_also_on_it
    FROM drug_claims r JOIN drugs d USING (din) JOIN sglt2 USING (person_id)
    WHERE d.atc NOT LIKE 'A10BK%' GROUP BY 1 ORDER BY 2 DESC LIMIT 6""")
--- The ATC path of one product: empagliflozin
 level     atc                                               name
     1       A                    Alimentary tract and metabolism
     2     A10                             Drugs used in diabetes
     3    A10B       Blood glucose lowering drugs, excl. insulins
     4   A10BK Sodium-glucose co-transporter 2 (SGLT2) inhibitors
     5 A10BK03                                      empagliflozin

--- 2024 public drug claims grouped at ATC level 4 (chemical subgroup)
 atc4                                               name  claims  people  total_cost
A10BJ          Glucagon-like peptide-1 (GLP-1) analogues   11966    1633     6565138
A10BK Sodium-glucose co-transporter 2 (SGLT2) inhibitors   41252    5560     4522612
A10AE  Insulins and analogues for injection, long-acting   32066    4329     3213426
C09AA                              ACE inhibitors, plain  208056   28003     2795818
C10AA                       HMG CoA reductase inhibitors  164920   22151     2380011
C08CA                        Dihydropyridine derivatives  128822   17291     1643324
A10BH          Dipeptidyl peptidase 4 (DPP-4) inhibitors   25485    3475     1630927
A10BA                                         Biguanides  120068   16211     1603843
R03BB                                   Anticholinergics   15759    2091     1316481
R03AC           Selective beta-2-adrenoreceptor agonists   28649    3793      477676
A10BB                                      Sulfonylureas   21554    2952      400192
C03CA                                Sulfonamides, plain   24890    3430      258682

--- Everything under 'Drugs used in diabetes' (A10), by plan
 plan_id  people  claims  plan_paid  patient_paid
  ODB-65    8295  115017    7098421       1175908
 ODB-65L    1738   24271    1616121         48542
  ODB-SA     646    8608     544552         17216
   OHIP+      65     774      48554             0
RAMQ-PUB    6777   94018    4493365       2177760
 RAMQ-SA     713    9703     715699             0

--- SGLT2 inhibitor users (A10BK) and what else they take
      ingredient  sglt2_users_also_on_it
       metformin                    4677
        ramipril                    2989
    atorvastatin                    2444
      amlodipine                    1902
    rosuvastatin                    1740
insulin glargine                    1248

Look at the second table. GLP-1 analogues have the fewest diabetes-drug users (1,633) but the highest total cost ($6.57 million). Metformin has ten times the users at a quarter of the cost. That is the pattern of new drugs in a budget impact analysis: a small, growing share of patients and a large share of spending. Renavex will join that list in 2025.

Try it (10 min). How many people in each province had both an SGLT2 inhibitor and a GLP-1 analogue in 2024?

Solution
"""Day 3 exercise 3.3: how many people had both an SGLT2 inhibitor and a GLP-1 analogue in 2024?"""

import os
import sys

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

con = connect()
show(con, """
    WITH users AS (
        SELECT r.person_id, any_value(r.province) AS province,
               bool_or(d.atc LIKE 'A10BK%') AS sglt2, bool_or(d.atc LIKE 'A10BJ%') AS glp1
        FROM drug_claims r JOIN drugs d USING (din) GROUP BY 1)
    SELECT province, count_if(sglt2) AS sglt2_users, count_if(glp1) AS glp1_users,
           count_if(sglt2 AND glp1) AS both
    FROM users GROUP BY 1 ORDER BY 1""")
province  sglt2_users  glp1_users  both
      ON         3348         946   290
      QC         2212         687   189

One row per person, with bool_or() flags, makes "both", "either" and "neither" one-line counts. Remember Day 2: these are public-plan users only.


3.4 What does a hospital stay cost? (40 min)

Hospitals in Canada are mostly funded by global budgets, so a stay has no "price" in the data. Health economists estimate its cost in three steps.

  1. Group the stay. CIHI's grouping method assigns each stay to a case-mix group (CMG) of clinically similar stays that use similar resources (heart failure, hip replacement, and so on).
  2. Weight the stay. Each stay gets a resource intensity weight (RIW): its expected resource use relative to the average stay, which has an RIW of 1.0. The RIW depends on the CMG, the length of stay, age and complications.
  3. Price the weight. Multiply the RIW by a cost per weighted case (CPWC): what an average stay (RIW 1.0) costs in that province and year. CIHI publishes this as the cost of a standard hospital stay.
cost of a stay=RIW×CPWC\text{cost of a stay} = \text{RIW} \times \text{CPWC}

The course uses a CPWC of $6,800 for Ontario and $6,400 for Quebec.

"""Day 3.4: what does a hospital stay cost? RIW x cost per weighted case."""

import os
import sys

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

con = connect()
con.execute("""
    CREATE TEMP VIEW stay_costs AS
    SELECT h.*, p.cost_per_weighted_case, round(h.riw * p.cost_per_weighted_case, 2) AS cost
    FROM hospital_discharges h JOIN provinces p USING (province)""")

print("--- One stay, worked through")
show(con, """
    SELECT abstract_id, province, cmg, los_days, riw, cost_per_weighted_case, cost
    FROM stay_costs WHERE abstract_id = 'H0000001'""")

print("\n--- Cost by case-mix group (both provinces)")
show(con, """
    SELECT s.cmg, c.description, count(*) AS stays, round(avg(los_days), 1) AS mean_los,
           round(avg(riw), 3) AS mean_riw, round(avg(cost)) AS mean_cost, round(sum(cost)) AS total_cost
    FROM stay_costs s JOIN cmg c USING (cmg)
    GROUP BY ALL ORDER BY total_cost DESC""")

print("\n--- Hospital spending in 2024 by province")
show(con, """
    SELECT province, count(*) AS stays, round(sum(riw), 1) AS weighted_cases,
           round(sum(cost)) AS total_cost,
           round(1000 * count(*) / any_value(n), 1) AS stays_per_1000,
           round(sum(cost) / any_value(n), 2) AS cost_per_adult
    FROM stay_costs JOIN (SELECT province, count(*) AS n FROM persons GROUP BY 1) USING (province)
    GROUP BY 1 ORDER BY 1""")

print("\n--- Why not just average cost per day? Cost per day by length of stay")
show(con, """
    SELECT CASE WHEN los_days <= 2 THEN '1-2' WHEN los_days <= 5 THEN '3-5'
                WHEN los_days <= 10 THEN '6-10' ELSE '11+' END AS los_group,
           count(*) AS stays, round(avg(cost)) AS mean_cost, round(sum(cost) / sum(los_days)) AS cost_per_day
    FROM stay_costs GROUP BY 1 ORDER BY min(los_days)""")
--- One stay, worked through
abstract_id province  cmg  los_days    riw  cost_per_weighted_case    cost
   H0000001       ON CH13         4 0.8363                    6800 5686.84

--- Cost by case-mix group (both provinces)
 cmg                                             description  stays  mean_los  mean_riw  mean_cost  total_cost
CH05                                               Pneumonia   5781       6.5     1.161       7721    44635845
CH09                                                  Sepsis   2290      10.3     2.670      17727    40594984
CH11                           Hip fracture with replacement   2067      11.9     2.477      16462    34026431
CH01                                           Heart failure   2453       7.4     1.455       9674    23729346
CH13                                 Urinary tract infection   3834       4.6     0.868       5769    22117005
CH03                                                  Stroke   1078      11.0     2.401      15951    17194645
CH12                                Chest pain, investigated   4360       1.9     0.575       3823    16667163
CH07         Chronic kidney disease / dialysis complications    989       6.9     1.605      10675    10557420
CH10                                            Appendectomy   1570       2.6     0.975       6476    10167376
CH04                                       COPD exacerbation   1082       5.9     1.208       8036     8695150
CH08                             Diabetes with complications   1156       4.9     1.047       6962     8047708
CH06                                     Acute kidney injury    905       6.7     1.333       8855     8013839
CH02 Acute myocardial infarction, with coronary intervention     54       4.6     2.203      14683      792892

--- Hospital spending in 2024 by province
province  stays  weighted_cases  total_cost  stays_per_1000  cost_per_adult
      ON  17050         22683.5   154247829           109.9          994.36
      QC  10569         14217.5    90991976           111.4          959.04

--- Why not just average cost per day? Cost per day by length of stay
los_group  stays  mean_cost  cost_per_day
      1-2   8044       4592          3158
      3-5   8110       7141          1839
     6-10   6759      10227          1338
      11+   4706      17268          1065

The last table explains why you do not just use an average cost per day. The first days of a stay are the expensive ones (tests, procedures, intensive care), so a short stay costs $3,158 a day and a long one $1,065. Multiplying days by an average daily cost would overstate long stays and understate short ones.

Two cautions for costing studies. RIW-based costs are expected costs for that kind of stay, not what that patient's care actually cost. And they exclude physicians' fees, which are paid through OHIP or RAMQ. To get the full cost of a stay, add the physician claims during the stay, and be careful not to count them twice.

Try it (10 min). For people with at least one heart failure stay (MRDx I500) in 2024, compute per person: the cost of their heart failure stays, and the cost of all their stays.

Solution
"""Day 3 exercise 3.4: hospital cost per person for people admitted for heart failure (MRDx I500)."""

import os
import sys

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

con = connect()
show(con, """
    WITH costs AS (
        SELECT h.person_id, h.province, h.mrdx, h.riw * p.cost_per_weighted_case AS cost
        FROM hospital_discharges h JOIN provinces p USING (province)),
    hf_people AS (SELECT DISTINCT person_id FROM costs WHERE mrdx = 'I500')
    SELECT province, count(DISTINCT person_id) AS people,
           round(sum(cost) FILTER (mrdx = 'I500') / count(DISTINCT person_id)) AS hf_stays_cost_per_person,
           round(sum(cost) / count(DISTINCT person_id)) AS all_stays_cost_per_person
    FROM costs JOIN hf_people USING (person_id) GROUP BY 1 ORDER BY 1""")
province  people  hf_stays_cost_per_person  all_stays_cost_per_person
      ON    1274                     11793                      13709
      QC     812                     10720                      12456

About 14% of these patients' hospital costs come from stays for other reasons. A model that counts only "heart failure stays" misses that part of the disease's burden. Module 2 will compare costs with a matched group without the disease.


3.5 Two code bugs (25 min)

Bug 1: the dot. People write ICD-10 codes with a dot ("E11.2"), but hospital abstracts store them without it ("E112").

"""Day 3 bug of the day (part 1): ICD-10 codes are stored without the dot,
and a prefix that is one character too short catches other diseases."""

import os
import sys

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

con = connect()
for pattern in ("E11.%", "E11%", "E1%"):
    n = con.execute("SELECT count(*) FROM hospital_discharges WHERE mrdx LIKE ?", [pattern]).fetchall()[0][0]
    in_lookup = con.execute("SELECT string_agg(code || ' ' || description, '; ' ORDER BY code) FROM icd10 "
                            "WHERE code LIKE ?", [pattern]).fetchall()[0][0]
    print(f"LIKE '{pattern}': {n:>5} stays in 2024 | lookup codes: {in_lookup}")
LIKE 'E11.%':     0 stays in 2024 | lookup codes: None
LIKE 'E11%':  1156 stays in 2024 | lookup codes: E112 Type 2 diabetes mellitus with renal complications; E119 Type 2 diabetes mellitus without complications
LIKE 'E1%':  1156 stays in 2024 | lookup codes: E109 Type 1 diabetes mellitus without complications; E112 Type 2 diabetes mellitus with renal complications; E119 Type 2 diabetes mellitus without complications

LIKE 'E11.%' returns nothing, and no error warns you. The prefix one character too short (E1%) looks right on 2024's data, because there were no type 1 diabetes stays. But the lookup shows it would also catch E109, type 1 diabetes. Write code lists at the level of the concept (E11 for type 2), and check every pattern against the lookup, not just against this year's data.

Bug 2: the leading zero. A DIN is a code that happens to contain digits.

"""Day 3 bug of the day (part 2): a DIN is a code, not a number."""

import os
import sys

import pandas as pd

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

drugs = pd.read_csv(os.path.join(DATA, "drugs.csv"))                     # the bug: default types
claims = pd.read_csv(os.path.join(DATA, "drug_claims_2024.csv"), usecols=["rx_id", "din"])
print("pandas guessed:", drugs["din"].dtype, "->", drugs["din"].iloc[0])

# a colleague's code list of SGLT2 DINs, typed in as text (as every formulary prints them)
sglt2 = pd.DataFrame({"din": ["09900066", "09900074"], "drug": ["empagliflozin", "dapagliflozin"]})
claims["din"].astype(str).head(1).pipe(lambda s: print("claims DIN as text:", s.iloc[0]))
matched = claims.assign(din=claims["din"].astype(str)).merge(sglt2, on="din")
print(f"SGLT2 claims matched with default types: {len(matched):,}")

claims = pd.read_csv(os.path.join(DATA, "drug_claims_2024.csv"), usecols=["rx_id", "din"], dtype={"din": str})
matched = claims.merge(sglt2, on="din")
print(f"SGLT2 claims matched with dtype={{'din': str}}: {len(matched):,}")
pandas guessed: int64 -> 9900015
claims DIN as text: 9900031
SGLT2 claims matched with default types: 0
SGLT2 claims matched with dtype={'din': str}: 41,252

pandas reads 09900066 as the number 9900066, and the zero is gone. A join to a DIN list typed as text then matches zero claims, and you might conclude nobody took the drug. Postal codes, ICD-9 codes such as 250 and fee codes all have the same problem. The fix is to declare code columns as text when you read them, which corridor/db.py does for every table.


3.6 Mini-project: one code list, three sources (60 min)

A code list records, in one place, which codes define a concept in each data source. Analysts, reviewers and your future self can then read it without digging through SQL. Here is the course's first one:

concept,source,code_system,code,match,note
diabetes,physician_claims,ICD-9,250,exact,diabetes mellitus (type not recorded on claims)
diabetes,hospital_discharges,ICD-10,E11,prefix,type 2 diabetes in any diagnosis position
diabetes,drug_claims,ATC,A10,prefix,any drug used in diabetes (public plans only)
ckd,physician_claims,ICD-9,585,exact,chronic kidney disease
ckd,hospital_discharges,ICD-10,N18,prefix,chronic kidney disease in any diagnosis position
ckd,hospital_discharges,ICD-10,Z491,exact,dialysis
ckd,physician_claims,FEE,CH103,exact,dialysis supervision (Ontario course code)
ckd,physician_claims,FEE,Q0103,exact,dialysis supervision (Quebec course code)

corridor/codes.py turns each row into SQL and collects the people it finds:

"""Day 3: code lists - one file says which codes define a concept in each source."""

import csv

DX_COLUMNS = ("mrdx", "dx2", "dx3", "dx4")

def load_codelist(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))

def _condition(column, code, match):
    code = code.replace("'", "''")
    return f"{column} LIKE '{code}%'" if match == "prefix" else f"{column} = '{code}'"

def people_sql(row):
    """SQL returning the distinct person_ids that one code-list row captures."""
    src, system, code, match = row["source"], row["code_system"], row["code"], row["match"]
    if src == "physician_claims":
        col = "fee_code" if system == "FEE" else "dx_code"
        return f"SELECT DISTINCT person_id FROM physician_claims WHERE {_condition(col, code, match)}"
    if src == "hospital_discharges":
        cond = " OR ".join(_condition(c, code, match) for c in DX_COLUMNS)
        return f"SELECT DISTINCT person_id FROM hospital_discharges WHERE {cond}"
    if src == "drug_claims":
        return ("SELECT DISTINCT r.person_id FROM drug_claims r JOIN drugs d USING (din) "
                f"WHERE {_condition('d.atc', code, match)}")
    raise ValueError(f"unknown source {src!r}")

def flag_people(con, codelist, concept):
    """Return {source: set(person_id)} for one concept."""
    found = {}
    for row in codelist:
        if row["concept"] != concept:
            continue
        ids = {r[0] for r in con.sql(people_sql(row)).fetchall()}
        found.setdefault(row["source"], set()).update(ids)
    return found
"""Day 3 mini-project: one code list, three sources - who does each source find?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.codes import flag_people, load_codelist  # noqa: E402
from corridor.db import ROOT, connect  # noqa: E402

con = connect()
codelist = load_codelist(os.path.join(ROOT, "codelists", "diabetes_ckd.csv"))
ever_public = {r[0] for r in con.sql("SELECT DISTINCT person_id FROM drug_plan_eligibility").fetchall()}

for concept in ("diabetes", "ckd"):
    found = flag_people(con, codelist, concept)
    sources = sorted(found)
    everyone = set().union(*found.values())
    print(f"--- {concept}: {len(everyone):,} people found by at least one source")
    for s in sources:
        print(f"  {s:<22}{len(found[s]):>8,}")
    if len(sources) == 3:
        print("  pattern (physician / hospital / drug):")
        patterns = {}
        for pid in everyone:
            key = tuple(int(pid in found[s]) for s in ("physician_claims", "hospital_discharges", "drug_claims"))
            patterns[key] = patterns.get(key, 0) + 1
        for key in sorted(patterns, reverse=True):
            label = " ".join("yes" if k else " - " for k in key)
            print(f"    {label}   {patterns[key]:>7,}")
        drug_only_public = len(found["drug_claims"] - found["physician_claims"] - found["hospital_discharges"])
        no_drug = everyone - found["drug_claims"]
        print(f"  found without any drug claim: {len(no_drug):,}, "
              f"of whom {len(no_drug & ever_public):,} ever had a public drug plan")
        print(f"  found only through drug claims: {drug_only_public:,}")
    print()
--- diabetes: 28,519 people found by at least one source
  drug_claims             18,206
  hospital_discharges      6,155
  physician_claims        27,648
  pattern (physician / hospital / drug):
    yes yes yes     4,140
    yes yes  -      1,643
    yes  -  yes    13,311
    yes  -   -      8,554
     -  yes yes       256
     -  yes  -        116
     -   -  yes       499
  found without any drug claim: 10,313, of whom 1,078 ever had a public drug plan
  found only through drug claims: 499

--- ckd: 12,570 people found by at least one source
  hospital_discharges      4,185
  physician_claims        11,690

What the patterns tell you:

  • Physician claims find almost everyone (27,648 of 28,519 for diabetes). Hospital data alone find only 6,155.
  • 8,554 people have only physician claims. Some are real diabetes cases whose drugs are paid privately. Others are "rule-out" visits by people who do not have diabetes at all. One claim is weak evidence.
  • 10,313 people found by the code list have no drug claim at all, and only 1,078 of them ever had a public drug plan. Day 2's coverage gap again.
  • 499 people appear only through drug claims. An A10 drug without a diabetes diagnosis can be metformin prescribed for another reason. This is why drug-only definitions need care.

On Day 5 you will use the standard Ontario approach for diabetes as a validated case definition. It asks for one hospitalization or two physician claims within two years, rather than "any code anywhere". The code list you built today is its input. (Day 5 also uses the hidden truth file to measure how accurate each definition is.)

Why it matters at work: the case definition determines who is in your study, and HTA reviewers check it line by line. A published code list with sources makes it auditable.

Where you'll meet this: the appendix of every ICES or RAMQ study · CDA-AMC reviews of RWE submissions · phenotype libraries · Module 3's target trial protocol


3.7 Save your work (15 min)

Add the tests for Days 1–3 (tests/test_days_01_03.py; known answers for cost sharing, suppression and code-list SQL), run them, and commit.

"""Known-answer tests for Days 1-3."""

import pandas as pd
import pytest

from corridor.codes import people_sql
from corridor.costshare import Plan, load_plans, new_tracker, price_prescription, split_cost
from corridor.privacy import suppress

def test_renavex_price_ontario():
    assert price_prescription(3.85, 30, 0.08, 8.83) == (115.50, 9.24, 8.83, 133.57)

def test_odb_deductible_then_copay(con):
    plan = load_plans(con)["ODB-65"]
    t = new_tracker()
    assert split_cost(plan, 133.57, t, "2026-03") == (106.11, 27.46)   # $100 deductible + $6.11
    assert split_cost(plan, 133.57, t, "2026-04") == (6.11, 127.46)

def test_ramq_monthly_maximum(con):
    plan = load_plans(con)["RAMQ-PUB"]
    t = new_tracker()
    assert split_cost(plan, 500.00, t, "2026-03") == (96.25, 403.75)   # capped at the monthly maximum
    assert split_cost(plan, 50.00, t, "2026-03") == (0.00, 50.00)      # nothing more this month
    assert split_cost(plan, 50.00, t, "2026-04")[0] == pytest.approx(31.57)  # 22.90 + 0.32 * 27.10

def test_coinsurance_without_rules():
    assert split_cost(Plan("X", coinsurance=0.2), 100.0, new_tracker(), "2026-01") == (20.0, 80.0)

def test_rule_matches_claims(con):
    plans = load_plans(con)
    rows = con.sql("""SELECT person_id, plan_id, strftime(dispense_date, '%Y-%m'), total_cost, patient_paid
                      FROM drug_claims WHERE person_id IN
                          (SELECT DISTINCT person_id FROM drug_claims ORDER BY person_id LIMIT 2000)
                      ORDER BY person_id, rx_id""").fetchall()
    trackers = {}
    for person, plan_id, month, total, paid in rows:
        patient, _ = split_cost(plans[plan_id], total, trackers.setdefault((person, plan_id), new_tracker()), month)
        assert patient == pytest.approx(paid, abs=0.005)

def test_suppression_hides_small_and_one_more():
    t = pd.DataFrame({"a": [3, 10], "b": [20, 0], "c": [30, 40]}, index=["r1", "r2"])
    safe, hidden = suppress(t)
    assert hidden == 2                     # the 3, then the 20 so the row total can't reveal it
    assert safe.loc["r1", "a"] == "<6" and safe.loc["r1", "b"] == "<6"
    assert safe.loc["r2", "b"] == 0        # zeros are allowed

def test_code_list_sql(con):
    exact = people_sql({"source": "physician_claims", "code_system": "ICD-9", "code": "250", "match": "exact"})
    prefix = people_sql({"source": "hospital_discharges", "code_system": "ICD-10", "code": "E11", "match": "prefix"})
    assert "dx_code = '250'" in exact
    assert "mrdx LIKE 'E11%'" in prefix and "dx4 LIKE 'E11%'" in prefix
    assert con.sql(prefix).fetchall()

def test_dins_are_eight_character_text(con):
    assert con.sql("SELECT count(*) FROM drug_claims WHERE length(din) <> 8").fetchall()[0][0] == 0
python -m pytest -q
git add .
git commit -m "Day 3: codes, hospital costing, first code list"

Day 3 checklist

  • I can read an ICD-10 code, an ICD-9 claim code, a CCI code, a fee code, a DIN and an ATC code, and say where each comes from
  • I know the difference between the MRDx and other diagnoses, and I unpivot diagnosis columns
  • I can cost a hospital stay as RIW × CPWC and explain why cost per day misleads
  • I check every code pattern against the lookup, and read every code column as text
  • My code list finds people in three sources, and I can explain why the sources disagree