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

Costing from Administrative Data

Cost-effectiveness analysis, budget impact and burden-of-illness studies all need the same thing: what did these people cost the payer? Today you turn every hospital stay, physician claim and public drug claim into a cost item in a common currency, 2025 dollars. Then you cost the base cohort in the year before its index date and in its 2025 follow-up, and look at the shape of the costs. That shape (most people cheap, a few very expensive) drives the statistics of Module 2.

▶
Video for Day 7 coming soon

By the end of today you can

  • state the public payer perspective and list which cost columns it includes
  • Every cost is dated, priced in its own year, and converted to 2025 dollars with the CPI
  • My cost items reconcile to the claims to the cent (dbt test)
  • report cohort costs per person and per person-year, in baseline and follow-up windows
  • describe the shape of health care costs: skewed, concentrated, highest near death

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:40
7.1 Whose costs? Perspective and components
0:40–1:20
7.2 Prices change: unit costs by year and inflation
1:20–1:35
Break
1:35–2:25
7.3 Cost items in the warehouse
2:25–3:10
7.4 Costing the cohort
3:10–3:25
Break
3:25–3:45
7.5 The wrong column for the perspective
3:45–4:45
7.6 Mini-project: how are costs distributed?
4:45–5:00
7.7 Save your work
5:00–5:30
Bloc français

In this lesson

7.1 Whose costs? Perspective and components (40 min)

The perspective decides which costs count. CDA-AMC's reference case takes the view of the publicly funded health care payer. INESSS also asks about wider societal costs in some evaluations, and Module 5 covers both. In Corridor Health, the public payer pays for three things:

ComponentSourcePublic payer costNot the public payer's
Hospital staysfct_hospital_staysRIW × cost per weighted case (Day 3)—
Physician servicesfct_physician_claimspaid_amount—
Prescription drugsfct_drug_dispensationsplan_paidpatient_paid (deductibles, co-payments)

What administrative data do not show at all: drugs paid by private plans, out-of-pocket care, home care and long-term care (in this course), and time lost from work. A societal analysis would need other sources for these.

Two rules keep a costing honest:

  1. One perspective per analysis. Do not add patients' co-payments to the payer's costs "to be complete". That answers a different question.
  2. Date every cost. Costs belong to the window in which they happened, and to the price year in which they were paid.

7.2 Prices change: unit costs by year and inflation (40 min)

Day 3 priced every stay with the 2024 cost per weighted case (CPWC). That was fine for one year. Across 2019–2025 it is wrong twice over: a 2019 stay was cheaper in 2019 dollars, and 2019 dollars bought more than 2025 dollars. The generator now adds cpwc_by_year.csv and cpi_health.csv (course values, shaped like a health price index):

cost2025 $=costyear y×CPI2025CPIy\text{cost}_{2025\,\$} = \text{cost}_{\text{year } y} \times \frac{\text{CPI}_{2025}}{\text{CPI}_{y}}
python data/make_data.py       # adds the two small tables; every earlier file is unchanged
"""Day 7.2: prices change - one stay, priced in its own year and in 2025 dollars."""

import os
import sys

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

con = warehouse()
print("--- Cost per weighted case by year, and the health price index")
show(con, """
    SELECT c.year, any_value(c.cost_per_weighted_case) FILTER (c.province = 'ON') AS cpwc_on,
           any_value(c.cost_per_weighted_case) FILTER (c.province = 'QC') AS cpwc_qc, any_value(p.index) AS cpi,
           round((SELECT index FROM stg_cpi_health WHERE year = 2025) / any_value(p.index), 4) AS to_2025_dollars
    FROM stg_cpwc_by_year c JOIN stg_cpi_health p USING (year) GROUP BY 1 ORDER BY 1""")

print("\n--- The same kind of stay (heart failure, Ontario, RIW 1.5) in different years")
show(con, """
    SELECT c.year, 1.5 AS riw, round(1.5 * c.cost_per_weighted_case, 2) AS cost_that_year,
           round(1.5 * c.cost_per_weighted_case * (SELECT index FROM stg_cpi_health WHERE year = 2025) / p.index, 2)
               AS cost_in_2025_dollars,
           round(1.5 * (SELECT cost_per_weighted_case FROM stg_cpwc_by_year WHERE province = 'ON' AND year = 2024), 2)
               AS day3_constant_price
    FROM stg_cpwc_by_year c JOIN stg_cpi_health p USING (year) WHERE c.province = 'ON' ORDER BY 1""")
