Applied Health Economics, RWE & HTA
Overview / Module 3 / Day 23
Module 3 · Causal inference for RWE · Day 23 of 100

Immortal Time and Other Time-Related Biases

The most common error in pharmacoepidemiology is not a wrong model but a wrong clock. Classify people by whether they ever used a drug and follow everyone from the same date, and every future user is guaranteed to survive until their first prescription: immortal time. Today you produce that bias on purpose (it makes Renavex look miraculous), then fix it with time-varying exposure built from dispensing records, test how much the grace period matters, and line up every Renavex estimate from Days 21–23 against the truth.

▶
Video for Day 23 coming soon

By the end of today you can

  • draw immortal time on a timeline and say which way it biases
  • never define exposure using information from after time zero
  • build time-varying exposure from dispensings with episodes and a stated grace period
  • check that my risk sets follow (start, stop] and that Python and R agree
  • line up several designs and say which question each answers

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:30
23.1 What immortal time is
0:30–1:00
23.2 'Ever users' vs 'never users'
1:00–1:15
Break
1:15–2:20
23.3 Time-varying exposure: person-months
2:20–2:35
Break
2:35–3:15
23.4 Episodes and the grace period
3:15–3:45
23.5 Dropping the immortal time is not enough
3:45–4:50
23.6 Mini-project: one question, every design
4:50–5:00
23.7 Save your work
5:00–5:30
Bloc français

In this lesson

23.1 What immortal time is (30 min)

"""Day 23.1: what immortal time looks like - four patients followed from 1 January 2026."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib  # noqa: E402

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

from corridor.db import ROOT  # noqa: E402

people = [("A: starts month 14, alive", 14, 36, False), ("B: starts month 3, dies month 20", 3, 20, True),
          ("C: never starts, dies month 6", None, 6, True), ("D: never starts, alive", None, 36, False)]
fig, ax = plt.subplots(figsize=(8, 2.8))
for i, (label, start, end, died) in enumerate(people):
    y = len(people) - i
    if start is None:
        ax.plot([0, end], [y, y], color="#9aa6bf", lw=6, solid_capstyle="butt")
    else:
        ax.plot([0, start], [y, y], color="#f5a524", lw=6, solid_capstyle="butt")
        ax.plot([start, end], [y, y], color="#3ecf8e", lw=6, solid_capstyle="butt")
    if died:
        ax.plot(end, y, "x", color="#e5484d", ms=10, mew=3)
    ax.text(-0.5, y, label, ha="right", va="center", fontsize=9)
ax.plot([], [], color="#f5a524", lw=6, label="'ever user', not yet treated: immortal time")
ax.plot([], [], color="#3ecf8e", lw=6, label="on Renavex")
ax.plot([], [], color="#9aa6bf", lw=6, label="never user")
ax.set(xlim=(-0.5, 37), ylim=(0.3, 4.8), xlabel="months since 1 January 2026", yticks=[])
ax.legend(loc="upper center", bbox_to_anchor=(0.45, -0.3), ncol=3, fontsize=8, frameon=False)
for s in ("left", "right", "top"):
    ax.spines[s].set_visible(False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day23_immortal_time.png"), dpi=130, bbox_inches="tight")
print("Person B is an 'ever user' and person C a never user. Under 'ever vs never', B's first 3 months count as")
print("treated time in which B could not have died - had B died then, B would have been a never user.")
Person B is an 'ever user' and person C a never user. Under 'ever vs never', B's first 3 months count as
treated time in which B could not have died - had B died then, B would have been a never user.

Immortal time

Patient B is an "ever user" from 1 January 2026, but only started in month 3. The first three months (orange) are counted as treated, and B could not have died in them: anyone who died before starting would have been a "never user", like C. Treated person-time gets free survival; untreated person-time gets the early deaths. The bias always favours the drug, and it grows with the delay before treatment starts.


23.2 'Ever users' vs 'never users' (30 min)

Bug of the day, made on purpose:

"""Day 23 bug of the day: 'ever users' vs 'never users', followed from the same date."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
from statsmodels.duration.hazard_regression import PHReg  # noqa: E402

