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

DAGs for Clinical Questions

Before any model, write down what causes what. A directed acyclic graph (DAG) turns clinical knowledge into a precise answer to "what should I adjust for?" and an equally precise warning when no adjustment can work. Today you write a small DAG library, test it on the classic structures, draw the DAG for Renavex and kidney failure, and see confounding by indication in the data: the people who get Renavex are the people most likely to have kidney failure anyway.

▶
Video for Day 21 coming soon

By the end of today you can

  • write the causal question with population, strategies, outcome and time frame
  • find valid adjustment sets with d-separation and explain chains, forks and colliders
  • never adjust for mediators, colliders or other descendants of the treatment
  • show confounding by indication with a treatment model and an outcome model
  • say when a DAG shows that no measured adjustment is enough (death and frailty)

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:35
21.1 The question and the extract
0:35–1:20
21.2 DAGs, d-separation and the backdoor criterion
1:20–1:35
Break
1:35–2:05
21.3 Confounder, mediator, collider: a simulation
2:05–2:45
21.4 The DAG for Renavex
2:45–3:00
Break
3:00–3:35
21.5 Confounding by indication in the data
3:35–3:50
21.6 A dashboard of rates on and off the drug
3:50–4:50
21.7 Mini-project: a first adjusted comparison
4:50–5:00
21.8 Save your work
5:00–5:30
Bloc français

In this lesson

21.1 The question and the extract (35 min)

A causal question names a population, two (or more) strategies, an outcome and a time frame:

Among adults with type 2 diabetes and CKD (eGFR 20–60) in Ontario and Quebec, does starting Renavex, compared with not starting it, reduce the risk of kidney failure within 24 months?

Every word matters later. "Starting" means new users (Day 22), "within 24 months" fixes time zero and follow-up (Days 22–23), and "compared with not starting" says the comparator is usual care, not placebo.

Regenerate the data, then load the extract with its baseline history:

python data/make_data.py
"""Days 21-30: the Renavex real-world extract (2026-2028) joined to the warehouse (2019-2025).

The extract covers adults with type 2 diabetes and CKD stage 3a-4 alive and not on dialysis on
1 January 2026: lab results (eGFR, urine albumin-to-creatinine ratio), Renavex and new SGLT2 inhibitor
dispensations, and outcomes (kidney failure, hospitalization, death) to 31 December 2028.
Baseline history comes from the 2019-2025 claims in the warehouse.
"""

import os

import numpy as np
import pandas as pd

from corridor.cohort import baseline_sql
from corridor.db import DATA

START, END = "2026-01-01", "2028-12-31"
D = DATA.replace("\\", "/")

def register(con):
    """Views rwe_persons, rwe_labs, rwe_dispensations, rwe_events on a connection."""
    for name, types in (("rwe_persons", ""), ("rwe_labs", ""), ("rwe_dispensations", ""), ("rwe_events", "")):
        con.execute(f"CREATE OR REPLACE TEMP VIEW {name} AS SELECT * FROM read_csv('{D}/{name}.csv')")

BASELINE_SQL = f"""
WITH ix AS (SELECT person_id, DATE '{START}' AS index_date FROM rwe_persons),
egfr AS (
    SELECT person_id, arg_max(value, lab_date) AS egfr, max(lab_date) AS egfr_date
    FROM rwe_labs WHERE test = 'egfr' AND lab_date < DATE '{START}' GROUP BY 1),
uacr AS (
    SELECT person_id, arg_max(value, lab_date) AS uacr
    FROM rwe_labs WHERE test = 'uacr' AND lab_date < DATE '{START}' GROUP BY 1),
first_event AS (
    SELECT person_id,
           min(event_date) FILTER (event = 'kidney_failure') AS kf_date,
           min(event_date) FILTER (event = 'death') AS death_date
    FROM rwe_events GROUP BY 1),
start_rx AS (
    SELECT person_id,
           min(dispense_date) FILTER (drug = 'renavex') AS renavex_date,
           min(dispense_date) FILTER (drug = 'sglt2') AS new_sglt2_date
    FROM rwe_dispensations GROUP BY 1)
SELECT p.person_id, d.province, d.region, d.sex, age_on(d.birth_date, DATE '{START}') AS age, d.income_quintile,
       d.rural::INT AS rural, p.usual_prescriber, p.nephrology_care,
       (p.renavex_start_2025 IS NOT NULL)::INT AS renavex_2025,
       e.egfr, e.egfr_date, u.uacr, (u.uacr >= 30)::INT AS albuminuria,
       b.heart_failure::INT AS heart_failure, b.copd::INT AS copd, b.prior_stays, b.sglt2::INT AS sglt2_2025,
       b.insulin::INT AS insulin, b.physician_visits,
       f.kf_date, f.death_date, s.renavex_date, s.new_sglt2_date
FROM rwe_persons p
JOIN dim_person d USING (person_id)
JOIN ({{baseline}}) b USING (person_id)
LEFT JOIN egfr e USING (person_id)
LEFT JOIN uacr u USING (person_id)
LEFT JOIN first_event f USING (person_id)
LEFT JOIN start_rx s USING (person_id)
ORDER BY p.person_id"""