--- Cost per weighted case by year, and the health price index
 year  cpwc_on  cpwc_qc   cpi  to_2025_dollars
 2019     5950     5620 131.4           1.1674
 2020     6080     5730 133.2           1.1517
 2021     6210     5850 135.9           1.1288
 2022     6420     6050 141.3           1.0856
 2023     6630     6250 146.1           1.0500
 2024     6800     6400 149.8           1.0240
 2025     6960     6560 153.4           1.0000

--- The same kind of stay (heart failure, Ontario, RIW 1.5) in different years
 year  riw  cost_that_year  cost_in_2025_dollars  day3_constant_price
 2019  1.5            8925              10419.29                10200
 2020  1.5            9120              10503.06                10200
 2021  1.5            9315              10514.50                10200
 2022  1.5            9630              10454.65                10200
 2023  1.5            9945              10441.91                10200
 2024  1.5           10200              10445.13                10200
 2025  1.5           10440              10440.00                10200

Pricing each stay in its own year and then inflating gives $10,419–$10,515 for the same stay in any year. Using one year's price for all years (the Day 3 shortcut) understates every stay by 2–3%. CDA-AMC asks for all costs in a single, stated price year. For real work, use Statistics Canada's consumer price index for health care (table 18-10-0004) and CIHI's published costs per weighted case for each year.


7.3 Cost items in the warehouse (50 min)

Two new dbt models put every cost in one long table, then roll it up to person-years:

-- Day 7: every cost item, from the public payer's perspective, in nominal and 2025 dollars.
-- Hospital stays are priced with the cost per weighted case of the admission year.
with cpi as (
    select year, index, (select index from {{ ref('stg_cpi_health') }} where year = 2025) / index as to_2025
    from {{ ref('stg_cpi_health') }}
),
items as (
    select h.person_id, h.province, h.admit_date as cost_date, 'hospital' as component,
           round(h.riw * c.cost_per_weighted_case, 2) as payer_cost, 0.0 as patient_cost
    from {{ ref('fct_hospital_stays') }} h
    join {{ ref('stg_cpwc_by_year') }} c on c.province = h.province and c.year = year(h.admit_date)
    union all
    select person_id, province, service_date, 'physician', paid_amount, 0.0
    from {{ ref('fct_physician_claims') }}
    union all
    select person_id, province, dispense_date, 'drug', plan_paid, patient_paid
    from {{ ref('fct_drug_dispensations') }}
)
select i.person_id, i.province, i.cost_date, year(i.cost_date) as year, i.component,
       i.payer_cost, i.patient_cost,
       round(i.payer_cost * cpi.to_2025, 2) as payer_cost_2025
from items i join cpi on cpi.year = year(i.cost_date)
-- Day 7: one row per person-year (fct_person_years), with public payer costs by component.
with costs as (
    select person_id, year,
           sum(payer_cost) filter (component = 'hospital')        as hospital,
           sum(payer_cost) filter (component = 'physician')       as physician,
           sum(payer_cost) filter (component = 'drug')            as drug,
           sum(payer_cost)                                         as total,
           sum(payer_cost_2025)                                    as total_2025
    from {{ ref('int_cost_items') }}
    group by all
)
select py.person_id, py.year, py.province, py.days_observed, py.died,
       coalesce(c.hospital, 0)   as hospital,
       coalesce(c.physician, 0)  as physician,
       coalesce(c.drug, 0)       as drug,
       coalesce(c.total, 0)      as total,
       coalesce(c.total_2025, 0) as total_2025
from {{ ref('fct_person_years') }} py
left join costs c using (person_id, year)

A cost table needs a reconciliation test: the items must add up, to the cent, to the claims they came from. Two singular tests check that, and that no cost falls outside an observed person-year:

-- Day 7: the cost items add up to the claims they came from (to the cent, per component).
with items as (
    select component, round(sum(payer_cost), 2) as items from {{ ref('int_cost_items') }} group by 1
),
sources as (
    select 'physician' as component, round(sum(paid_amount), 2) as source from {{ ref('fct_physician_claims') }}
    union all
    select 'drug', round(sum(plan_paid), 2) from {{ ref('fct_drug_dispensations') }}
    union all
    select 'hospital', round(sum(round(h.riw * c.cost_per_weighted_case, 2)), 2)
    from {{ ref('fct_hospital_stays') }} h
    join {{ ref('stg_cpwc_by_year') }} c on c.province = h.province and c.year = year(h.admit_date)
)
select * from items join sources using (component) where abs(items - source) > 0.01

Rebuild the warehouse (dbt build --profiles-dir . from warehouse/, or):

"""Day 7.3: rebuild the warehouse with the cost models, and list what was built and tested.

Same as running, from the warehouse folder:   dbt build --profiles-dir .
"""

import contextlib
import io
import os
import sys

from dbt.cli.main import dbtRunner

WAREHOUSE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "warehouse")
os.chdir(WAREHOUSE_DIR)

log = io.StringIO()
with contextlib.redirect_stdout(log):          # dbt's own log has timings; we print a stable summary
    result = dbtRunner().invoke(["build", "--profiles-dir", ".", "--quiet"])
if not result.success:
    print(log.getvalue())
    sys.exit("dbt build failed")

rows = []
for r in result.result:
    node = r.node
    kind = node.resource_type.value if hasattr(node.resource_type, "value") else str(node.resource_type)
    mat = node.config.materialized if kind == "model" else ""
    rows.append((kind, mat, node.name, str(r.status)))
order = {"model": 0, "test": 1}
rows.sort(key=lambda x: (order.get(x[0], 2), x[1], x[2]))
print(f"{'type':<7}{'materialized':<14}{'name':<72}status")
for kind, mat, name, status in rows:
    print(f"{kind:<7}{mat:<14}{name[:70]:<72}{status}")
print(f"\n{sum(k == 'model' for k, *_ in rows)} models, {sum(k == 'test' for k, *_ in rows)} tests, "
      f"{sum(s not in ('success', 'pass') for *_, s in rows)} problems")
model  table         dim_person                                                              success
model  table         fct_drug_dispensations                                                  success
model  table         fct_hospital_diagnoses                                                  success
model  table         fct_hospital_stays                                                      success
model  table         fct_person_year_costs                                                   success
model  table         fct_person_years                                                        success
model  table         fct_physician_claims                                                    success
model  table         int_cost_items                                                          success
model  table         mart_annual_summary                                                     success
model  table         stg_atc                                                                 success
model  table         stg_cci                                                                 success
model  table         stg_cci_sections                                                        success
model  table         stg_cmg                                                                 success
model  table         stg_cpi_health                                                          success
model  table         stg_cpwc_by_year                                                        success
model  table         stg_drug_plan_eligibility                                               success
model  table         stg_drug_plans                                                          success
model  table         stg_drugs                                                               success
model  table         stg_fee_codes                                                           success
model  table         stg_icd10                                                               success
model  table         stg_icd10_chapters                                                      success
model  table         stg_icd9_dx                                                             success
model  table         stg_persons                                                             success
model  table         stg_pharmacy_pricing                                                    success
model  table         stg_provinces                                                           success
model  table         stg_regions                                                             success
model  table         stg_renavex_milestones                                                  success
...
test                 cost_items_reconcile                                                    pass
...
27 models, 23 tests, 0 problems
"""Day 7.3: the cost items table - totals by component and year, nominal and in 2025 dollars."""

import os
import sys

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

con = warehouse()
print("--- Public payer spending, all of Corridor Health ($ millions)")
show(con, """
    PIVOT (SELECT year, component, sum(payer_cost) / 1e6 AS m FROM int_cost_items GROUP BY ALL)
    ON component USING round(sum(m), 2) GROUP BY year ORDER BY year""")