from corridor.db import warehouse  # noqa: E402
from corridor.exposure import ADJUST  # noqa: E402
from corridor.rwe import baseline  # noqa: E402

b = baseline(warehouse())
b = b[b.renavex_2025 == 0].copy()
b["ever"] = b.t_renavex.notna().astype(int)
print(f"{len(b):,} people; {b.ever.sum():,} start Renavex at some point in 2026-2028")
print(f"deaths: ever users {b.died[b.ever == 1].mean():.1%}, never users {b.died[b.ever == 0].mean():.1%}")
for outcome, t in (("kf", "t_kf"), ("died", "t_end")):
    for label, x in (("crude", "ever"), ("adjusted", f"ever + {ADJUST}")):
        m = PHReg.from_formula(f"{t} ~ {x}", b, status=b[outcome], ties="efron").fit()
        print(f"{'kidney failure' if outcome == 'kf' else 'death':<15}{label:<10} HR {np.exp(m.params[0]):.2f} "
              f"({np.exp(m.params[0] - 1.96 * m.bse[0]):.2f}-{np.exp(m.params[0] + 1.96 * m.bse[0]):.2f})")
9,018 people; 3,299 start Renavex at some point in 2026-2028
deaths: ever users 6.7%, never users 16.4%
kidney failure crude      HR 1.50 (1.23-1.81)
kidney failure adjusted   HR 0.22 (0.18-0.28)
death          crude      HR 0.38 (0.33-0.44)
death          adjusted   HR 0.32 (0.27-0.38)

16.4% of never users died against 6.7% of ever users, and the adjusted hazard ratio for death is 0.32: a 68% reduction in mortality, from a drug whose true effect on the death hazard is 11%. For kidney failure, confounding by indication (crude 1.50) and immortal time pull in opposite directions; after adjustment, immortal time wins (0.22). Published studies with this design have reported implausibly large benefits (metformin and cancer is the best-known example) until reanalyses with time-varying exposure made most of the benefit disappear.


23.3 Time-varying exposure: person-months (65 min)

Split each person's follow-up into months. In each month, exposure is what it was at the start of the month: off before the first dispensing, on afterwards. Each month's row enters the risk set at its start and leaves at its end, so nobody is ever counted as treated before they were.

"""Day 23: exposure that changes over time - dispensing episodes and a person-month table.

A dispensing of `days_supply` days covers the person from the dispensing date to date + supply - 1.
Consecutive dispensings join into one episode if the gap is no longer than `grace` days; an episode
ends `grace` days after the last supply runs out.
"""

import os

import numpy as np
import pandas as pd

from corridor.rwe import D, START

M3 = os.path.join(os.path.dirname(D), "m3")

def episodes(disp, grace=30):
    """disp: person_id, dispense_date, days_supply (one drug). Returns person_id, ep_start, ep_end."""
    d = disp.sort_values(["person_id", "dispense_date"]).copy()
    d["dispense_date"] = pd.to_datetime(d["dispense_date"])
    d["cover_end"] = d.dispense_date + pd.to_timedelta(d.days_supply - 1, unit="D")
    prev_end = d.groupby("person_id").cover_end.shift()
    new = prev_end.isna() | ((d.dispense_date - prev_end).dt.days - 1 > grace)
    d["ep"] = new.groupby(d.person_id).cumsum()
    e = d.groupby(["person_id", "ep"]).agg(ep_start=("dispense_date", "min"), ep_end=("cover_end", "max")).reset_index()
    e["ep_end"] = e.ep_end + pd.Timedelta(days=grace)
    return e[["person_id", "ep_start", "ep_end"]]

