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

Who Pays? Health Care and Drug Coverage in Ontario and Quebec

Every health economic analysis starts from one question: who pays for what? A cost-effectiveness analysis for Canada's Drug Agency takes the view of the public health care payer. A budget impact analysis has to say what each provincial drug plan will spend. A market access plan depends on which patients' plans will cover the drug at all. Today you learn the payment system and follow Renavex from approval to listing. Then you code the cost-sharing rules of five public drug plans and check them against 823,487 real-shaped claims.

▶
Video for Day 1 coming soon

By the end of today you can

  • explain why physician and hospital records cover everyone but provincial drug claims do not
  • name the public drug programs in Ontario (ODB, OHIP+, Trillium) and Quebec (RAMQ public plan, mandatory group plans)
  • list the steps from Health Canada approval to a provincial listing, and say what CDA-AMC, INESSS and pCPA each do
  • corridor/db.py opens every table, and split_cost() reproduces all 2024 claims
  • computed a year of Renavex for seven people and can explain why the amounts differ

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:45
1.1 Who pays for health care in Canada
0:45–1:25
1.2 Drug coverage in Ontario and Quebec
1:25–1:40
Break
1:40–2:20
1.3 From approval to a listing: Renavex's route
2:20–3:00
1.4 Set up, and a first look at the data
3:00–3:15
Break
3:15–4:00
1.5 Who pays for one prescription
4:00–4:45
1.6 Mini-project: a year of Renavex for seven people
4:45–5:00
1.7 Save your work with Git
5:00–5:30
Bloc français

In this lesson

1.1 Who pays for health care in Canada (45 min)

Canada does not have one health system. It has thirteen provincial and territorial systems held together by a federal law. The Canada Health Act (1984) sets the conditions a province must meet to receive its full federal cash transfer. There are five criteria:

CriterionIn plain words
Public administrationThe provincial plan is run on a non-profit basis by a public authority
ComprehensivenessIt covers all insured services: medically necessary hospital and physician services
UniversalityAll insured residents are covered on uniform terms
PortabilityCoverage continues when you move or travel within Canada (with waiting periods and limits)
AccessibilityNo extra billing or user charges for insured services

The key word is insured services. Doctors' visits and hospital care must be covered, and they are free at the point of care. Prescription drugs taken outside hospital are not insured services under the Act. Each province decides whom its public drug plan covers, and everyone else relies on private insurance or pays out of pocket. That single fact explains most of what you will see in drug data:

  • Physician claims exist for almost everyone, because the province pays the doctor (in Ontario, OHIP; in Quebec, RAMQ).
  • Hospital records exist for everyone, because hospitals report every discharge, whoever pays.
  • Drug claims in provincial data exist only for people whose drugs the public plan pays for. Drugs paid by private insurers are invisible.

Overall, about 70% of Canada's health spending is public and 30% private. Private spending is concentrated in prescription drugs, dental care, vision care and other professionals.

Why it matters at work: a health economic evaluation must state its perspective. CDA-AMC's reference case is the publicly funded health care payer. That means you count what OHIP, RAMQ, hospitals and public drug plans pay. Patients' co-payments and private insurers' costs fall outside it.

Where you'll meet this: the perspective section of a CDA-AMC submission · budget impact models by plan · an INESSS evaluation that also reports a societal view · burden-of-illness reports that split public and private costs

Try it (5 min). For each item, is it an insured service under the Canada Health Act? (a) A family doctor visit for a cough. (b) Insulin used during a hospital stay. (c) Insulin picked up at a community pharmacy. (d) A dental cleaning.

Solution

(a) Yes: a medically necessary physician service. (b) Yes: drugs given in hospital are part of hospital services. (c) No: outpatient drugs are covered only if a provincial drug plan or a private plan pays. (d) No: dental care outside hospital is not an insured service. (Federal dental programs are separate from the Act.)


1.2 Drug coverage in Ontario and Quebec (40 min)

The two provinces of the corridor solved the drug-coverage gap in very different ways. The difference matters for every analysis you will do in this course.

Ontario: public coverage for specific groups. The Ontario Drug Benefit (ODB) program pays for drugs on its formulary for:

  • residents aged 65 and over (from the first day of the month after their 65th birthday)
  • people on Ontario Works or ODSP (social assistance), in long-term care or receiving home care
  • OHIP+: residents under 25 who have no private drug plan. OHIP+ began in January 2018 for everyone under 25. Since April 2019 it has excluded young people covered by a private plan.
  • the Trillium Drug Program: anyone whose drug costs are high compared with household income. You pay a yearly deductible of about 4% of household income, and then a small co-payment per prescription.

Everyone else between 25 and 64 has a workplace or private plan, or pays out of pocket.