print("\n--- Total per person-year: nominal vs 2025 dollars")
show(con, """
    SELECT year, round(sum(total) / (sum(days_observed) / 365.25), 2) AS nominal_per_py,
           round(sum(total_2025) / (sum(days_observed) / 365.25), 2) AS dollars_2025_per_py
    FROM fct_person_year_costs GROUP BY 1 ORDER BY 1""")
print("\n--- What patients paid out of pocket for public-plan drugs ($ millions, outside the payer perspective)")
show(con, """SELECT year, round(sum(patient_cost) / 1e6, 2) AS patient_drug_costs
             FROM int_cost_items WHERE component = 'drug' GROUP BY 1 ORDER BY 1""")
--- Public payer spending, all of Corridor Health ($ millions)
 year  drug  hospital  physician
 2019  6.59    199.27      43.83
 2020  7.70    204.21      44.41
 2021  9.14    210.10      45.28
 2022 11.18    222.37      46.82
 2023 14.19    234.27      49.36
 2024 18.11    245.24      53.46
 2025 16.75    246.62      53.43

--- Total per person-year: nominal vs 2025 dollars
 year  nominal_per_py  dollars_2025_per_py
 2019         1073.40              1253.13
 2020         1082.98              1247.22
 2021         1103.86              1246.00
 2022         1152.99              1251.73
 2023         1207.38              1267.71
 2024         1272.78              1303.37
 2025         1287.25              1287.25

--- What patients paid out of pocket for public-plan drugs ($ millions, outside the payer perspective)
 year  patient_drug_costs
 2019                5.00
 2020                5.58
 2021                6.18
 2022                6.89
 2023                7.80
 2024                8.70
 2025                8.17

Hospital care is close to 80% of public spending in Corridor Health, physician services about 17%, and public drug plans between 2.6% (2019) and 5.7% (2024). (Remember Day 2: most drug spending for people under 65 is private, so it is invisible here.) In nominal dollars, cost per person-year rises 20% from 2019 to 2025. In 2025 dollars it rises 3%. Most of the apparent growth is prices, not more care.


7.4 Costing the cohort (45 min)

For a cohort, costs are counted in windows relative to each person's index date:

  • Baseline: the 365 days before index. This is a covariate (Module 3 adjusts for prior costs).
  • Follow-up: from the index date to death or the end of the data. This is an outcome.

Follow-up ends early for people who die, so report costs per person-year as well as per person.

"""Day 7: public payer costs for a cohort, over windows defined relative to each index date."""

def window_costs_sql(index_table, start, end, dollars="payer_cost_2025"):
    """Costs by component per person between `start` and `end` (SQL expressions using i.index_date
    and i.end_date), with the days each person was observed in the window.

    index_table needs person_id, index_date and end_date (last day of follow-up).
    dollars: 'payer_cost_2025' (constant 2025 dollars) or 'payer_cost' (nominal).
    """
    return f"""
    WITH i AS (SELECT person_id, index_date, end_date FROM {index_table}),
    w AS (SELECT person_id, ({start})::DATE AS w_start, least(({end})::DATE, end_date) AS w_end FROM i),
    c AS (
        SELECT w.person_id,
               sum({dollars}) FILTER (component = 'hospital')  AS hospital,
               sum({dollars}) FILTER (component = 'physician') AS physician,
               sum({dollars}) FILTER (component = 'drug')      AS drug
        FROM w JOIN int_cost_items x ON x.person_id = w.person_id AND x.cost_date BETWEEN w.w_start AND w.w_end
        GROUP BY w.person_id)
    SELECT w.person_id, date_diff('day', w.w_start, w.w_end) + 1 AS days,
           coalesce(c.hospital, 0) AS hospital, coalesce(c.physician, 0) AS physician,
           coalesce(c.drug, 0) AS drug,
           coalesce(c.hospital, 0) + coalesce(c.physician, 0) + coalesce(c.drug, 0) AS total
    FROM w LEFT JOIN c USING (person_id)"""

def cohort_follow_up(con, cohort="cohort", last_day="2025-12-31", table="fu"):
    """Add end_date (death or end of data) to a cohort, as temp table `table`."""
    con.execute(f"""
        CREATE OR REPLACE TEMP TABLE {table} AS
        SELECT c.*, least(coalesce(p.death_date, DATE '{last_day}'), DATE '{last_day}') AS end_date,
               p.death_date IS NOT NULL AND p.death_date <= DATE '{last_day}' AS died
        FROM {cohort} c JOIN dim_person p USING (person_id)""")