def person_months(base, eps, labs, months=36):
    """One row per person and month of follow-up from 1 January 2026 (month 0): on_renavex (covered at the
    start of the month), started (any Renavex before the month started, ever after), the latest eGFR before
    the month (lagged), and kidney failure / death in the month."""
    start = pd.Timestamp(START)
    ids = base.person_id.to_numpy()
    pm = pd.DataFrame({"person_id": np.repeat(ids, months), "month": np.tile(np.arange(months), len(ids))})
    pm["m_start"] = start + pd.to_timedelta(pm.month * 30.4375, unit="D")
    pm["m_start"] = pm.m_start.dt.normalize()
    pm["m_end"] = pm.groupby("person_id").m_start.shift(-1).fillna(pd.Timestamp("2029-01-01")) - pd.Timedelta(days=1)
    b = base.set_index("person_id")
    pm = pm.join(b[["kf_date", "death_date", "renavex_date", "egfr10", "albuminuria", "sglt2_2025", "age10", "male",
                    "qc", "nephrology_care", "heart_failure", "copd", "prior_stays"]], on="person_id")
    stop = pm[["kf_date", "death_date"]].min(axis=1)
    pm = pm[stop.isna() | (stop >= pm.m_start)].copy()               # still at risk at the month start
    pm["kf"] = ((pm.kf_date >= pm.m_start) & (pm.kf_date <= pm.m_end)).astype(int)
    pm["death"] = ((pm.death_date >= pm.m_start) & (pm.death_date <= pm.m_end)).astype(int)
    pm["started"] = (pm.renavex_date < pm.m_start).astype(int)
    e = eps.merge(pm[["person_id", "month", "m_start"]], on="person_id")
    on = e[(e.ep_start < e.m_start) & (e.ep_end >= e.m_start)][["person_id", "month"]].drop_duplicates()
    on["on_renavex"] = 1
    pm = pm.merge(on, on=["person_id", "month"], how="left").fillna({"on_renavex": 0})
    lab = labs[labs.test == "egfr"].copy()
    lab["lab_date"] = pd.to_datetime(lab.lab_date).astype("datetime64[ns]")
    pm["m_start"] = pm.m_start.astype("datetime64[ns]")
    pm = pd.merge_asof(pm.sort_values("m_start"), lab.sort_values("lab_date")[["person_id", "lab_date", "value"]],
                       left_on="m_start", right_on="lab_date", by="person_id", allow_exact_matches=False)
    pm["egfr_now10"] = (45 - pm.value) / 10
    return pm.drop(columns=["value", "lab_date"]).sort_values(["person_id", "month"]).reset_index(drop=True)
def tv_cox(pm, exposure, outcome, extra=""):
    """Cox model on person-months (entry = month, exit = month + 1), exposure first. Returns HR and 95% CI."""
    from statsmodels.duration.hazard_regression import PHReg
    d = pm.dropna(subset=["egfr_now10"]) if "egfr_now10" in extra else pm
    m = PHReg.from_formula(f"exit ~ {exposure} + {ADJUST}{extra}", d.assign(exit=d.month + 1.0), status=d[outcome],
                           entry=d.month + 0.5, ties="breslow").fit()   # (month, month+1]: see Day 23.3
    b, se = m.params[0], m.bse[0]
    return float(np.exp(b)), float(np.exp(b - 1.96 * se)), float(np.exp(b + 1.96 * se))
"""Day 23.2-23.3: exposure that switches on when treatment starts - person-months and a time-varying Cox model."""

import os
import sys

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

b, pm, _, _ = build(warehouse())
print(f"{len(pm):,} person-months for {pm.person_id.nunique():,} people (m3/person_months.parquet)")
print(f"{int(pm.kf.sum())} kidney failures, {int(pm.death.sum())} deaths; {pm.on_renavex.mean():.1%} of person-months on Renavex")
rows = [("started (once started, always counted)", "started", ""),
        ("on Renavex (covered by a supply + 30 days)", "on_renavex", ""),
        ("on Renavex, + latest eGFR before the month", "on_renavex", " + egfr_now10")]