Quebec: everyone must be insured. Since 1997, everyone living permanently in Quebec must have prescription drug insurance at all times. If a group plan is available to you (through work, a spouse or parents), you must join it. Otherwise you register with RAMQ's Public Prescription Drug Insurance Plan. At 65 you are registered with the public plan automatically, and you may keep a private plan if you are still eligible for one. Group plans must give at least the basic coverage of the public plan.

Cost sharing. Public plans rarely pay 100%. The tools are always the same:

ToolMeaningCourse example
DeductibleYou pay everything until you have paid this amount in the periodODB seniors: $100 a year · RAMQ: $22.90 a month
Co-paymentA fixed amount per prescriptionODB seniors: $6.11 · low income and social assistance: $2.00
CoinsuranceA share of the cost after the deductibleRAMQ: 32%
Out-of-pocket maximumThe most you pay in the periodRAMQ: $96.25 a month

The course stores these rules in data/drug_plans.csv:

plan_id,province,name,who,deductible,deductible_period,copay_per_rx,coinsurance,max_out_of_pocket,max_period,public
ODB-65,ON,ODB seniors,"Ontario residents 65+ (single, above the low-income threshold)",100.00,year,6.11,0.00,,,1
ODB-65L,ON,"ODB seniors, low income",Ontario residents 65+ below the low-income threshold,0.00,,2.00,0.00,,,1
ODB-SA,ON,ODB social assistance,Ontario Works / ODSP recipients,0.00,,2.00,0.00,,,1
OHIP+,ON,OHIP+,Ontario residents under 25 with no private drug plan,0.00,,0.00,0.00,,,1
ON-PRIV,ON,Ontario private group plan (typical),Employees and dependants with a workplace plan,0.00,,0.00,0.20,,,0
ON-NONE,ON,No drug coverage,Ontario residents under 65 with no plan (may apply to Trillium),0.00,,0.00,1.00,,,0
RAMQ-PUB,QC,RAMQ public plan,"Quebec residents with no access to a private plan, and most 65+",22.90,month,0.00,0.32,96.25,month,1
RAMQ-SA,QC,"RAMQ, last-resort financial assistance",Social assistance recipients,0.00,,0.00,0.00,,,1
QC-PRIV,QC,Quebec private group plan (typical),Anyone with access to a group plan must join it,0.00,,0.00,0.32,96.25,month,0

National pharmacare. The federal Pharmacare Act (October 2024) set out first-dollar public coverage of diabetes drugs and contraceptives, delivered through bilateral agreements with each province. Four jurisdictions signed agreements. Ontario and Quebec did not, and Quebec said it would opt out. The plans in this course are therefore the ones that pay for Renavex's comparators in the corridor. Check Health Canada's pharmacare page for the current status before you write about it.

Try it (10 min). Which plan pays for each person's drugs in 2024? (a) Aisha, 23, a student in Toronto covered by her mother's workplace plan. (b) Luc, 23, a student in Sherbrooke whose parents have no group plan. (c) Ming, 66, in Ottawa, retired with no private plan. (d) Robert, 66, in Laval, still working with a group plan.

Solution

(a) Her mother's private plan. OHIP+ excludes anyone with private coverage. (b) RAMQ's public plan: with no group plan available, he must register with RAMQ. (c) ODB, from the first day of the month after he turned 65. (d) He can choose. At 65 he was registered with the public plan automatically, but he may keep his group plan instead (or as well) while he is eligible for it.


1.3 From approval to a listing: Renavex's route (40 min)