"""Day 7.4: what does the base cohort cost the public payer, before and after the index date?"""

import os
import sys

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

con = warehouse()
build_base_cohort(con)
cohort_follow_up(con)
con.execute(f"""CREATE TEMP TABLE base_costs AS
                {window_costs_sql('fu', 'i.index_date - INTERVAL 365 DAY', 'i.index_date - INTERVAL 1 DAY')}""")
END = "DATE '2025-12-31'"
con.execute(f"CREATE TEMP TABLE fu_costs AS {window_costs_sql('fu', 'i.index_date', END)}")

print("--- Follow-up: deaths and person-time")
show(con, """SELECT count(*) AS people, count_if(died) AS died_in_2025,
                    round(sum(f.days) / 365.25, 1) AS person_years
             FROM fu JOIN fu_costs f USING (person_id)""")

for label, t in (("Baseline year (365 days before index)", "base_costs"), ("Follow-up (2025)", "fu_costs")):
    print(f"\n--- {label}, 2025 dollars")
    show(con, f"""
        SELECT coalesce(c.province, 'All') AS province, count(*) AS people,
               round(sum(x.hospital) / count(*)) AS hospital_per_person,
               round(sum(x.physician) / count(*)) AS physician_per_person,
               round(sum(x.drug) / count(*)) AS drug_per_person,
               round(sum(x.total) / count(*)) AS total_per_person,
               round(sum(x.total) / (sum(x.days) / 365.25)) AS total_per_person_year
        FROM fu c JOIN {t} x USING (person_id)
        GROUP BY ROLLUP (c.province) ORDER BY grouping(c.province), c.province""")

print("\n--- Follow-up: share of cost by component")
show(con, """SELECT round(100 * sum(hospital) / sum(total), 1) AS hospital_pct,
                    round(100 * sum(physician) / sum(total), 1) AS physician_pct,
                    round(100 * sum(drug) / sum(total), 1) AS drug_pct FROM fu_costs""")
--- Follow-up: deaths and person-time
 people  died_in_2025  person_years
   6224           432        6003.8

--- Baseline year (365 days before index), 2025 dollars
province  people  hospital_per_person  physician_per_person  drug_per_person  total_per_person  total_per_person_year
      ON    3956                 3927                   580             1137              5644                   5648
      QC    2268                 3744                   569              869              5181                   5185
     All    6224                 3860                   576             1039              5476                   5479

--- Follow-up (2025), 2025 dollars
province  people  hospital_per_person  physician_per_person  drug_per_person  total_per_person  total_per_person_year
      ON    3956                 3800                   544             1053              5397                   5582
      QC    2268                 3503                   526              766              4795                   4991
     All    6224                 3692                   537              948              5178                   5368

--- Follow-up: share of cost by component
 hospital_pct  physician_pct  drug_pct
         71.3           10.4      18.3

A person in the base cohort costs the public payer about $5,200 in 2025 ($5,368 per person-year). 71% of that is hospital care. Ontario costs more than Quebec mainly through drugs ($1,053 against $766 per person). Day 1 explains why: RAMQ's deductible and 32% coinsurance shift more of each prescription to the patient.

Try it (10 min). Using fct_person_year_costs, show the public payer cost per person-year for the whole population, 2019–2025, by province, in nominal and 2025 dollars.

Solution
"""Day 7 exercise: public payer cost per person-year, 2019-2025, nominal and in 2025 dollars, by province."""

import os
import sys

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