for outcome, name in (("kf", "kidney failure"), ("death", "death")):
    print(f"--- {name}")
    for label, e, extra in rows:
        hr, lo, hi = tv_cox(pm, e, outcome, extra)
        print(f"  {label:<46} HR {hr:.2f} ({lo:.2f}-{hi:.2f})")
297,617 person-months for 9,018 people (m3/person_months.parquet)
411 kidney failures, 1085 deaths; 18.4% of person-months on Renavex
--- kidney failure
  started (once started, always counted)         HR 0.85 (0.67-1.08)
  on Renavex (covered by a supply + 30 days)     HR 0.82 (0.65-1.03)
  on Renavex, + latest eGFR before the month     HR 0.80 (0.64-1.01)
--- death
  started (once started, always counted)         HR 0.96 (0.80-1.14)
  on Renavex (covered by a supply + 30 days)     HR 0.89 (0.74-1.07)
  on Renavex, + latest eGFR before the month     HR 0.88 (0.74-1.06)

Three definitions of exposure:

  • started: once started, always counted as exposed (like intention to treat): HR 0.85 for kidney failure.
  • on Renavex: exposed while covered by a dispensing plus a 30-day grace period (as treated): 0.82.
  • on Renavex, adjusted for the latest eGFR before each month: 0.80 (95% CI 0.64 to 1.01). Renavex is started when eGFR falls, so the most recent eGFR is a time-varying confounder, and this model adjusts for it as it changes.

The generator's hazard ratio while on Renavex is 0.75, inside the interval. Day 26 explains why adjusting for a time-varying confounder that the treatment itself affects (eGFR) can still bias this kind of model, and how marginal structural models avoid it.

A detail worth a paragraph. statsmodels' PHReg puts a row in the risk set at times ≥ its entry time; survival's coxph uses (start, stop]. With entry at the month boundary, statsmodels counted each person twice at the end of every month (the ending row and the next one), and gave 0.76 instead of 0.80. Entry at month + 0.5 gives the (start, stop] risk set, and the two languages now agree:

# Day 23: the time-varying Cox model in R, with counting-process (start, stop] data.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(survival) })
con <- dbConnect(duckdb(shared_home = FALSE))
pm <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/person_months.parquet')")
dbDisconnect(con, shutdown = TRUE)
adj <- "egfr10 + albuminuria + sglt2_2025 + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays"
for (out in c("kf", "death")) {
  f <- coxph(as.formula(paste0("Surv(month, month + 1, ", out, ") ~ on_renavex + ", adj, " + egfr_now10")),
             data = pm, ties = "breslow")
  ci <- exp(confint(f)["on_renavex", ])
  cat(sprintf("%-6s on Renavex, + latest eGFR: HR %.2f (%.2f-%.2f)\n", out, exp(coef(f)[["on_renavex"]]), ci[1], ci[2]))
}
kf     on Renavex, + latest eGFR: HR 0.80 (0.64-1.01)
death  on Renavex, + latest eGFR: HR 0.88 (0.74-1.06)

23.4 Episodes and the grace period (40 min)

Dispensing records say when a supply was handed over, not when pills were taken. Join dispensings into episodes of continuous use, allowing a grace period between the end of one supply and the next (late refills), and after the last one:

def episodes(disp, grace=30):
    """disp: person_id, dispense_date, days_supply (one drug). Returns person_id, ep_start, ep_end."""
    d = disp.sort_values(["person_id", "dispense_date"]).copy()
    d["dispense_date"] = pd.to_datetime(d["dispense_date"])
    d["cover_end"] = d.dispense_date + pd.to_timedelta(d.days_supply - 1, unit="D")
    prev_end = d.groupby("person_id").cover_end.shift()
    new = prev_end.isna() | ((d.dispense_date - prev_end).dt.days - 1 > grace)
    d["ep"] = new.groupby(d.person_id).cumsum()
    e = d.groupby(["person_id", "ep"]).agg(ep_start=("dispense_date", "min"), ep_end=("cover_end", "max")).reset_index()
    e["ep_end"] = e.ep_end + pd.Timedelta(days=grace)
    return e[["person_id", "ep_start", "ep_end"]]