A new drug passes through several bodies before a public plan pays for it.

  1. Health Canada reviews safety, efficacy and quality, then issues a Notice of Compliance (NOC). The drug can now be sold.
  2. The Patented Medicine Prices Review Board (PMPRB) makes sure the price of a patented medicine is not excessive. It sets a ceiling, not the price plans pay.
  3. A health technology assessment (HTA) body reviews clinical and cost-effectiveness evidence and recommends whether public plans should pay, and on what conditions. Canada's Drug Agency (CDA-AMC, called CADTH until 2024) advises every federal, provincial and territorial plan except Quebec's. Quebec has its own HTA body: INESSS (Institut national d'excellence en santé et en services sociaux). Its recommendation (avis) goes to Quebec's health minister. Manufacturers often file before the NOC, so the reviews overlap with Health Canada's.
  4. The pan-Canadian Pharmaceutical Alliance (pCPA) negotiates prices jointly for public plans, including Quebec's. A successful negotiation ends with a letter of intent.
  5. Each plan lists the drug on its own formulary and sets its own conditions. Ontario uses General Benefit, Limited Use (prescriber must confirm criteria) or the Exceptional Access Program (case-by-case approval). Quebec uses its Liste des médicaments, where médicaments d'exception need specific criteria to be met.

Renavex's (fictional) timeline is in data/renavex_milestones.csv. Today's script lines up the dates:

"""Day 1.3: Renavex's route from approval to public coverage."""

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("--- Milestones in date order (days counted from the Notice of Compliance)")
show(con, """
    SELECT date, jurisdiction, milestone,
           date_diff('day', (SELECT date FROM renavex_milestones WHERE milestone = 'health_canada_noc'), date)
               AS days_from_noc
    FROM renavex_milestones ORDER BY date""")

print("\n--- How long each step took")
steps = [
    ("CDA-AMC review", "cda_submission", "cda_recommendation"),
    ("INESSS review", "inesss_submission", "inesss_avis"),
    ("Wait for pCPA to start", "cda_recommendation", "pcpa_start"),
    ("pCPA negotiation", "pcpa_start", "pcpa_loi"),
    ("Letter of intent to Ontario listing", "pcpa_loi", "on_listing"),
    ("Letter of intent to Quebec listing", "pcpa_loi", "qc_listing"),
    ("Approval to Ontario listing", "health_canada_noc", "on_listing"),
    ("Approval to Quebec listing", "health_canada_noc", "qc_listing"),
]
dates = dict(con.sql("SELECT milestone, date FROM renavex_milestones").fetchall())
for label, a, b in steps:
    days = (dates[b] - dates[a]).days
    print(f"{label:<38}{days:>5} days  ({days / 30.44:4.1f} months)")

gap = (dates["qc_listing"] - dates["on_listing"]).days
print(f"\nOntario lists Renavex {gap} days before Quebec: "
      f"{dates['on_listing']} vs {dates['qc_listing']}.")
--- Milestones in date order (days counted from the Notice of Compliance)
      date jurisdiction          milestone  days_from_noc
2024-03-25          ALL     cda_submission            -50
2024-04-15           QC  inesss_submission            -29
2024-05-14          ALL  health_canada_noc              0
2024-12-10          ALL cda_recommendation            210
2025-02-03           QC        inesss_avis            265
2025-03-03          ALL         pcpa_start            293
2025-07-22          ALL           pcpa_loi            434
2025-10-01           ON         on_listing            505
2026-02-04           QC         qc_listing            631

--- How long each step took
CDA-AMC review                          260 days  ( 8.5 months)
INESSS review                           294 days  ( 9.7 months)
Wait for pCPA to start                   83 days  ( 2.7 months)
pCPA negotiation                        141 days  ( 4.6 months)
Letter of intent to Ontario listing      71 days  ( 2.3 months)
Letter of intent to Quebec listing      197 days  ( 6.5 months)
Approval to Ontario listing             505 days  (16.6 months)
Approval to Quebec listing              631 days  (20.7 months)

Ontario lists Renavex 126 days before Quebec: 2025-10-01 vs 2026-02-04.

Two things to notice. First, approval is not access: Ontarians on ODB wait 505 days from the NOC, and Quebecers on RAMQ wait 631. Second, the two provinces' listing dates differ by 126 days. For four months, very similar patients in Ottawa and Gatineau have different access to the same drug. In Module 4 you will use that gap as a natural experiment (difference-in-differences across provinces).

Why it matters at work: market access teams plan launch budgets around these steps. HTA researchers use listing dates to define "before" and "after" in policy evaluations.

Where you'll meet this: time-to-listing analyses · uptake curves in budget impact models · interrupted time series around a listing date · pCPA price-reduction scenarios in Module 7


1.4 Set up, and a first look at the data (40 min)

You will use VS Code on your own machine or a GitHub Codespace. Python 3.13 is the course version.

Windows (PowerShell in VS Code's terminal):

git clone https://github.com/<you>/corridor-health.git     # or: mkdir corridor-health
cd corridor-health
py -3.13 -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
python data/make_data.py

macOS, Linux or Codespaces: the same, with python3.13 -m venv .venv and source .venv/bin/activate.

If PowerShell refuses to run Activate.ps1, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once and try again. In VS Code, choose the .venv interpreter (Ctrl+Shift+P → Python: Select Interpreter).

make_data.py uses only Python's standard library and a fixed seed (2026), so everyone gets byte-identical files. It writes 22 CSV files into data/ and one hidden file into data/truth/. The full generator is on the site's Course data page.

Your first module: corridor/db.py. Instead of loading CSVs into a database, we let DuckDB read them in place through views. Two details matter: code columns are read as text, and a small age_on() macro gives the exact age on any date.

"""Open the Corridor Health tables in DuckDB.

Every CSV in data/ becomes a view with the same name. Code columns (DINs,
diagnosis codes, fee codes) are read as text, so leading zeros survive and
'250' stays a code rather than a number.
"""

import os

import duckdb

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(ROOT, "data")

# view name -> (file, columns that must stay text)
TABLES = {
    "provinces": ("provinces.csv", []),
    "regions": ("regions.csv", []),
    "persons": ("persons.csv", []),
    "drug_plan_eligibility": ("drug_plan_eligibility.csv", []),
    "physician_claims": ("physician_claims_2024.csv", ["fee_code", "dx_code"]),
    "hospital_discharges": ("hospital_discharges_2024.csv", ["mrdx", "dx2", "dx3", "dx4", "cmg"]),
    "drug_claims": ("drug_claims_2024.csv", ["din"]),
    "drug_plans": ("drug_plans.csv", []),
    "pharmacy_pricing": ("pharmacy_pricing.csv", []),
    "drugs": ("drugs.csv", ["din", "atc"]),
    "atc": ("atc.csv", ["atc"]),
    "icd9_dx": ("icd9_dx.csv", ["dx_code"]),
    "icd10": ("icd10.csv", ["code"]),
    "icd10_chapters": ("icd10_chapters.csv", []),
    "cci": ("cci.csv", []),
    "cci_sections": ("cci_sections.csv", []),
    "cmg": ("cmg.csv", []),
    "fee_codes": ("fee_codes.csv", ["fee_code"]),
    "renavex_milestones": ("renavex_milestones.csv", []),
    "personas": ("personas.csv", []),
}

def connect(database=":memory:"):
    """Return a DuckDB connection with one view per course table."""
    con = duckdb.connect(database)
    for name, (file, text_cols) in TABLES.items():
        path = os.path.join(DATA, file).replace("\\", "/")
        if not os.path.exists(path):
            raise FileNotFoundError(f"{file} is missing: run  python data/make_data.py  first")
        types = ", ".join(f"'{c}': 'VARCHAR'" for c in text_cols)
        con.execute(f"CREATE VIEW {name} AS SELECT * FROM read_csv('{path}', types = {{{types}}})")
    # exact age in whole years on a date
    con.execute("""CREATE MACRO age_on(birth, d) AS
                   date_diff('year', birth, d) - (strftime(d, '%m-%d') < strftime(birth, '%m-%d'))::INT""")
    return con

def show(con, sql, **params):
    """Run a query and print it as a plain table (no index)."""
    df = con.execute(sql, params).df() if params else con.sql(sql).df()
    for col in df.columns:  # counts can arrive as floats; show them as whole numbers
        if df[col].dtype.kind == "f" and df[col].notna().all() and (df[col] % 1 == 0).all():
            df[col] = df[col].astype("int64")
    print(df.to_string(index=False))
    return df
"""Day 1.4: a first look at Corridor Health."""

import os
import sys

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

con = connect()

print("--- Tables and row counts")
for name in TABLES:
    n = con.sql(f"SELECT count(*) FROM {name}").fetchall()[0][0]
    print(f"{name:<24}{n:>12,}")

print("\n--- People by province")
show(con, """
    SELECT province,
           count(*)                                                   AS people,
           round(avg(age_on(birth_date, DATE '2024-01-01')), 1)       AS mean_age,
           count(death_date)                                          AS died_2024
    FROM persons GROUP BY province ORDER BY province""")

print("\n--- Public drug plan on 1 July 2024")
show(con, """
    SELECT p.province, e.plan_id, count(*) AS people
    FROM drug_plan_eligibility e JOIN persons p USING (person_id)
    WHERE e.start_date <= DATE '2024-07-01'
      AND (e.end_date IS NULL OR e.end_date >= DATE '2024-07-01')
      AND (p.death_date IS NULL OR p.death_date >= DATE '2024-07-01')
    GROUP BY ALL ORDER BY 1, 2""")

print("\n--- Share of adults with a public drug plan on 1 July 2024, by age group")
show(con, """
    WITH alive AS (
        SELECT person_id, province,
               CASE WHEN age_on(birth_date, DATE '2024-07-01') < 25 THEN '18-24'
                    WHEN age_on(birth_date, DATE '2024-07-01') < 65 THEN '25-64'
                    ELSE '65+' END AS age_group
        FROM persons
        WHERE registry_start <= DATE '2024-07-01'
          AND (death_date IS NULL OR death_date >= DATE '2024-07-01')),
    covered AS (
        SELECT DISTINCT person_id FROM drug_plan_eligibility
        WHERE start_date <= DATE '2024-07-01' AND (end_date IS NULL OR end_date >= DATE '2024-07-01'))
    SELECT province, age_group, count(*) AS people,
           round(100 * avg((c.person_id IS NOT NULL)::INT), 1) AS pct_public_plan
    FROM alive a LEFT JOIN covered c USING (person_id)
    GROUP BY ALL ORDER BY 1, 2""")
--- Tables and row counts
provinces                          2
regions                           11
persons                      250,000
drug_plan_eligibility        103,844
physician_claims           1,058,159
hospital_discharges           27,619
drug_claims                  823,487
drug_plans                         9
pharmacy_pricing                   2
drugs                             16
atc                               45
icd9_dx                           12
icd10                             19
icd10_chapters                     9
cci                                6
cci_sections                       7
cmg                               13
fee_codes                         13
renavex_milestones                 9
personas                           7

--- People by province
province  people  mean_age  died_2024
      ON  155122      49.5       1529
      QC   94878      49.5        950

--- Public drug plan on 1 July 2024
province  plan_id  people
      ON   ODB-65   32485
      ON  ODB-65L    6036
      ON   ODB-SA    8480
      ON    OHIP+    3635
      QC RAMQ-PUB   44425
      QC  RAMQ-SA    5150

--- Share of adults with a public drug plan on 1 July 2024, by age group
province age_group  people  pct_public_plan
      ON     18-24   14189             33.0
      ON     25-64  101643              7.3
      ON       65+   38525            100.0
      QC     18-24    8973             39.5
      QC     25-64   61918             38.8
      QC       65+   23517             93.7

Look at the last table. Every Ontarian aged 65+ has a public drug plan, but only 7.3% of Ontarians aged 25–64 do. In Quebec the figure for 25–64 is 38.8%, because everyone without a group plan must join RAMQ. Day 2 shows what that does to anything you count from drug claims.


1.5 Who pays for one prescription (45 min)

A pharmacy charges the drug cost, plus a markup, plus a dispensing fee. The plan's rules then split the total between patient and plan, in a fixed order: deductible first, then the co-payment, then coinsurance on the rest, and finally the out-of-pocket maximum caps what the patient pays.

"""Day 1: who pays for a prescription?

price_prescription() turns a drug's list price into what the pharmacy charges.
split_cost() splits that total between the patient and the plan, using the
plan's deductible, co-payment, coinsurance and out-of-pocket maximum.
All amounts are course values (see data/drug_plans.csv).
"""

from dataclasses import dataclass

@dataclass(frozen=True)
class Plan:
    plan_id: str
    deductible: float = 0.0
    deductible_period: str = ""   # "year", "month" or ""
    copay_per_rx: float = 0.0
    coinsurance: float = 0.0      # share of the rest the patient pays
    max_out_of_pocket: float | None = None
    max_period: str = ""          # "year", "month" or ""

def load_plans(con):
    rows = con.sql("SELECT * FROM drug_plans").fetchall()
    cols = [c[0] for c in con.sql("SELECT * FROM drug_plans").description]
    plans = {}
    for r in rows:
        d = dict(zip(cols, r))
        plans[d["plan_id"]] = Plan(
            plan_id=d["plan_id"],
            deductible=float(d["deductible"] or 0),
            deductible_period=d["deductible_period"] or "",
            copay_per_rx=float(d["copay_per_rx"] or 0),
            coinsurance=float(d["coinsurance"] or 0),
            max_out_of_pocket=None if d["max_out_of_pocket"] is None else float(d["max_out_of_pocket"]),
            max_period=d["max_period"] or "",
        )
    return plans

def price_prescription(unit_price, quantity, markup_rate, dispensing_fee):
    """Drug cost + pharmacy markup + dispensing fee, each rounded to the cent."""
    cost = round(unit_price * quantity, 2)
    markup = round(cost * markup_rate, 2)
    return cost, markup, dispensing_fee, round(cost + markup + dispensing_fee, 2)

def new_tracker():
    """Running totals the plan rules need: deductible paid and out-of-pocket paid, by period."""
    return {"deductible": {}, "out_of_pocket": {}}

def _period(kind, month):
    return month if kind == "month" else "year"

def split_cost(plan, total, tracker, month):
    """Return (patient, plan) for one prescription costing `total`.

    month is "YYYY-MM"; the tracker is updated in place, so pass the same
    tracker for every prescription of the same person and plan, in date order.
    """
    patient, rest = 0.0, total

    # 1. deductible: the patient pays everything until it is used up
    if plan.deductible:
        key = _period(plan.deductible_period, month)
        left = max(plan.deductible - tracker["deductible"].get(key, 0.0), 0.0)
        paid = min(left, rest)
        tracker["deductible"][key] = tracker["deductible"].get(key, 0.0) + paid
        patient += paid
        rest -= paid

    # 2. fixed co-payment per prescription, then coinsurance on what is left
    copay = min(plan.copay_per_rx, rest)
    patient += copay + plan.coinsurance * (rest - copay)

    # 3. out-of-pocket maximum for the period
    if plan.max_out_of_pocket is not None:
        key = _period(plan.max_period, month)
        room = max(plan.max_out_of_pocket - tracker["out_of_pocket"].get(key, 0.0), 0.0)
        patient = min(patient, room)

    patient = round(patient, 2)
    key = _period(plan.max_period, month)
    tracker["out_of_pocket"][key] = tracker["out_of_pocket"].get(key, 0.0) + patient
    return patient, round(total - patient, 2)
"""Day 1.5: who pays for a prescription, and does our rule match the claims?"""

import os
import sys

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

con = connect()
plans = load_plans(con)
pharmacy = {p: (m, f) for p, m, f in con.sql("SELECT * FROM pharmacy_pricing").fetchall()}
unit = con.sql("SELECT unit_price FROM drugs WHERE product = 'Renavex 25'").fetchall()[0][0]

print("--- One 30-day Renavex prescription (30 tablets)")
for prov in ("ON", "QC"):
    cost, markup, fee, total = price_prescription(unit, 30, *pharmacy[prov])
    print(f"{prov}: drug ${cost:.2f} + markup ${markup:.2f} + dispensing fee ${fee:.2f} = ${total:.2f}")

print("\n--- Three fills in a row, by plan (patient pays / plan pays)")
for plan_id, prov in (("ODB-65", "ON"), ("ODB-65L", "ON"), ("RAMQ-PUB", "QC"), ("RAMQ-SA", "QC")):
    total = price_prescription(unit, 30, *pharmacy[prov])[3]
    tracker = new_tracker()
    cells = []
    for month in ("2026-03", "2026-04", "2026-05"):
        patient, payer = split_cost(plans[plan_id], total, tracker, month)
        cells.append(f"{month}: {patient:7.2f} / {payer:7.2f}")
    print(f"{plan_id:<9}" + "   ".join(cells))

print("\n--- Check: recompute patient_paid for every 2024 public drug claim")
claims = con.sql("""SELECT rx_id, person_id, plan_id, strftime(dispense_date, '%Y-%m') AS month,
                           total_cost, patient_paid
                    FROM drug_claims ORDER BY person_id, rx_id""").fetchall()
trackers, wrong, n = {}, 0, 0
for rx_id, person, plan_id, month, total, paid in claims:
    tracker = trackers.setdefault((person, plan_id), new_tracker())
    patient, _ = split_cost(plans[plan_id], total, tracker, month)
    n += 1
    if abs(patient - paid) > 0.005:
        wrong += 1
print(f"{n:,} claims checked, {wrong:,} disagree with the rule.")
--- One 30-day Renavex prescription (30 tablets)
ON: drug $115.50 + markup $9.24 + dispensing fee $8.83 = $133.57
QC: drug $115.50 + markup $7.51 + dispensing fee $9.25 = $132.26

--- Three fills in a row, by plan (patient pays / plan pays)
ODB-65   2026-03:  106.11 /   27.46   2026-04:    6.11 /  127.46   2026-05:    6.11 /  127.46
ODB-65L  2026-03:    2.00 /  131.57   2026-04:    2.00 /  131.57   2026-05:    2.00 /  131.57
RAMQ-PUB 2026-03:   57.90 /   74.36   2026-04:   57.90 /   74.36   2026-05:   57.90 /   74.36
RAMQ-SA  2026-03:    0.00 /  132.26   2026-04:    0.00 /  132.26   2026-05:    0.00 /  132.26

--- Check: recompute patient_paid for every 2024 public drug claim
823,487 claims checked, 0 disagree with the rule.

The first Ontario fill costs the senior $106.11: the whole $100 deductible plus the $6.11 co-payment. Every later fill costs $6.11. In Quebec the deductible is monthly, so every fill in a new month costs $22.90 plus 32% of the rest. The last line is the real test: applied in date order, your rules reproduce what patients paid on every one of the 823,487 public claims in 2024.

Bug of the day. A colleague reused the Ontario logic for Quebec and applied the deductible once a year:

"""Day 1 bug of the day: RAMQ's deductible is monthly, not yearly.

A colleague reused the Ontario logic (one deductible per year) for Quebec.
"""

import os
import sys
from dataclasses import replace

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

con = connect()
plans = load_plans(con)
wrong_plan = replace(plans["RAMQ-PUB"], deductible_period="year")   # the bug

claims = con.sql("""SELECT person_id, strftime(dispense_date, '%Y-%m') AS month, total_cost, patient_paid
                    FROM drug_claims WHERE plan_id = 'RAMQ-PUB' ORDER BY person_id, rx_id""").fetchall()
trackers = {}
bug_total = real_total = 0.0
for person, month, total, paid in claims:
    tracker = trackers.setdefault(person, new_tracker())
    patient, _ = split_cost(wrong_plan, total, tracker, month)
    bug_total += patient
    real_total += paid

people = len(trackers)
print(f"RAMQ-PUB claims: {len(claims):,} for {people:,} people")
print(f"Patients really paid      ${real_total:14,.2f}  (${real_total / people:,.2f} a person)")
print(f"Yearly-deductible version ${bug_total:14,.2f}  (${bug_total / people:,.2f} a person)")
print(f"The bug moves ${real_total - bug_total:,.2f} from patients to RAMQ "
      f"({100 * (real_total - bug_total) / real_total:.1f}% of what patients paid).")
RAMQ-PUB claims: 310,339 for 19,585 people
Patients really paid      $  4,804,604.88  ($245.32 a person)
Yearly-deductible version $  3,042,146.18  ($155.33 a person)
The bug moves $1,762,458.70 from patients to RAMQ (36.7% of what patients paid).

Nothing crashes, and the totals look plausible. But a third of patients' payments move to RAMQ. In a budget impact analysis that error goes straight into the plan's predicted spending. The fix is the one-word deductible_period="month", plus a test against the claims, like the one in cost_sharing.py.

Try it (10 min). Total the 2024 public drug claims by plan: claims, total cost, patient share and plan share. Which plan's patients pay the largest share?

Solution
"""Day 1 exercise 1.5: who paid for 2024's public drug 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()
show(con, """
    SELECT plan_id, count(*) AS claims, round(sum(total_cost)) AS total,
           round(sum(patient_paid)) AS patient, round(sum(plan_paid)) AS plan,
           round(100 * sum(patient_paid) / sum(total_cost), 1) AS pct_patient
    FROM drug_claims GROUP BY 1 ORDER BY 1""")
 plan_id  claims    total  patient    plan  pct_patient
  ODB-65  379464 12331906  3690254 8641652         29.9
 ODB-65L   75718  2470446   151436 2319010          6.1
  ODB-SA   26631   833844    53262  780582          6.4
   OHIP+    2315    70252        0   70252          0.0
RAMQ-PUB  310339 10069883  4804605 5265278         47.7
 RAMQ-SA   29020  1031798        0 1031798          0.0

RAMQ's public plan: patients pay 47.7% of the cost. Most claims are for cheap generics, where the monthly deductible takes most of the total. Ontario seniors pay 29.9%, mostly through the $6.11 co-payment on cheap drugs.


1.6 Mini-project: a year of Renavex for seven people (45 min)

Seven personas (data/personas.csv) each need twelve 30-day fills of Renavex in 2026, on the 10th of every month. Renavex is on Ontario's formulary from 1 October 2025 and on RAMQ's list from 4 February 2026. Before a drug is listed, the public plan pays nothing.

Your job: compute what each person and their plan pays in the year. For Daniel, who has no plan, also try the Trillium Drug Program. (Course version: a yearly deductible of 4% of his $41,000 income, then $2 a fill.)

"""Day 1 mini-project: what does a year of Renavex cost seven people, and who pays?

Twelve 30-day fills in 2026, one on the 10th of each month. Renavex is on the
ODB formulary from 2025-10-01 and on RAMQ's list from 2026-02-04. Before a drug
is listed, the public plan pays nothing (course assumption: private plans cover
it from approval).
"""

import datetime as dt
import os
import sys

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

con = connect()
plans = load_plans(con)
pharmacy = {p: (m, f) for p, m, f in con.sql("SELECT * FROM pharmacy_pricing").fetchall()}
unit = con.sql("SELECT unit_price FROM drugs WHERE product = 'Renavex 25'").fetchall()[0][0]
listed = {"ON": dt.date(2025, 10, 1), "QC": dt.date(2026, 2, 4)}
public = {p for p, v in con.sql("SELECT plan_id, public FROM drug_plans").fetchall() if v == 1}
fills = [dt.date(2026, m, 10) for m in range(1, 13)]

def year_of_renavex(plan, prov, is_public):
    total = price_prescription(unit, 30, *pharmacy[prov])[3]
    tracker, patient_sum, plan_sum, covered = new_tracker(), 0.0, 0.0, 0
    for d in fills:
        if is_public and d < listed[prov]:
            patient_sum += total          # not on the formulary yet: patient pays it all
            continue
        patient, payer = split_cost(plan, total, tracker, d.strftime("%Y-%m"))
        patient_sum, plan_sum, covered = patient_sum + patient, plan_sum + payer, covered + 1
    return covered, round(patient_sum, 2), round(plan_sum, 2)

rows = []
for name, prov, age, plan_id, low, income, note in con.sql("SELECT * FROM personas").fetchall():
    covered, patient, payer = year_of_renavex(plans[plan_id], prov, plan_id in public)
    rows.append((name, prov, age, plan_id, covered, patient, payer))
    if plan_id == "ON-NONE":
        # Trillium (course version): yearly deductible of 4% of household income, then $2 a fill
        trillium = Plan("TRILLIUM", deductible=round(0.04 * income, 2), deductible_period="year", copay_per_rx=2.0)
        covered, patient, payer = year_of_renavex(trillium, prov, True)
        rows.append((name + " (Trillium)", prov, age, "TRILLIUM", covered, patient, payer))

con.execute("CREATE TEMP TABLE result (persona VARCHAR, province VARCHAR, age INT, plan VARCHAR, "
            "fills_covered INT, patient_pays DOUBLE, plan_pays DOUBLE)")
con.executemany("INSERT INTO result VALUES (?, ?, ?, ?, ?, ?, ?)", rows)
print("--- One year of Renavex (12 fills, 2026)")
show(con, "SELECT *, round(patient_pays + plan_pays, 2) AS total FROM result")
--- One year of Renavex (12 fills, 2026)
          persona province  age     plan  fills_covered  patient_pays  plan_pays   total
         Margaret       ON   72   ODB-65             12        173.32    1429.52 1602.84
           Joseph       ON   69  ODB-65L             12         24.00    1578.84 1602.84
            Priya       ON   52  ON-PRIV             12        320.52    1282.32 1602.84
           Daniel       ON   58  ON-NONE             12       1602.84       0.00 1602.84
Daniel (Trillium)       ON   58 TRILLIUM             12       1602.84       0.00 1602.84
           Sylvie       QC   74 RAMQ-PUB             11        769.16     817.96 1587.12
            Karim       QC   47  QC-PRIV             12        507.84    1079.28 1587.12
         Nathalie       QC   55 RAMQ-PUB             11        769.16     817.96 1587.12

What the table tells a health economist:

  • The same drug has seven different prices to patients, from $24 (Joseph, low-income senior) to $1,602.84 (Daniel, uninsured).
  • Trillium does not help Daniel on Renavex alone. His deductible ($1,640) is more than a year of the drug ($1,602.84).
  • Listing dates cost Quebecers money. Sylvie's and Nathalie's January fill came before RAMQ's listing, so they paid the full $132.26.
  • The public payer's cost is not the list price. ODB pays $1,429.52 for Margaret and $1,578.84 for Joseph. That difference matters when CDA-AMC's reference case counts only public payer costs.

Try it (10 min). Daniel's doctor adds semaglutide, one pen a month. Does Trillium help now?

Solution
"""Day 1 exercise 1.6: Daniel also needs semaglutide. Does Trillium help now?"""

import os
import sys

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

con = connect()
markup, fee = con.sql("SELECT markup_rate, dispensing_fee FROM pharmacy_pricing WHERE province = 'ON'").fetchall()[0]
price = dict(con.sql("SELECT product, unit_price FROM drugs").fetchall())
renavex = price_prescription(price["Renavex 25"], 30, markup, fee)[3]
sema = price_prescription(price["Semaglutide pen"], 1, markup, fee)[3]   # one pen = 4 weekly doses
total_year = 12 * (renavex + sema)
trillium = Plan("TRILLIUM", deductible=0.04 * 41000, deductible_period="year", copay_per_rx=2.0)
tracker, patient = new_tracker(), 0.0
for m in range(1, 13):
    for total in (renavex, sema):
        patient += split_cost(trillium, total, tracker, f"2026-{m:02d}")[0]
print(f"Renavex fill ${renavex:.2f}, semaglutide pen ${sema:.2f}")
print(f"A year of both: ${total_year:,.2f}")
print(f"Without Trillium Daniel pays ${total_year:,.2f}; with Trillium ${patient:,.2f} "
      f"(Trillium pays ${total_year - patient:,.2f})")
Renavex fill $133.57, semaglutide pen $243.19
A year of both: $4,521.12
Without Trillium Daniel pays $4,521.12; with Trillium $1,670.61 (Trillium pays $2,850.51)

Yes. A year of both drugs costs $4,521.12, well above his $1,640 deductible. Trillium pays $2,850.51 and Daniel pays $1,670.61.


1.7 Save your work with Git (15 min)

The generated CSVs are large and can be rebuilt from make_data.py, so .gitignore keeps them out of Git:

.venv/
__pycache__/
.pytest_cache/
*.duckdb
*.duckdb.wal
# generated data: rebuild with python data/make_data.py
data/*.csv
data/truth/

Run the tests, then commit:

python -m pytest -q
git init
git add .
git commit -m "Day 1: corridor.db, cost sharing, Renavex timeline"

Push to a new private GitHub repository (in VS Code: Source Control → Publish Branch).

Day 1 checklist

  • I can explain why physician and hospital records cover everyone but provincial drug claims do not
  • I can name the public drug programs in Ontario (ODB, OHIP+, Trillium) and Quebec (RAMQ public plan, mandatory group plans)
  • I can list the steps from Health Canada approval to a provincial listing, and say what CDA-AMC, INESSS and pCPA each do
  • corridor/db.py opens every table, and split_cost() reproduces all 2024 claims
  • I computed a year of Renavex for seven people and can explain why the amounts differ