con = warehouse()
show(con, """
    SELECT year,
           round(sum(total) FILTER (province = 'ON') / (sum(days_observed) FILTER (province = 'ON') / 365.25)) AS on_nominal,
           round(sum(total_2025) FILTER (province = 'ON') / (sum(days_observed) FILTER (province = 'ON') / 365.25)) AS on_2025,
           round(sum(total) FILTER (province = 'QC') / (sum(days_observed) FILTER (province = 'QC') / 365.25)) AS qc_nominal,
           round(sum(total_2025) FILTER (province = 'QC') / (sum(days_observed) FILTER (province = 'QC') / 365.25)) AS qc_2025
    FROM fct_person_year_costs GROUP BY 1 ORDER BY 1""")
 year  on_nominal  on_2025  qc_nominal  qc_2025
 2019        1095     1278        1038     1212
 2020        1108     1275        1043     1201
 2021        1141     1288        1043     1178
 2022        1182     1284        1105     1199
 2023        1237     1299        1159     1216
 2024        1294     1325        1238     1268
 2025        1313     1313        1245     1245

In 2025 dollars, costs per person-year are almost flat: Ontario goes from $1,278 to $1,313. A chart in nominal dollars would suggest 20% growth. Always label which dollars a chart shows.


7.5 The wrong column for the perspective (20 min)

Bug of the day. A colleague costs the cohort's 2025 drugs with total_cost, what the pharmacy charged, instead of plan_paid:

"""Day 7 bug of the day: the wrong column for the perspective.

A colleague costs the cohort's 2025 drugs with total_cost (what the pharmacy charged)
instead of plan_paid (what the public plan paid).
"""

import os
import sys

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

con = warehouse()
build_base_cohort(con)
show(con, """
    SELECT c.province,
           round(sum(r.plan_paid) / count(DISTINCT c.person_id))    AS plan_paid_per_person,
           round(sum(r.total_cost) / count(DISTINCT c.person_id))   AS total_cost_per_person,
           round(100 * (sum(r.total_cost) / sum(r.plan_paid) - 1), 1) AS pct_overstated
    FROM cohort c JOIN fct_drug_dispensations r USING (person_id)
    WHERE r.dispense_year = 2025
    GROUP BY 1 ORDER BY 1""")
province  plan_paid_per_person  total_cost_per_person  pct_overstated
      ON                  1056                   1271            20.3
      QC                   769                   1197            55.6

Drug costs are overstated by 20% in Ontario and 56% in Quebec. Worse, the error differs between provinces, so a comparison of the two provinces is biased as well as inflated. The cause is Day 1's cost sharing: RAMQ patients pay a larger share. Name the perspective in the column you sum. payer_cost in int_cost_items is the only cost column the course's analyses use.


7.6 Mini-project: how are costs distributed? (60 min)

Describe the cohort's follow-up costs: mean and median, the share of cost in the top 10% of people, decedents against survivors, and whether last year's costs predict this year's. Save the person-level costs for Days 8–10.

"""Day 7 mini-project: how are follow-up costs distributed, and who costs the most?

Saves warehouse/cohort_costs.parquet (baseline and follow-up costs, 2025 dollars) for Days 8-10.
"""

import os
import sys

import matplotlib

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

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

con = warehouse()
build_base_cohort(con)
cohort_follow_up(con)
con.execute(f"""CREATE TEMP TABLE b AS
                {window_costs_sql('fu', 'i.index_date - INTERVAL 365 DAY', 'i.index_date - INTERVAL 1 DAY')}""")
END = "DATE '2025-12-31'"
con.execute(f"CREATE TEMP TABLE f AS {window_costs_sql('fu', 'i.index_date', END)}")
con.execute("""
    CREATE TEMP TABLE cohort_costs AS
    SELECT fu.person_id, fu.province, fu.died, fu.end_date, fu.heart_failure, fu.prior_stays,
           b.total AS baseline_cost, f.days AS fu_days, f.hospital AS fu_hospital, f.physician AS fu_physician,
           f.drug AS fu_drug, f.total AS fu_cost
    FROM fu JOIN b USING (person_id) JOIN f USING (person_id) ORDER BY person_id""")

print("--- Follow-up cost per person (2025 dollars)")
show(con, """
    SELECT round(avg(fu_cost)) AS mean, round(median(fu_cost)) AS median,
           round(quantile_cont(fu_cost, 0.9)) AS p90, round(max(fu_cost)) AS max,
           round(100 * avg((fu_cost = 0)::INT), 1) AS pct_zero,
           round(100 * (SELECT sum(fu_cost) FROM (SELECT fu_cost FROM cohort_costs ORDER BY fu_cost DESC
                         LIMIT (SELECT count(*) // 10 FROM cohort_costs))) / sum(fu_cost), 1) AS top10pct_share
    FROM cohort_costs""")