def baseline(con):
    """One row per person: who they were on 1 January 2026, and what happened later (dates)."""
    register(con)
    con.execute(f"CREATE OR REPLACE TEMP TABLE rwe_index AS SELECT person_id, DATE '{START}' AS index_date FROM rwe_persons")
    df = con.sql(BASELINE_SQL.replace("{baseline}", baseline_sql("rwe_index"))).df()
    for c in ("kf_date", "death_date", "renavex_date", "new_sglt2_date", "egfr_date"):
        df[c] = pd.to_datetime(df[c])
    end = pd.Timestamp(END)
    df["end_date"] = df[["death_date"]].min(axis=1).fillna(end)
    df["t_end"] = (df.end_date - pd.Timestamp(START)).dt.days + 1           # days, day 1 = 1 Jan 2026
    df["died"] = df.death_date.notna().astype(int)
    df["kf"] = df.kf_date.notna().astype(int)
    df["t_kf"] = np.where(df.kf == 1, (df.kf_date - pd.Timestamp(START)).dt.days + 1, df.t_end)
    df["t_renavex"] = (df.renavex_date - pd.Timestamp(START)).dt.days + 1    # NaN if never dispensed
    df["egfr10"] = (45 - df.egfr) / 10                                      # lower eGFR = higher value
    df["age10"] = (df.age - 70) / 10
    df["male"] = (df.sex == "M").astype(int)
    df["qc"] = (df.province == "QC").astype(int)
    return df