"""Day 23.4: how long after the last supply is someone still 'on' the drug? The grace period."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402

from corridor.db import warehouse  # noqa: E402
from corridor.exposure import episodes, person_months, tv_cox  # noqa: E402
from corridor.rwe import D, baseline  # noqa: E402

b = baseline(warehouse())
b = b[b.renavex_2025 == 0].reset_index(drop=True)
disp = duckdb.sql(f"SELECT * FROM read_csv('{D}/rwe_dispensations.csv') WHERE drug = 'renavex'").df()
labs = duckdb.sql(f"SELECT * FROM read_csv('{D}/rwe_labs.csv')").df()
print(f"{'grace (days)':>12}{'episodes':>10}{'% months on':>13}{'kidney failure HR':>22}{'death HR':>20}")
for grace in (0, 30, 90, 180):
    eps = episodes(disp, grace)
    pm = person_months(b, eps, labs)
    kf = tv_cox(pm, "on_renavex", "kf", " + egfr_now10")
    de = tv_cox(pm, "on_renavex", "death", " + egfr_now10")
    print(f"{grace:>12}{len(eps):>10,}{100 * pm.on_renavex.mean():>12.1f}%"
          f"{kf[0]:>9.2f} ({kf[1]:.2f}-{kf[2]:.2f}){de[0]:>9.2f} ({de[1]:.2f}-{de[2]:.2f})")
grace (days)  episodes  % months on     kidney failure HR            death HR
           0    16,825        17.7%     0.75 (0.60-0.95)     0.88 (0.73-1.05)
          30     4,394        18.4%     0.80 (0.64-1.01)     0.88 (0.74-1.06)
          90     4,296        18.7%     0.79 (0.63-0.99)     0.90 (0.75-1.08)
         180     4,202        19.1%     0.77 (0.61-0.97)     0.91 (0.76-1.09)

Without a grace period, every refill a few days late breaks the episode, and 4,394 episodes become 16,825. The hazard ratios still range only from 0.75 to 0.80 for kidney failure, because the people who stop for good dominate the off-treatment time. Report a sensitivity analysis like this one; reviewers will ask, and a result that hinged on the grace period would need explaining.


23.5 Dropping the immortal time is not enough (30 min)

Try it (20 min). Follow users only from their first dispensing (dropping their immortal time) and never users from 1 January 2026. Does that fix the ever–never analysis?

Solution
"""Day 23 try it: drop the immortal time - users followed from their first dispensing, never users from 1 January 2026."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
from statsmodels.duration.hazard_regression import PHReg  # noqa: E402

from corridor.db import warehouse  # noqa: E402
from corridor.exposure import ADJUST  # noqa: E402
from corridor.rwe import baseline  # noqa: E402

b = baseline(warehouse())
b = b[b.renavex_2025 == 0].copy()
b["ever"] = b.t_renavex.notna().astype(int)
b["entry"] = np.where(b.ever == 1, b.t_renavex - 0.5, 0.0)       # at risk from the first dispensing day
for outcome, t in (("kf", "t_kf"), ("died", "t_end")):
    d = b[b[t] > b.entry]
    m = PHReg.from_formula(f"{t} ~ ever + {ADJUST}", d, status=d[outcome], entry=d.entry, ties="efron").fit()
    print(f"{'kidney failure' if outcome == 'kf' else 'death':<15} HR {np.exp(m.params[0]):.2f} "
          f"({np.exp(m.params[0] - 1.96 * m.bse[0]):.2f}-{np.exp(m.params[0] + 1.96 * m.bse[0]):.2f})")