print("\n--- People who died vs survivors: per person and per person-year")
show(con, """
    SELECT died, count(*) AS people, round(avg(fu_days)) AS mean_days,
           round(avg(fu_cost)) AS cost_per_person,
           round(sum(fu_cost) / (sum(fu_days) / 365.25)) AS cost_per_person_year
    FROM cohort_costs GROUP BY 1 ORDER BY 1""")

print("\n--- Does the baseline year predict the follow-up year? (quintiles of baseline cost)")
show(con, """
    SELECT q AS baseline_quintile, count(*) AS people, round(avg(baseline_cost)) AS mean_baseline,
           round(sum(fu_cost) / (sum(fu_days) / 365.25)) AS fu_cost_per_person_year
    FROM (SELECT *, ntile(5) OVER (ORDER BY baseline_cost, person_id) AS q FROM cohort_costs)
    GROUP BY 1 ORDER BY 1""")

df = con.sql("SELECT fu_cost FROM cohort_costs").df()
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.hist(df.fu_cost / 1000, bins=60, color="#2563eb")
ax.axvline(df.fu_cost.mean() / 1000, color="#d97706", lw=2, label=f"mean ${df.fu_cost.mean():,.0f}")
ax.axvline(df.fu_cost.median() / 1000, color="#059669", lw=2, ls="--", label=f"median ${df.fu_cost.median():,.0f}")
ax.set_xlabel("Follow-up cost in 2025 (thousands of 2025 dollars)")
ax.set_ylabel("People")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day07_costs.png"), dpi=130, metadata={"Software": None})

path = os.path.join(ROOT, "warehouse", "cohort_costs.parquet")
con.execute(f"COPY cohort_costs TO '{path}' (FORMAT parquet)")
print("\nSaved figures/day07_costs.png and warehouse/cohort_costs.parquet")
--- Follow-up cost per person (2025 dollars)
 mean  median   p90   max  pct_zero  top10pct_share
 5178    1567 14911 59464       0.1            43.6

--- People who died vs survivors: per person and per person-year
 died  people  mean_days  cost_per_person  cost_per_person_year
False    5792        365             4841                  4845
 True     432        182             9687                 19396

--- Does the baseline year predict the follow-up year? (quintiles of baseline cost)
 baseline_quintile  people  mean_baseline  fu_cost_per_person_year
                 1    1245            583                     3481
                 2    1245           1135                     4463
                 3    1245           1797                     5293
                 4    1245           6390                     6655
                 5    1244          17484                     6973

Saved figures/day07_costs.png and warehouse/cohort_costs.parquet

Distribution of follow-up costs

Health care costs have a shape you will meet in every dataset:

  • Right-skewed. The mean ($5,178) is more than three times the median ($1,567). The 10% most expensive people account for 43.6% of all costs. Most people have no hospital stay, and one stay costs thousands. Module 2 starts with models built for this shape (log models, gamma GLMs, two-part models).
  • The last months of life are expensive. The 432 people who died cost $19,396 per person-year, four times survivors. Per person, they look only twice as expensive, because their follow-up is short. Per person-year is the fair comparison.
  • Past costs predict future costs, but they regress to the mean. The top baseline quintile cost $17,484 in the year before index, and $6,973 per person-year after it. A year with a big hospital stay is often followed by a quieter one. This regression to the mean will matter in Module 4, when programs target last year's high-cost patients.

7.7 Save your work

python -m pytest -q
git add .
git commit -m "Day 7: cost items, 2025 dollars, cohort costs"

Day 7 checklist

  • I can state the public payer perspective and list which cost columns it includes
  • Every cost is dated, priced in its own year, and converted to 2025 dollars with the CPI
  • My cost items reconcile to the claims to the cent (dbt test)
  • I report cohort costs per person and per person-year, in baseline and follow-up windows
  • I can describe the shape of health care costs: skewed, concentrated, highest near death