This translation keeps the chapter’s basic workflow:
compare naive and adjusted outcome regressions
estimate a propensity score
look at overlap directly
use the propensity score to stratify the treated-control comparison
compare Horvitz-Thompson and Hajek IPW with propensity-score truncation
check whether stratification and weighting improve covariate balance
Show code
from pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport crabbymetrics as cmnp.set_printoptions(precision=4, suppress=True)def repo_root():for candidate in [Path.cwd().resolve(), *Path.cwd().resolve().parents]:if (candidate /"ding_w_source").exists():return candidateraiseFileNotFoundError("could not locate ding_w_source from the current working directory")def expit(x):return1.0/ (1.0+ np.exp(-x))
for level in np.unique(quintile): idx = quintile == levelprint(f"Quintile {int(level) +1}: n = {idx.sum():4d}, treated share = {float(d[idx].mean()): .4f}" )
3 Stratification And IPW
The R script reports propensity-score subclassification for several numbers of strata, then compares Horvitz-Thompson and Hajek IPW under increasing propensity-score truncation. The estimates below use the same formulas.
The balance diagnostic asks the same question as the R plots: after reducing the covariates to a scalar propensity score, do the residual treated-control differences in the original covariates shrink?