kidney failure  HR 0.37 (0.30-0.48)
death           HR 0.62 (0.52-0.74)

Better than 0.22 and 0.32, still far from the truth (0.37 for kidney failure, 0.62 for death). Users now start the clock at their first dispensing, but never users start on 1 January 2026, and "never user" is still defined by the future: a person counted as a never user had to stay off Renavex until the end of the data, often because they died first. Only designs where everyone's exposure is defined by what has already happened (time-varying exposure, landmarks, sequential trials) remove the bias.

Why it matters at work: Immortal time bias is one of the first things RWE reviewers check, because it is common and always favours the drug. A study that defines exposure as "ever used during follow-up" will not survive an HTA review.

Where you'll meet this: drug safety and effectiveness studies from claims, registries and EHRs; critical appraisal of observational evidence (Module 7)


23.6 Mini-project: one question, every design (65 min)

Put every Renavex estimate from Days 21–23 in one table, with what it estimates and how it compares with the truth:

"""Day 23 mini-project: one question (does Renavex prevent kidney failure?), every design of Days 21-23.

Estimates are copied from this module's outputs (re-run the scripts to refresh them); the truths come
from the generator: Renavex multiplies the kidney failure hazard by 0.75 while taken (and slows eGFR
decline), and the true 24-month risk ratio for starting in the sequential trials is 0.77 among starters.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import pandas as pd  # noqa: E402

rows = [
    ("dashboard: rate on vs off Renavex (Day 21)", "none", "3.63", "confounded by indication"),
    ("ever vs never, adjusted (Day 23 bug)", "baseline covariates", "0.22", "immortal time"),
    ("ever vs never, immortal time dropped (Day 23 try it)", "baseline covariates", "0.37", "time zero still misaligned"),
    ("landmark at 6 months (Day 21)", "the DAG's set", "0.71", "the effect of starting in the first 6 months"),
    ("sequential trials, g-formula (Day 22)", "covariates at each trial start", "0.80 (risk ratio)", "true risk ratio 0.77"),
    ("time-varying, on Renavex, + latest eGFR (Day 23)", "baseline + time-updated eGFR", "0.80", "true hazard ratio while on: 0.75"),
]
print(pd.DataFrame(rows, columns=["design", "adjusted for", "estimate", "what it answers / truth"]).to_string(index=False))
                                              design                   adjusted for          estimate                      what it answers / truth
          dashboard: rate on vs off Renavex (Day 21)                           none              3.63                     confounded by indication
                ever vs never, adjusted (Day 23 bug)            baseline covariates              0.22                                immortal time
ever vs never, immortal time dropped (Day 23 try it)            baseline covariates              0.37                   time zero still misaligned
                       landmark at 6 months (Day 21)                  the DAG's set              0.71 the effect of starting in the first 6 months
               sequential trials, g-formula (Day 22) covariates at each trial start 0.80 (risk ratio)                         true risk ratio 0.77
    time-varying, on Renavex, + latest eGFR (Day 23)   baseline + time-updated eGFR              0.80             true hazard ratio while on: 0.75

From the same data, the "effect of Renavex on kidney failure" ranges from a 3.6-fold harm to a 78% benefit. The designs that align time zero (landmark, sequential trials, time-varying exposure) all land between 0.71 and 0.80, near the truth. The others are not small variations; they answer the wrong question. Write the paragraph you would send a payer who has seen the dashboard (21.6) and a published "ever user" study (23.2).

23.7 Save your work

python -m pytest -q
git add .
git commit -m "Day 23: immortal time, time-varying exposure, grace periods"

Day 23 checklist

  • I can draw immortal time on a timeline and say which way it biases
  • I never define exposure using information from after time zero
  • I build time-varying exposure from dispensings with episodes and a stated grace period
  • I check that my risk sets follow (start, stop] and that Python and R agree
  • I can line up several designs and say which question each answers