The baseline is 1 January 2026. Lab values come from the last result before that date, and diagnoses, drugs and hospital stays from the 365 days before it (Day 5's baseline_sql). Dates of later events stay as dates, so each day can choose its own time zero.


21.2 DAGs, d-separation and the backdoor criterion (45 min)

A DAG has an arrow from X to Y when X directly affects Y. Paths between treatment A and outcome Y carry association; only the directed ones (A → … → Y) carry causation. Three building blocks decide whether a path is open:

StructureExamplePath open?If you condition on the middle node
chain A → M → YRenavex → eGFR later → kidney failureopenblocked (you remove part of the effect)
fork A ← L → YRenavex ← low eGFR → kidney failureopenblocked (confounding removed)
collider A → C ← YRenavex → hospitalization ← kidney failureblockedopened (selection bias)

The backdoor criterion: a set Z identifies the effect of A on Y if no variable in Z is a descendant of A, and Z blocks every path from A to Y that starts with an arrow into A. corridor/dag.py implements d-separation (via the moral ancestral graph) and searches for minimal adjustment sets:

"""Day 21: directed acyclic graphs (DAGs) - d-separation and the backdoor criterion, in plain Python.

A DAG is a dict: node -> list of its parents. Two nodes are d-separated given Z when every path
between them is blocked: a path is blocked at a non-collider that is in Z, or at a collider that is
not in Z and has no descendant in Z. The test below uses the moral ancestral graph (Lauritzen):
keep X, Y, Z and their ancestors, marry parents of a common child, drop arrows, delete Z, and ask
whether X can still reach Y.
"""

from itertools import combinations

class DAG:
    def __init__(self, parents):
        self.parents = {k: list(v) for k, v in parents.items()}
        for v in list(self.parents.values()):
            for p in v:
                self.parents.setdefault(p, [])
        self.nodes = sorted(self.parents)

    def children(self, node):
        return [c for c, ps in self.parents.items() if node in ps]

    def ancestors(self, nodes):
        out, stack = set(nodes), list(nodes)
        while stack:
            for p in self.parents[stack.pop()]:
                if p not in out:
                    out.add(p)
                    stack.append(p)
        return out

    def descendants(self, node):
        out, stack = set(), [node]
        while stack:
            for c in self.children(stack.pop()):
                if c not in out:
                    out.add(c)
                    stack.append(c)
        return out

    def d_separated(self, x, y, z=()):
        z = set(z)
        keep = self.ancestors({x, y} | z)
        adj = {n: set() for n in keep}
        for child in keep:
            ps = [p for p in self.parents[child] if p in keep]
            for p in ps:
                adj[p].add(child)
                adj[child].add(p)
            for a, b in combinations(ps, 2):          # marry the parents
                adj[a].add(b)
                adj[b].add(a)
        seen, stack = {x}, [x]
        while stack:
            for n in adj[stack.pop()] - z:
                if n == y:
                    return False
                if n not in seen:
                    seen.add(n)
                    stack.append(n)
        return True

    def backdoor_ok(self, treatment, outcome, z):
        """Z satisfies the backdoor criterion: no descendant of the treatment, and Z blocks every path
        from treatment to outcome that starts with an arrow INTO the treatment."""
        z = set(z)
        if z & self.descendants(treatment):
            return False
        cut = DAG({n: [p for p in ps if not (p == treatment)] for n, ps in self.parents.items()})
        return cut.d_separated(treatment, outcome, z)

    def adjustment_sets(self, treatment, outcome, candidates=None, minimal=True):
        """All valid backdoor adjustment sets drawn from `candidates` (default: every other node).
        With minimal=True, only those with no valid proper subset."""
        pool = [n for n in (candidates or self.nodes) if n not in (treatment, outcome)]
        valid = [set(c) for k in range(len(pool) + 1) for c in combinations(pool, k)
                 if self.backdoor_ok(treatment, outcome, c)]
        if minimal:
            valid = [s for s in valid if not any(t < s for t in valid)]
        return [sorted(s) for s in valid]
"""Day 21.2: d-separation and adjustment sets on three small graphs."""

import os
import sys

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

graphs = {
    "confounder: A <- L -> Y, A -> Y": (DAG({"A": ["L"], "Y": ["A", "L"]}), ["L"]),
    "mediator: A -> M -> Y, A -> Y": (DAG({"M": ["A"], "Y": ["A", "M"]}), ["M"]),
    "collider: A -> C <- Y, A -> Y": (DAG({"C": ["A", "Y"], "Y": ["A"]}), ["C"]),
    "M-bias: A <- U1 -> C <- U2 -> Y": (DAG({"A": ["U1"], "C": ["U1", "U2"], "Y": ["A", "U2"]}), ["C"]),
}
for name, (g, z) in graphs.items():
    print(f"{name}")
    print(f"   adjust for nothing: {'valid' if g.backdoor_ok('A', 'Y', []) else 'NOT valid'};   "
          f"adjust for {z[0]}: {'valid' if g.backdoor_ok('A', 'Y', z) else 'NOT valid'};   "
          f"minimal sets: {g.adjustment_sets('A', 'Y', [n for n in g.nodes if not n.startswith('U')])}")
confounder: A <- L -> Y, A -> Y
   adjust for nothing: NOT valid;   adjust for L: valid;   minimal sets: [['L']]
mediator: A -> M -> Y, A -> Y
   adjust for nothing: valid;   adjust for M: NOT valid;   minimal sets: [[]]
collider: A -> C <- Y, A -> Y
   adjust for nothing: valid;   adjust for C: NOT valid;   minimal sets: [[]]
M-bias: A <- U1 -> C <- U2 -> Y
   adjust for nothing: valid;   adjust for C: NOT valid;   minimal sets: [[]]

Adjusting is not always safe. Adjusting for the mediator or the collider breaks a correct analysis. In M-bias, a pre-treatment variable that is merely associated with both treatment and outcome (through two different unmeasured causes) is a collider, and adjusting for it opens a path. "Adjust for everything measured at baseline" is a heuristic, not a rule.


21.3 Confounder, mediator, collider: a simulation (30 min)

Three worlds, each with a true total effect of 1.0:

def dag_structures(n=50_000, seed=2026):
    """Three small worlds, each with a true effect of A on Y of 1.0:
    confounder (L -> A, L -> Y), mediator (A -> M -> Y plus A -> Y), collider (A -> C <- Y)."""
    rng = np.random.default_rng(seed)
    out = {}
    L = rng.normal(size=n)
    A = 0.8 * L + rng.normal(size=n)
    out["confounder"] = pd.DataFrame({"A": A, "L": L, "Y": 1.0 * A + 1.5 * L + rng.normal(size=n)})
    A = rng.normal(size=n)
    M = 0.6 * A + rng.normal(size=n)
    out["mediator"] = pd.DataFrame({"A": A, "M": M, "Y": 0.4 * A + 1.0 * M + rng.normal(size=n)})  # total 0.4 + 0.6
    A = rng.normal(size=n)
    Y = 1.0 * A + rng.normal(size=n)
    out["collider"] = pd.DataFrame({"A": A, "Y": Y, "C": A + Y + rng.normal(size=n)})
    return out
"""Day 21.3: adjust or not? Three simulated worlds where the true total effect of A on Y is 1.0."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf  # noqa: E402

from corridor.sim import dag_structures  # noqa: E402

for name, d in dag_structures().items():
    other = [c for c in d.columns if c not in ("A", "Y")][0]
    crude = smf.ols("Y ~ A", d).fit().params["A"]
    adj = smf.ols(f"Y ~ A + {other}", d).fit().params["A"]
    print(f"{name:<11} crude {crude:5.2f}   adjusted for {other}: {adj:5.2f}   (truth 1.00)")
confounder  crude  1.74   adjusted for L:  1.00   (truth 1.00)
mediator    crude  0.99   adjusted for M:  0.40   (truth 1.00)
collider    crude  1.01   adjusted for C:  0.01   (truth 1.00)

The DAG predicts each row: adjusting for the confounder fixes the estimate (1.74 → 1.00), adjusting for the mediator removes the indirect effect (1.00 → 0.40), and adjusting for the collider manufactures a near-zero effect out of a real one.


21.4 The DAG for Renavex (40 min)

"""Day 21: the working DAG for 'does starting Renavex in routine care prevent kidney failure?'.

Arrows say what causes what in the course's world (the generator); 'frailty' is not measured.
"""

from corridor.dag import DAG

RENAVEX_DAG = DAG({
    "renavex": ["egfr", "albuminuria", "nephrology", "age", "frailty", "prescriber", "sglt2", "province"],
    "sglt2": ["egfr", "albuminuria", "nephrology", "prescriber"],
    "nephrology": ["egfr", "albuminuria"],
    "egfr_later": ["egfr", "albuminuria", "renavex", "sglt2"],
    "kidney_failure": ["egfr_later", "renavex", "sglt2"],
    "death": ["age", "frailty", "heart_failure", "copd", "kidney_failure", "renavex", "egfr_later"],
    "heart_failure": ["age"],
    "hospitalization": ["frailty", "heart_failure", "kidney_failure"],
})
UNMEASURED = {"frailty"}
POSITIONS = {"province": (0, 4), "prescriber": (0, 2.6), "age": (1.2, 5), "frailty": (3.2, 5.3),
             "egfr": (0, 1.2), "albuminuria": (0, 0), "nephrology": (1.4, 0.4), "sglt2": (2.2, 2.4),
             "renavex": (2.4, 3.8), "egfr_later": (4.2, 1.2), "kidney_failure": (5.8, 2.2),
             "death": (6.6, 4.2), "heart_failure": (4.4, 5.0), "copd": (5.6, 5.4), "hospitalization": (7.4, 3.0)}
"""Day 21.4: the DAG for Renavex and kidney failure, and what to adjust for."""

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
from corridor.renavex_dag import POSITIONS, RENAVEX_DAG, UNMEASURED  # noqa: E402

g = RENAVEX_DAG
measured = [n for n in g.nodes if n not in UNMEASURED]
for outcome in ("kidney_failure", "death"):
    sets = g.adjustment_sets("renavex", outcome, [n for n in measured if n not in ("egfr_later", "hospitalization")])
    print(f"--- renavex -> {outcome}: minimal adjustment sets from MEASURED variables")
    print("   " + ("\n   ".join(", ".join(s) for s in sets) if sets else "none: the unmeasured confounder (frailty) leaves a backdoor path open"))
base = ["egfr", "albuminuria", "sglt2"]
for extra in ([], ["egfr_later"], ["prescriber"], ["age", "nephrology"]):
    z = base + extra
    print(f"kidney failure, adjust for {', '.join(z)}: {'valid' if g.backdoor_ok('renavex', 'kidney_failure', z) else 'NOT valid'}")
print(f"death, adjust for everything measured at baseline: "
      f"{'valid' if g.backdoor_ok('renavex', 'death', ['egfr', 'albuminuria', 'sglt2', 'age', 'heart_failure', 'copd', 'nephrology']) else 'NOT valid (frailty is open)'}")

fig, ax = plt.subplots(figsize=(9.5, 5))
for child, ps in g.parents.items():
    for p in ps:
        (x0, y0), (x1, y1) = POSITIONS[p], POSITIONS[child]
        hot = p == "renavex"
        ax.annotate("", xy=(x1, y1), xytext=(x0, y0), arrowprops=dict(
            arrowstyle="-|>", color="#3ecf8e" if hot else "#9aa6bf", lw=1.6 if hot else 0.9, shrinkA=22, shrinkB=22))
for n, (x, y) in POSITIONS.items():
    fc = "#fde2e2" if n in UNMEASURED else ("#d9f7e9" if n in ("renavex", "kidney_failure") else "#eef2ff")
    ax.text(x, y, n.replace("_", " "), ha="center", va="center", fontsize=9,
            bbox=dict(boxstyle="round,pad=0.35", fc=fc, ec="#555", ls="--" if n in UNMEASURED else "-"))
ax.set(xlim=(-0.8, 8.2), ylim=(-0.6, 6))
ax.axis("off")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day21_renavex_dag.png"), dpi=130)
--- renavex -> kidney_failure: minimal adjustment sets from MEASURED variables
   albuminuria, egfr, sglt2
--- renavex -> death: minimal adjustment sets from MEASURED variables
   none: the unmeasured confounder (frailty) leaves a backdoor path open
kidney failure, adjust for egfr, albuminuria, sglt2: valid
kidney failure, adjust for egfr, albuminuria, sglt2, egfr_later: NOT valid
kidney failure, adjust for egfr, albuminuria, sglt2, prescriber: valid
kidney failure, adjust for egfr, albuminuria, sglt2, age, nephrology: valid
death, adjust for everything measured at baseline: NOT valid (frailty is open)

The working DAG for Renavex

For kidney failure the minimal set is baseline eGFR, albuminuria and SGLT2 use. Adding age or nephrology care keeps the set valid. Adding eGFR measured after starting (a mediator) does not. For death, no set of measured variables works: frailty makes doctors less likely to start Renavex and makes death more likely, and it is not in the data. The DAG tells you this before you fit a model, so the report can say which result is credible and which needs a sensitivity analysis (Day 28).

sglt2 in the DAG means use at baseline. An SGLT2 inhibitor started after Renavex is a consequence of the treatment decision, not a confounder of it.

Try it (15 min). Is the usual prescriber a confounder, an instrument, or both? Use the DAG functions.

Solution
"""Day 21 try it: is the usual prescriber a confounder, an instrument, or both? Ask the DAG."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.dag import DAG  # noqa: E402
from corridor.renavex_dag import RENAVEX_DAG as g  # noqa: E402

print("paths from prescriber to kidney failure that avoid Renavex:",
      not g.d_separated("prescriber", "kidney_failure", ["renavex"]))
print("...once SGLT2 is in the adjustment set:",
      not g.d_separated("prescriber", "kidney_failure", ["renavex", "sglt2", "egfr", "albuminuria"]))
no_sglt = DAG({k: [p for p in v if not (k == "sglt2" and p == "prescriber")] for k, v in g.parents.items()})
print("if prescribers did not also drive SGLT2 use, prescriber is an instrument:",
      no_sglt.d_separated("prescriber", "kidney_failure", ["renavex", "egfr", "albuminuria", "sglt2"]))
print("adjustment set with prescriber instead of SGLT2 valid?",
      g.backdoor_ok("renavex", "kidney_failure", ["egfr", "albuminuria", "prescriber", "nephrology"]))
paths from prescriber to kidney failure that avoid Renavex: True
...once SGLT2 is in the adjustment set: False
if prescribers did not also drive SGLT2 use, prescriber is an instrument: True
adjustment set with prescriber instead of SGLT2 valid? False

Prescribers who like Renavex also start more SGLT2 inhibitors, and SGLT2 inhibitors protect the kidneys. So the prescriber reaches kidney failure through SGLT2 use: a confounder path, closed by adjusting for SGLT2. Once SGLT2 use is adjusted for, the prescriber affects kidney failure only through Renavex, which is what an instrument needs (Day 36). Adjusting for the prescriber cannot replace adjusting for SGLT2, because SGLT2 use also directly confounds Renavex.


21.5 Confounding by indication in the data (35 min)

Who starts Renavex in 2026, and who has kidney failure in 2026–2028? Fit both models with the same baseline variables:

"""Day 21.5: confounding by indication - who starts Renavex in 2026, and who has kidney failure?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402
import statsmodels.formula.api as smf  # noqa: E402

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

b = baseline(warehouse())
print(f"{len(b):,} people in the extract on 1 January 2026; {b.renavex_2025.sum()} already on Renavex (started 2025)")
d = b[(b.renavex_2025 == 0)].copy()
d["start_2026"] = (d.t_renavex <= 365).astype(int)
X = "egfr10 + albuminuria + nephrology_care + sglt2_2025 + age10 + male + qc + heart_failure + copd + prior_stays"
treat = smf.logit(f"start_2026 ~ {X}", d).fit(disp=0)
out = smf.logit(f"kf ~ {X}", d).fit(disp=0)
t = pd.DataFrame({"OR start Renavex in 2026": np.exp(treat.params), "OR kidney failure 2026-28": np.exp(out.params)}).drop("Intercept")
print(f"\n{d.start_2026.sum():,} of {len(d):,} started Renavex in 2026")
print(t.round(2).to_string())
print("\n(egfr10 = 10 points LOWER eGFR at baseline)")
9,805 people in the extract on 1 January 2026; 787 already on Renavex (started 2025)

1,356 of 9,018 started Renavex in 2026
                 OR start Renavex in 2026  OR kidney failure 2026-28
egfr10                               1.92                       4.81
albuminuria                          2.05                       1.13
nephrology_care                      2.01                       0.91
sglt2_2025                           1.28                       0.78
age10                                0.75                       0.97
male                                 1.03                       0.84
qc                                   0.94                       0.84
heart_failure                        0.93                       0.88
copd                                 1.07                       0.64
prior_stays                          1.04                       1.11

(egfr10 = 10 points LOWER eGFR at baseline)

Each 10 points of lower eGFR doubles the odds of starting Renavex (OR 1.92) and multiplies the odds of kidney failure by almost five (OR 4.81). Albuminuria and nephrology care push towards treatment too. Doctors are doing their job: they treat the people at highest risk. That is confounding by indication, and any comparison that ignores it will make the drug look harmful.

Why it matters at work: Confounding by indication is the first objection a CDA-AMC or INESSS reviewer raises to an observational effectiveness claim. The DAG is how you show you thought about it before seeing the results.

Where you'll meet this: every RWE protocol (the "confounders" section), comparative effectiveness for reassessment and reimbursement renewals, pharmacovigilance studies


21.6 A dashboard of rates on and off the drug (15 min)

Bug of the day. A provincial analytics team publishes kidney failure rates for person-time on and off Renavex:

"""Day 21 bug of the day: a dashboard of kidney failure rates on and off Renavex."""

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.rwe import baseline  # noqa: E402

b = baseline(warehouse())
b = b[b.renavex_2025 == 0]
start = b.t_renavex.where(b.t_renavex < b.t_kf)                   # started before any kidney failure
on_py = ((b.t_kf - start).clip(lower=0).fillna(0)) / 365.25
off_py = (start.fillna(b.t_kf) / 365.25)
kf_on = ((b.kf == 1) & start.notna()).sum()
kf_off = ((b.kf == 1) & start.isna()).sum()
print(f"kidney failure per 100 person-years ON Renavex:  {100 * kf_on / on_py.sum():.2f}  ({kf_on} events, {on_py.sum():,.0f} PY)")
print(f"kidney failure per 100 person-years OFF Renavex: {100 * kf_off / off_py.sum():.2f}  ({kf_off} events, {off_py.sum():,.0f} PY)")
print(f"rate ratio {(kf_on / on_py.sum()) / (kf_off / off_py.sum()):.2f}  <- the dashboard's headline: 'Renavex users fail faster'")
kidney failure per 100 person-years ON Renavex:  3.94  (197 events, 5,003 PY)
kidney failure per 100 person-years OFF Renavex: 1.08  (214 events, 19,737 PY)
rate ratio 3.63  <- the dashboard's headline: 'Renavex users fail faster'

Kidney failure is 3.6 times as common on Renavex. The person-time is counted correctly, and the conclusion is still wrong: the people on Renavex had much lower eGFR to begin with. A rate on treatment versus off treatment answers "who gets the drug?", not "what does the drug do?".


21.7 Mini-project: a first adjusted comparison (60 min)

Compare people who started Renavex in the first six months of 2026 with people who had not, counting kidney failure from 1 July 2026 (a landmark: everyone is alive and kidney failure-free at the start of follow-up, so nobody's treatment status depends on surviving). Adjust with the DAG's set, then with more, then (wrongly) with a mediator:

"""Day 21.6: a first comparison - and the bug of adjusting for a mediator.

Landmark at 1 July 2026: people who started Renavex by then vs those who had not, among people alive,
free of kidney failure and not on Renavex before 2026. Kidney failure is counted from 1 July 2026.
"""

import os
import sys

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

from corridor.db import warehouse  # noqa: E402
from corridor.rwe import D, baseline  # noqa: E402

LAND = 182                                         # day 182 = 1 July 2026
b = baseline(warehouse())
d = b[(b.renavex_2025 == 0) & (b.t_kf > LAND) & (b.t_end > LAND)].copy()
d["early"] = (d.t_renavex <= LAND).fillna(False).astype(int)
d["t"] = d.t_kf - LAND
later = duckdb.sql(f"""SELECT person_id, arg_max(value, lab_date) AS egfr_last FROM read_csv('{D}/rwe_labs.csv')
                       WHERE test = 'egfr' GROUP BY 1""").df()      # the LAST eGFR on record
d = d.merge(later, on="person_id", how="left")
d["egfr_last10"] = (45 - d.egfr_last) / 10
print(f"{len(d):,} people at the landmark; {d.early.sum()} started Renavex in the first six months; "
      f"{d.kf.sum()} kidney failures after the landmark")
for label, x in (("crude", "early"),
                 ("adjusted: baseline eGFR, albuminuria, SGLT2 (the DAG's set)", "early + egfr10 + albuminuria + sglt2_2025"),
                 ("+ age, sex, province, nephrology, HF, COPD, prior stays", "early + egfr10 + albuminuria + sglt2_2025 + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays"),
                 ("+ the last eGFR on record (a mediator: do not)", "early + egfr10 + albuminuria + sglt2_2025 + egfr_last10")):
    m = PHReg.from_formula(f"t ~ {x}", d, status=d.kf, ties="efron").fit()
    b0, se = m.params[0], m.bse[0]
    print(f"{label:<60} HR {np.exp(b0):.2f} ({np.exp(b0 - 1.96 * se):.2f}-{np.exp(b0 + 1.96 * se):.2f})")
8,736 people at the landmark; 684 started Renavex in the first six months; 332 kidney failures after the landmark
crude                                                        HR 3.42 (2.64-4.44)
adjusted: baseline eGFR, albuminuria, SGLT2 (the DAG's set)  HR 0.71 (0.54-0.93)
+ age, sex, province, nephrology, HF, COPD, prior stays      HR 0.70 (0.53-0.92)
+ the last eGFR on record (a mediator: do not)               HR 0.72 (0.55-0.95)

The crude hazard ratio is 3.42; the DAG's three variables bring it to 0.71, and the extra variables barely move it. Adjusting for the last eGFR on record, a mediator, changes little here (0.72), because the eGFR-slowing effect accumulates slowly over two years. In the simulation of 21.3 it removed 60% of the effect: the rule doesn't depend on whether you notice the damage.

The generator says Renavex multiplies the hazard by 0.75 while taken, and also slows eGFR decline, so 0.71 is in the right place. But a landmark analysis answers a narrow question (starting within six months, effect after six months) and wastes everyone who started later. Day 22 does better.

21.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 21: DAGs, backdoor criterion, confounding by indication"

Day 21 checklist

  • I write the causal question with population, strategies, outcome and time frame
  • I can find valid adjustment sets with d-separation and explain chains, forks and colliders
  • I never adjust for mediators, colliders or other descendants of the treatment
  • I can show confounding by indication with a treatment model and an outcome model
  • I can say when a DAG shows that no measured adjustment is enough (death and frailty)