When units adopt at different times
See why two-way fixed effects can mislead under staggered adoption, and estimate group-time effects instead.
What runs in CodeSplash
- Staggered difference-in-differences (Callaway–Sant'Anna) Verified in Python and R
You will be able to
- Explain why already-treated units are poor controls
- Read group-time ATTs and their four aggregations
- Choose between never-treated and not-yet-treated controls
Read first
The trouble with one regression
ReadWhen units adopt a policy in different years, a two-way fixed effects regression makes many 2 × 2 comparisons. Some use already-treated units as controls.
If effects grow over time, those units are changing because of their own treatment, and subtracting that change can shrink the estimate or even flip its sign. Staggered adoptionStaggered adoptionUnits adopt a treatment at different times; two-way fixed effects can then give misleading averages. needs a different approach.
Group-time effects
ReadCallaway and Sant'Anna estimate a separate effect for each adoption cohort in each period , using only clean controls:
Those many small effects are then averaged in a way that fits your question.
Which summary is largest?
PredictPredict first
Employment data across counties adopting a minimum wage increase in three cohorts. Compare the simple average with the event-time (dynamic) average. If effects build over time, which is larger in size?
Reveal
Simple: −0.040. Dynamic: −0.077. Group: −0.031. Calendar: −0.042. Each averages over something different, so report the one that matches your question.
Read it
In the appATT = −0.04, SE = 0.01, 95% CI [−0.06, −0.02], p < .001
- ATT
- −0.0400
- 95% CI
- [−0.0635, −0.0164]
- p
- < .001
Plots
View data
| ATT | Upper | Lower | Periods since treatment |
|---|---|---|---|
| 0.0305 | 0.0600 | 0.0010 | −3 |
| −0.0006 | 0.0255 | −0.0266 | −2 |
| −0.0245 | 0.0034 | −0.0524 | −1 |
| −0.0199 | 0.0032 | −0.0431 | 0 |
| −0.0510 | −0.0178 | −0.0841 | 1 |
| −0.1373 | −0.0658 | −0.2087 | 2 |
| −0.1008 | −0.0335 | −0.1682 | 3 |
Assumptions
- Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(5) = 7.79, p = .168).
- Comparison units — 309 never-treated units form the comparison group.
Aggregated effects
| Aggregation | ATT | SE |
|---|---|---|
| simple | −0.0400 | 0.0120 |
| dynamic | −0.0772 | 0.0200 |
| group | −0.0310 | 0.0124 |
| calendar | −0.0417 | 0.0160 |
By event time (periods since treatment)
| Event time | ATT | SE | Lower | Upper |
|---|---|---|---|---|
| −3 | 0.0305 | 0.0150 | 0.0010 | 0.0600 |
| −2 | −0.0006 | 0.0133 | −0.0266 | 0.0255 |
| −1 | −0.0245 | 0.0142 | −0.0524 | 0.0034 |
| 0 | −0.0199 | 0.0118 | −0.0431 | 0.0032 |
| 1 | −0.0510 | 0.0169 | −0.0841 | −0.0178 |
| 2 | −0.1373 | 0.0364 | −0.2087 | −0.0658 |
| 3 | −0.1008 | 0.0344 | −0.1682 | −0.0335 |
Group-time effects ATT(g, t)
| Cohort | Period | ATT | SE |
|---|---|---|---|
| 2,004 | 2,004 | −0.0105 | 0.0233 |
| 2,004 | 2,005 | −0.0704 | 0.0310 |
| 2,004 | 2,006 | −0.1373 | 0.0364 |
| 2,004 | 2,007 | −0.1008 | 0.0344 |
| 2,006 | 2,004 | 0.0065 | 0.0233 |
| 2,006 | 2,005 | −0.0028 | 0.0196 |
| 2,006 | 2,006 | −0.0046 | 0.0178 |
| 2,006 | 2,007 | −0.0412 | 0.0202 |
| 2,007 | 2,004 | 0.0305 | 0.0150 |
| 2,007 | 2,005 | −0.0027 | 0.0164 |
| 2,007 | 2,006 | −0.0311 | 0.0179 |
| 2,007 | 2,007 | −0.0261 | 0.0167 |
- Estimator dr, varying base period, anticipation 0; analytic standard errors from influence functions (no bootstrap).
The exact R script · R R version 4.5.1 (2025-06-13)
# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec c4b7ba7e55b878c5
# Dataset: c1_mpdta (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
library(did)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_mpdta.parquet", col_select = c("lemp", "county", "year", "first treat")))
n_input <- nrow(df)
df[["county"]] <- factor(df[["county"]], levels = sort(unique(df[["county"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("lemp", "county", "year", "first treat")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("lemp", "county", "year", "first treat")) # infinite values stop the run (registry/errors.yaml)
# %% Design: a balanced panel (units × periods)
Y <- "lemp"
UNIT <- "county"
TIME <- "year"
COHORT <- "first treat"
COVARIATES <- c()
control_group <- "never_treated"
estimator <- "dr"
base_period <- "varying"
anticipation <- 0
headline <- "simple"
conf <- 0.95
d <- data.frame(unit = as.character(df[[UNIT]]), t = as.numeric(df[[TIME]]), g = as.numeric(df[[COHORT]]), y = as.numeric(df[[Y]]))
for (j in seq_along(COVARIATES)) d[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
if (any(tapply(d$g, d$unit, function(v) length(unique(v))) > 1)) {
stop(sprintf("%s must be constant within each unit (the period it was first treated, 0 if never).", COHORT))
}
counts <- tapply(d$t, d$unit, function(v) length(unique(v)))
balanced <- names(counts)[counts == length(unique(d$t))]
if (length(balanced) < length(counts)) {
warnings <- c(warnings, sprintf("%d unit(s) not observed in every period were dropped (balanced panel).", length(counts) - length(balanced)))
}
d <- d[d$unit %in% balanced, ]
units <- sort(unique(d$unit), method = "radix")
if (length(units) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = length(units))
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = Y) # every ATT(g, t) would be 0 with a zero standard error
d$id <- match(d$unit, units) # did needs a numeric id
# Treated cohorts with a period before their treatment (did's rule): cohorts after the last period count as never
# treated, units treated in the first period drop out, and without never-treated units the last cohort is the comparison.
times_all <- sort(unique(d$t))
cohorts <- d$g[match(units, d$unit)]
cohorts[cohorts > max(times_all) + anticipation] <- 0
glist <- unique(cohorts[cohorts > 0 & cohorts > min(times_all) + anticipation])
if (!any(cohorts == 0)) glist <- glist[glist != max(cohorts)]
if (!length(glist)) {
cs_error("CS_E_UNDEFINED", what = "The staggered difference-in-differences", reason = "no treated cohort has a period before its treatment")
}
# %% ATT(g, t) with did (analytic influence-function standard errors: no bootstrap)
xformla <- if (length(COVARIATES)) as.formula(paste("~", paste(paste0("x", seq_along(COVARIATES)), collapse = " + "))) else ~1
res <- suppressWarnings(att_gt(
yname = "y", tname = "t", idname = "id", gname = "g", xformla = xformla, data = d, panel = TRUE,
control_group = if (control_group == "never_treated") "nevertreated" else "notyettreated",
est_method = estimator, base_period = base_period, anticipation = anticipation,
bstrap = FALSE, cband = FALSE, alp = 1 - conf, allow_unbalanced_panel = FALSE, print_details = FALSE
))
aggs <- lapply(c(simple = "simple", dynamic = "dynamic", group = "group", calendar = "calendar"),
function(tp) suppressWarnings(aggte(res, type = tp, bstrap = FALSE, cband = FALSE, na.rm = TRUE)))
psi <- as.matrix(res$inffunc)
n <- nrow(psi)
se_cells <- sqrt(colSums(psi^2) / n / n)
# did's own pre-test p-value is rounded to 5 decimals: recompute it from the influence functions.
pre <- which(res$group > res$t & se_cells > 0 & is.finite(se_cells))
if (length(pre)) {
Vp <- crossprod(psi[, pre, drop = FALSE]) / n
W <- if (rcond(Vp) > .Machine$double.eps) as.numeric(n * t(res$att[pre]) %*% solve(Vp, res$att[pre])) else NULL
pretrend_p <- if (!is.null(W)) pchisq(W, length(pre), lower.tail = FALSE) else NULL
} else {
W <- NULL
pretrend_p <- NULL
}
z <- qnorm(0.5 + conf / 2)
est <- aggs[[headline]]$overall.att
se <- aggs[[headline]]$overall.se
p <- 2 * pnorm(-abs(est / se))
ci_low <- est - z * se
ci_high <- est + z * se
# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
if (!is.null(pretrend_p)) {
if (pretrend_p < 0.05) {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "concern", downgrade_to = "L2",
detail = sprintf("Pre-treatment ATT(g, t) differ from zero jointly (χ²(%d) = %.2f, %s): parallel trends are doubtful.", length(pre), W, cs_fmt_p(pretrend_p)))
} else {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "pass",
detail = sprintf("Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(%d) = %.2f, %s).", length(pre), W, cs_fmt_p(pretrend_p)))
}
} else {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "info", detail = "No pre-treatment cells to test parallel trends.")
}
# Never-treated units after did's recoding (cohorts after the last period count as never treated;
# without never-treated units the last cohort is the comparison group when control = never treated).
g_unit <- tapply(d$g, d$id, `[`, 1)
g_unit[g_unit > max(d$t) + anticipation] <- 0
if (!any(g_unit == 0) && control_group == "never_treated") g_unit[g_unit == max(g_unit)] <- 0
n_never <- sum(g_unit == 0)
if (control_group == "never_treated" && n_never < 20) {
add_check(id = "comparison_group", label = "Comparison units", status = "concern",
detail = sprintf("Only %d never-treated units: estimates rest on a small comparison group; consider not-yet-treated units.", n_never))
} else {
add_check(id = "comparison_group", label = "Comparison units", status = "pass",
detail = paste0(sprintf("%d never-treated units", n_never), if (control_group == "not_yet_treated") " plus not-yet-treated units" else "", " form the comparison group."))
}
if (length(COVARIATES) && estimator %in% c("dr", "ipw")) {
add_check(id = "overlap", label = "Overlap", status = "info",
detail = "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units.")
}
# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.staggered/mpdta-never/out-r")
cell_df <- data.frame(group = res$group, time = res$t, post = as.integer(res$group <= res$t), att = res$att, se = se_cells)
nanoparquet::write_parquet(cell_df, file.path(out, "att_gt.parquet"))
artifacts <- list(list(key = "att_gt", path = file.path(out, "att_gt.parquet"), format = "parquet", title = "Group-time average treatment effects"))
fin <- function(v) if (is.null(v) || is.na(v)) NULL else v
dyn <- aggs$dynamic
g3 <- function(v) formatC(v, digits = 3, format = "g")
how <- switch(headline, simple = "over cohorts and post-treatment periods", dynamic = "over post-treatment event times", group = "over cohorts", calendar = "over calendar periods")
summary <- sprintf("Averaged %s, treatment changed %s by %s (%.0f%% CI [%s, %s], %s), estimated cohort by cohort against %s units.",
how, Y, g3(est), conf * 100, g3(ci_low), g3(ci_high), cs_fmt_p(p), if (control_group == "never_treated") "never-treated" else "not-yet-treated")
if (!is.null(pretrend_p)) {
summary <- paste(summary, if (pretrend_p < 0.05) sprintf("Pre-treatment effects differ from zero (%s): parallel trends are doubtful.", cs_fmt_p(pretrend_p))
else sprintf("Pre-treatment effects are compatible with parallel trends (%s).", cs_fmt_p(pretrend_p)))
}
values <- list(
estimate = est, se = fin(se), ci_low = ci_low, ci_high = ci_high, p_value = p, n = n,
att_simple = aggs$simple$overall.att, se_simple = fin(aggs$simple$overall.se), att_dynamic = aggs$dynamic$overall.att, se_dynamic = fin(aggs$dynamic$overall.se),
att_group = aggs$group$overall.att, se_group = fin(aggs$group$overall.se), att_calendar = aggs$calendar$overall.att, se_calendar = fin(aggs$calendar$overall.se),
n_cohorts = length(unique(res$group)), n_never_treated = n_never, n_periods = length(unique(res$t)) + if (base_period == "varying") 1L else 0L,
pretrend_chi2 = W, pretrend_p = pretrend_p,
estimand = "ATT", headline = headline,
effect_label = sprintf("Average effect of treatment on %s for treated cohorts after they were treated", Y),
claim_level_max = "L3"
)
for (i in seq_along(dyn$egt)) {
values[[sprintf("es_estimate[%s]", format(dyn$egt[i]))]] <- dyn$att.egt[i]
values[sprintf("es_se[%s]", format(dyn$egt[i]))] <- list(fin(dyn$se.egt[i]))
}
for (i in seq_along(aggs$group$egt)) {
values[[sprintf("group_estimate[%s]", format(aggs$group$egt[i]))]] <- aggs$group$att.egt[i]
values[sprintf("group_se[%s]", format(aggs$group$egt[i]))] <- list(fin(aggs$group$se.egt[i]))
}
for (i in seq_along(aggs$calendar$egt)) values[[sprintf("calendar_estimate[%s]", format(aggs$calendar$egt[i]))]] <- aggs$calendar$att.egt[i]
for (i in seq_along(res$att)) {
values[[sprintf("attgt[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- res$att[i]
values[[sprintf("attgt_se[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- se_cells[i]
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
by_rows <- function(a) data.frame(key = a$egt, estimate = a$att.egt, se = a$se.egt, low = a$att.egt - z * a$se.egt, high = a$att.egt + z * a$se.egt)
cs_publish(list(
method = "causal.staggered",
methodVersion = "1.0.2",
title = "Staggered difference-in-differences (Callaway–Sant'Anna)",
engine = cs_engine_info("did", "DRDID", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("ATT = %s, SE = %s, %.0f%% CI [%s, %s], %s", cs_fmt_num(est), cs_fmt_num(se), conf * 100, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p)),
statistics = list(
list(key = "estimate", label = "ATT", value = est),
list(key = "ci", label = sprintf("%.0f%% CI", conf * 100), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p, format = "p")
),
tables = list(
list(key = "aggregations", title = "Aggregated effects",
columns = list(list(key = "type", label = "Aggregation", type = "string"), list(key = "estimate", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = data.frame(type = names(aggs), estimate = vapply(aggs, function(a) a$overall.att, numeric(1)), se = vapply(aggs, function(a) a$overall.se, numeric(1)))),
list(key = "event_study", title = "By event time (periods since treatment)",
columns = list(list(key = "key", label = "Event time", type = "number"), list(key = "estimate", label = "ATT", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Lower", type = "number"), list(key = "high", label = "Upper", type = "number")),
rows = by_rows(dyn)),
list(key = "att_gt", title = "Group-time effects ATT(g, t)",
columns = list(list(key = "group", label = "Cohort", type = "number"), list(key = "time", label = "Period", type = "number"),
list(key = "att", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = cell_df[, c("group", "time", "att", "se")])
),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
warnings = warnings,
notes = list(sprintf("Estimator %s, %s base period, anticipation %s; analytic standard errors from influence functions (no bootstrap).", estimator, base_period, format(anticipation))),
values = values,
artifacts = artifacts,
charts = list(cs_chart("event_study", "event-study", sprintf("Effect on %s by periods since treatment", Y), list(
rel_time = cs_col("Periods since treatment", dyn$egt, kind = "numeric"),
estimate = cs_col("ATT", dyn$att.egt, kind = "numeric"),
low = cs_col("Lower", dyn$att.egt - z * dyn$se.egt, kind = "numeric"),
high = cs_col("Upper", dyn$att.egt + z * dyn$se.egt, kind = "numeric")
), controls = list(reference = if (base_period == "universal") -1 else NULL)))
))
ATT = −0.04, SE = 0.01, 95% CI [−0.06, −0.02], p < .001
- ATT
- −0.0400
- 95% CI
- [−0.0635, −0.0164]
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(5) = 7.79, p = .168).
- Comparison units — 309 never-treated units form the comparison group.
Aggregated effects
| Aggregation | ATT | SE |
|---|---|---|
| simple | −0.0400 | 0.0120 |
| dynamic | −0.0772 | 0.0200 |
| group | −0.0310 | 0.0124 |
| calendar | −0.0417 | 0.0160 |
By event time (periods since treatment)
| Event time | ATT | SE | Lower | Upper |
|---|---|---|---|---|
| −3 | 0.0305 | 0.0150 | 0.0010 | 0.0600 |
| −2 | −0.0006 | 0.0133 | −0.0266 | 0.0255 |
| −1 | −0.0245 | 0.0142 | −0.0524 | 0.0034 |
| 0 | −0.0199 | 0.0118 | −0.0431 | 0.0032 |
| 1 | −0.0510 | 0.0169 | −0.0841 | −0.0178 |
| 2 | −0.1373 | 0.0364 | −0.2087 | −0.0658 |
| 3 | −0.1008 | 0.0344 | −0.1682 | −0.0335 |
Group-time effects ATT(g, t)
| Cohort | Period | ATT | SE |
|---|---|---|---|
| 2,004 | 2,004 | −0.0105 | 0.0233 |
| 2,004 | 2,005 | −0.0704 | 0.0310 |
| 2,004 | 2,006 | −0.1373 | 0.0364 |
| 2,004 | 2,007 | −0.1008 | 0.0344 |
| 2,006 | 2,004 | 0.0065 | 0.0233 |
| 2,006 | 2,005 | −0.0028 | 0.0196 |
| 2,006 | 2,006 | −0.0046 | 0.0178 |
| 2,006 | 2,007 | −0.0412 | 0.0202 |
| 2,007 | 2,004 | 0.0305 | 0.0150 |
| 2,007 | 2,005 | −0.0027 | 0.0164 |
| 2,007 | 2,006 | −0.0311 | 0.0179 |
| 2,007 | 2,007 | −0.0261 | 0.0167 |
- Estimator dr, varying base period, anticipation 0; analytic standard errors from influence functions (no bootstrap).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec c4b7ba7e55b878c5
# Dataset: c1_mpdta (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import staggered as csdid # twin of R's did::att_gt / did::aggte
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_mpdta.parquet", columns=["lemp", "county", "year", "first treat"])
n_input = len(df)
df["county"] = pd.Categorical(df["county"], categories=sorted(df["county"].dropna().unique()))
df = df.dropna(subset=["lemp", "county", "year", "first treat"]) # listwise deletion over the analysis columns
df["county"] = df["county"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["lemp", "county", "year", "first treat"]) # infinite values stop the run (registry/errors.yaml)
# %% Design: a balanced panel (units × periods)
Y, UNIT, TIME, COHORT = "lemp", "county", "year", "first treat"
COVARIATES = []
control_group = "never_treated"
estimator = "dr"
base_period = "varying"
anticipation = float(0)
headline = "simple"
conf = 0.95
d = df.assign(_unit=df[UNIT].astype(str), _time=df[TIME].astype(float), _g=df[COHORT].astype(float))
if d.groupby("_unit")["_g"].nunique().max() > 1:
raise ValueError(f"{COHORT} must be constant within each unit (the period it was first treated, 0 if never).")
times_all = np.sort(d["_time"].unique())
counts = d.groupby("_unit")["_time"].nunique()
balanced = counts[counts == len(times_all)].index
if len(balanced) < d["_unit"].nunique():
warnings.append(f"{d['_unit'].nunique() - len(balanced)} unit(s) not observed in every period were dropped (balanced panel).")
d = d[d["_unit"].isin(balanced)]
units = np.sort(d["_unit"].unique())
if len(units) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=len(units))
if np.unique(d[Y].to_numpy(dtype=float)).size < 2: # every ATT(g, t) would be 0 with a zero standard error
cs.cs_error("CS_E_CONSTANT", column=Y)
cohort0 = d.groupby("_unit")["_g"].first().reindex(units).to_numpy()
keep_t, cohort, keep_u, glist, notes = csdid.prepare(times_all, cohort0, control_group, anticipation)
tlist = times_all[keep_t]
units, cohort = units[keep_u], cohort[keep_u]
d = d[d["_unit"].isin(units) & d["_time"].isin(tlist)]
if len(glist) == 0:
cs.cs_error("CS_E_UNDEFINED", what="The staggered difference-in-differences", reason="no treated cohort has a period before its treatment")
wide = d.pivot_table(index="_unit", columns="_time", values=Y, aggfunc="first").reindex(index=units, columns=tlist)
Ym = wide.to_numpy(dtype=float)
Xs = []
for t in tlist:
cols = [np.ones(len(units))]
for c in COVARIATES:
cols.append(d[d["_time"] == t].set_index("_unit")[c].reindex(units).to_numpy(dtype=float))
Xs.append(np.column_stack(cols))
n = len(units)
# %% ATT(g, t), aggregations and the pre-trend test
cells, psi = csdid.att_gt(Ym, Xs, cohort, tlist, glist, control_group, estimator, base_period, anticipation)
se_cells = csdid.cell_se(psi)
agg = csdid.aggregate(cells, psi, cohort, tlist, glist)
W, pretrend_p, n_pre = csdid.pretest(cells, psi)
z = stats.norm.ppf(0.5 + conf / 2)
est, se = agg[headline]["att"], agg[headline]["se"]
p = float(2 * stats.norm.sf(abs(est / se)))
ci_low, ci_high = est - z * se, est + z * se
# %% Checks
checks = []
if pretrend_p is not None:
if pretrend_p < 0.05:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "concern", "downgrade_to": "L2",
"detail": f"Pre-treatment ATT(g, t) differ from zero jointly (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)}): parallel trends are doubtful."})
else:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "pass",
"detail": f"Pre-treatment ATT(g, t) are jointly compatible with zero (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)})."})
else:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info", "detail": "No pre-treatment cells to test parallel trends."})
n_never = int((cohort == 0).sum())
if control_group == "never_treated" and n_never < 20:
checks.append({"id": "comparison_group", "label": "Comparison units", "status": "concern",
"detail": f"Only {n_never} never-treated units: estimates rest on a small comparison group; consider not-yet-treated units."})
else:
checks.append({"id": "comparison_group", "label": "Comparison units", "status": "pass",
"detail": f"{n_never} never-treated units" + (" plus not-yet-treated units" if control_group == "not_yet_treated" else "") + " form the comparison group."})
if COVARIATES and estimator in ("dr", "ipw"):
checks.append({"id": "overlap", "label": "Overlap", "status": "info",
"detail": "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units."})
# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.staggered/mpdta-never/out-python")
cell_df = pd.DataFrame(cells).assign(se=se_cells)
cell_df.to_parquet(os.path.join(out, "att_gt.parquet"), index=False)
artifacts = [{"key": "att_gt", "path": os.path.join(out, "att_gt.parquet"), "format": "parquet", "title": "Group-time average treatment effects"}]
dyn = agg["dynamic"]["by"]
summary = (
f"Averaged {'over cohorts and post-treatment periods' if headline == 'simple' else {'dynamic': 'over post-treatment event times', 'group': 'over cohorts', 'calendar': 'over calendar periods'}[headline]}, "
f"treatment changed {Y} by {est:.3g} ({conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p)}), estimated cohort by cohort against "
f"{'never-treated' if control_group == 'never_treated' else 'not-yet-treated'} units."
)
if pretrend_p is not None:
summary += (f" Pre-treatment effects differ from zero ({cs.fmt_p(pretrend_p)}): parallel trends are doubtful." if pretrend_p < 0.05
else f" Pre-treatment effects are compatible with parallel trends ({cs.fmt_p(pretrend_p)}).")
fin = lambda v: None if v is None or not np.isfinite(v) else float(v)
values = {
"estimate": est, "se": fin(se), "ci_low": ci_low, "ci_high": ci_high, "p_value": p, "n": n,
"att_simple": agg["simple"]["att"], "se_simple": fin(agg["simple"]["se"]), "att_dynamic": agg["dynamic"]["att"], "se_dynamic": fin(agg["dynamic"]["se"]),
"att_group": agg["group"]["att"], "se_group": fin(agg["group"]["se"]), "att_calendar": agg["calendar"]["att"], "se_calendar": fin(agg["calendar"]["se"]),
"n_cohorts": len(glist), "n_never_treated": n_never, "n_periods": len(tlist), "pretrend_chi2": W, "pretrend_p": pretrend_p,
"estimand": "ATT", "headline": headline,
"effect_label": f"Average effect of treatment on {Y} for treated cohorts after they were treated",
"claim_level_max": "L3",
}
for e, a, s in dyn:
values[f"es_estimate[{e:g}]"] = a
values[f"es_se[{e:g}]"] = fin(s)
for g, a, s in agg["group"]["by"]:
values[f"group_estimate[{g:g}]"] = a
values[f"group_se[{g:g}]"] = fin(s)
for t, a, s in agg["calendar"]["by"]:
values[f"calendar_estimate[{t:g}]"] = a
for c, s in zip(cells, se_cells):
values[f"attgt[{c['group']:g}:{c['time']:g}]"] = c["att"]
values[f"attgt_se[{c['group']:g}:{c['time']:g}]"] = float(s)
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
by_rows = lambda kind: [{"key": k, "estimate": a, "se": s, "low": a - z * s, "high": a + z * s} for k, a, s in agg[kind]["by"]]
cs.publish({
"method": "causal.staggered",
"methodVersion": "1.0.2",
"title": "Staggered difference-in-differences (Callaway–Sant'Anna)",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"ATT = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p)}",
"statistics": [
{"key": "estimate", "label": "ATT", "value": est},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p, "format": "p"},
],
"tables": [
{"key": "aggregations", "title": "Aggregated effects",
"columns": [{"key": "type", "label": "Aggregation", "type": "string"}, {"key": "estimate", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": [{"type": k, "estimate": agg[k]["att"], "se": agg[k]["se"]} for k in ("simple", "dynamic", "group", "calendar")]},
{"key": "event_study", "title": "By event time (periods since treatment)",
"columns": [{"key": "key", "label": "Event time", "type": "number"}, {"key": "estimate", "label": "ATT", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
"rows": by_rows("dynamic")},
{"key": "att_gt", "title": "Group-time effects ATT(g, t)",
"columns": [{"key": "group", "label": "Cohort", "type": "number"}, {"key": "time", "label": "Period", "type": "number"},
{"key": "att", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": cell_df[["group", "time", "att", "se"]].to_dict("records")},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings + notes,
"notes": [f"Estimator {estimator}, {base_period} base period, anticipation {anticipation:g}; analytic standard errors from influence functions (no bootstrap)."],
"values": values,
"artifacts": artifacts,
"charts": [cs.chart("event_study", "event-study", f"Effect on {Y} by periods since treatment", {
"rel_time": cs.col("Periods since treatment", [r[0] for r in dyn], kind="numeric"),
"estimate": cs.col("ATT", [r[1] for r in dyn], kind="numeric"),
"low": cs.col("Lower", [r[1] - z * r[2] for r in dyn], kind="numeric"),
"high": cs.col("Upper", [r[1] + z * r[2] for r in dyn], kind="numeric"),
}, controls={"reference": -1 if base_period == "universal" else None})],
})
Here 3 cohorts adopt, and 309 counties never do. The pre-trend test gives p = .168: no clear sign of diverging trends, though that doesn't prove they're parallel.
Who are the controls?
Read- Never-treated: stable, but they may differ from adopters.
- Not-yet-treated: more like adopters, and available even when everyone eventually adopts.
ATT = 0.83, SE = 0.06, 95% CI [0.71, 0.95], p < .001
- ATT
- 0.8303
- 95% CI
- [0.7090, 0.9516]
- p
- < .001
Plots
View data
| ATT | Upper | Lower | Periods since treatment |
|---|---|---|---|
| −0.0331 | 0.1743 | −0.2406 | −5 |
| −0.1462 | 0.0454 | −0.3378 | −4 |
| 0.1134 | 0.2587 | −0.0319 | −3 |
| −0.0549 | 0.0688 | −0.1786 | −2 |
| −0.0087 | 0.1139 | −0.1313 | −1 |
| 0.6100 | 0.7237 | 0.4963 | 0 |
| 0.8243 | 0.9724 | 0.6762 | 1 |
| 0.9677 | 1.119 | 0.8168 | 2 |
| 1.164 | 1.389 | 0.9391 | 3 |
| 1.451 | 1.698 | 1.205 | 4 |
Assumptions
- Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(9) = 12.96, p = .165).
- Comparison units — 0 never-treated units plus not-yet-treated units form the comparison group.
Aggregated effects
| Aggregation | ATT | SE |
|---|---|---|
| simple | 0.8921 | 0.0606 |
| dynamic | 1.003 | 0.0694 |
| group | 0.8421 | 0.0644 |
| calendar | 0.8303 | 0.0619 |
By event time (periods since treatment)
| Event time | ATT | SE | Lower | Upper |
|---|---|---|---|---|
| −5 | −0.0331 | 0.1058 | −0.2406 | 0.1743 |
| −4 | −0.1462 | 0.0978 | −0.3378 | 0.0454 |
| −3 | 0.1134 | 0.0741 | −0.0319 | 0.2587 |
| −2 | −0.0549 | 0.0631 | −0.1786 | 0.0688 |
| −1 | −0.0087 | 0.0626 | −0.1313 | 0.1139 |
| 0 | 0.6100 | 0.0580 | 0.4963 | 0.7237 |
| 1 | 0.8243 | 0.0756 | 0.6762 | 0.9724 |
| 2 | 0.9677 | 0.0770 | 0.8168 | 1.119 |
| 3 | 1.164 | 0.1147 | 0.9391 | 1.389 |
| 4 | 1.451 | 0.1259 | 1.205 | 1.698 |
Group-time effects ATT(g, t)
| Cohort | Period | ATT | SE |
|---|---|---|---|
| 2,004 | 2,003 | −0.0509 | 0.1023 |
| 2,004 | 2,004 | 0.5625 | 0.1003 |
| 2,004 | 2,005 | 0.8074 | 0.0974 |
| 2,004 | 2,006 | 0.8377 | 0.0989 |
| 2,004 | 2,007 | 1.164 | 0.1147 |
| 2,004 | 2,008 | 1.451 | 0.1259 |
| 2,006 | 2,003 | −0.0353 | 0.0995 |
| 2,006 | 2,004 | 0.0297 | 0.0771 |
| 2,006 | 2,005 | −0.0982 | 0.0837 |
| 2,006 | 2,006 | 0.5283 | 0.0779 |
| 2,006 | 2,007 | 0.8411 | 0.1082 |
| 2,006 | 2,008 | 1.098 | 0.1095 |
| 2,008 | 2,003 | −0.0331 | 0.1058 |
| 2,008 | 2,004 | −0.1462 | 0.0978 |
| 2,008 | 2,005 | 0.2621 | 0.1007 |
| 2,008 | 2,006 | −0.1394 | 0.1006 |
| 2,008 | 2,007 | 0.1230 | 0.1205 |
| 2,008 | 2,008 | 0.7393 | 0.1251 |
- Estimator reg, varying base period, anticipation 1; analytic standard errors from influence functions (no bootstrap).
The exact R script · R R version 4.5.1 (2025-06-13)
# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec 1fd64941d07bf8fc
# Dataset: c1_stagger (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
library(did)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_stagger.parquet", col_select = c("y", "unit", "year", "cohort", "size")))
n_input <- nrow(df)
df[["unit"]] <- factor(df[["unit"]], levels = sort(unique(df[["unit"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("y", "unit", "year", "cohort", "size")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("y", "unit", "year", "cohort", "size")) # infinite values stop the run (registry/errors.yaml)
# %% Design: a balanced panel (units × periods)
Y <- "y"
UNIT <- "unit"
TIME <- "year"
COHORT <- "cohort"
COVARIATES <- c("size")
control_group <- "not_yet_treated"
estimator <- "reg"
base_period <- "varying"
anticipation <- 1
headline <- "calendar"
conf <- 0.95
d <- data.frame(unit = as.character(df[[UNIT]]), t = as.numeric(df[[TIME]]), g = as.numeric(df[[COHORT]]), y = as.numeric(df[[Y]]))
for (j in seq_along(COVARIATES)) d[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
if (any(tapply(d$g, d$unit, function(v) length(unique(v))) > 1)) {
stop(sprintf("%s must be constant within each unit (the period it was first treated, 0 if never).", COHORT))
}
counts <- tapply(d$t, d$unit, function(v) length(unique(v)))
balanced <- names(counts)[counts == length(unique(d$t))]
if (length(balanced) < length(counts)) {
warnings <- c(warnings, sprintf("%d unit(s) not observed in every period were dropped (balanced panel).", length(counts) - length(balanced)))
}
d <- d[d$unit %in% balanced, ]
units <- sort(unique(d$unit), method = "radix")
if (length(units) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = length(units))
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = Y) # every ATT(g, t) would be 0 with a zero standard error
d$id <- match(d$unit, units) # did needs a numeric id
# Treated cohorts with a period before their treatment (did's rule): cohorts after the last period count as never
# treated, units treated in the first period drop out, and without never-treated units the last cohort is the comparison.
times_all <- sort(unique(d$t))
cohorts <- d$g[match(units, d$unit)]
cohorts[cohorts > max(times_all) + anticipation] <- 0
glist <- unique(cohorts[cohorts > 0 & cohorts > min(times_all) + anticipation])
if (!any(cohorts == 0)) glist <- glist[glist != max(cohorts)]
if (!length(glist)) {
cs_error("CS_E_UNDEFINED", what = "The staggered difference-in-differences", reason = "no treated cohort has a period before its treatment")
}
# %% ATT(g, t) with did (analytic influence-function standard errors: no bootstrap)
xformla <- if (length(COVARIATES)) as.formula(paste("~", paste(paste0("x", seq_along(COVARIATES)), collapse = " + "))) else ~1
res <- suppressWarnings(att_gt(
yname = "y", tname = "t", idname = "id", gname = "g", xformla = xformla, data = d, panel = TRUE,
control_group = if (control_group == "never_treated") "nevertreated" else "notyettreated",
est_method = estimator, base_period = base_period, anticipation = anticipation,
bstrap = FALSE, cband = FALSE, alp = 1 - conf, allow_unbalanced_panel = FALSE, print_details = FALSE
))
aggs <- lapply(c(simple = "simple", dynamic = "dynamic", group = "group", calendar = "calendar"),
function(tp) suppressWarnings(aggte(res, type = tp, bstrap = FALSE, cband = FALSE, na.rm = TRUE)))
psi <- as.matrix(res$inffunc)
n <- nrow(psi)
se_cells <- sqrt(colSums(psi^2) / n / n)
# did's own pre-test p-value is rounded to 5 decimals: recompute it from the influence functions.
pre <- which(res$group > res$t & se_cells > 0 & is.finite(se_cells))
if (length(pre)) {
Vp <- crossprod(psi[, pre, drop = FALSE]) / n
W <- if (rcond(Vp) > .Machine$double.eps) as.numeric(n * t(res$att[pre]) %*% solve(Vp, res$att[pre])) else NULL
pretrend_p <- if (!is.null(W)) pchisq(W, length(pre), lower.tail = FALSE) else NULL
} else {
W <- NULL
pretrend_p <- NULL
}
z <- qnorm(0.5 + conf / 2)
est <- aggs[[headline]]$overall.att
se <- aggs[[headline]]$overall.se
p <- 2 * pnorm(-abs(est / se))
ci_low <- est - z * se
ci_high <- est + z * se
# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
if (!is.null(pretrend_p)) {
if (pretrend_p < 0.05) {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "concern", downgrade_to = "L2",
detail = sprintf("Pre-treatment ATT(g, t) differ from zero jointly (χ²(%d) = %.2f, %s): parallel trends are doubtful.", length(pre), W, cs_fmt_p(pretrend_p)))
} else {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "pass",
detail = sprintf("Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(%d) = %.2f, %s).", length(pre), W, cs_fmt_p(pretrend_p)))
}
} else {
add_check(id = "pretrend", label = "Parallel pre-trends", status = "info", detail = "No pre-treatment cells to test parallel trends.")
}
# Never-treated units after did's recoding (cohorts after the last period count as never treated;
# without never-treated units the last cohort is the comparison group when control = never treated).
g_unit <- tapply(d$g, d$id, `[`, 1)
g_unit[g_unit > max(d$t) + anticipation] <- 0
if (!any(g_unit == 0) && control_group == "never_treated") g_unit[g_unit == max(g_unit)] <- 0
n_never <- sum(g_unit == 0)
if (control_group == "never_treated" && n_never < 20) {
add_check(id = "comparison_group", label = "Comparison units", status = "concern",
detail = sprintf("Only %d never-treated units: estimates rest on a small comparison group; consider not-yet-treated units.", n_never))
} else {
add_check(id = "comparison_group", label = "Comparison units", status = "pass",
detail = paste0(sprintf("%d never-treated units", n_never), if (control_group == "not_yet_treated") " plus not-yet-treated units" else "", " form the comparison group."))
}
if (length(COVARIATES) && estimator %in% c("dr", "ipw")) {
add_check(id = "overlap", label = "Overlap", status = "info",
detail = "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units.")
}
# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.staggered/no-never-treated/out-r")
cell_df <- data.frame(group = res$group, time = res$t, post = as.integer(res$group <= res$t), att = res$att, se = se_cells)
nanoparquet::write_parquet(cell_df, file.path(out, "att_gt.parquet"))
artifacts <- list(list(key = "att_gt", path = file.path(out, "att_gt.parquet"), format = "parquet", title = "Group-time average treatment effects"))
fin <- function(v) if (is.null(v) || is.na(v)) NULL else v
dyn <- aggs$dynamic
g3 <- function(v) formatC(v, digits = 3, format = "g")
how <- switch(headline, simple = "over cohorts and post-treatment periods", dynamic = "over post-treatment event times", group = "over cohorts", calendar = "over calendar periods")
summary <- sprintf("Averaged %s, treatment changed %s by %s (%.0f%% CI [%s, %s], %s), estimated cohort by cohort against %s units.",
how, Y, g3(est), conf * 100, g3(ci_low), g3(ci_high), cs_fmt_p(p), if (control_group == "never_treated") "never-treated" else "not-yet-treated")
if (!is.null(pretrend_p)) {
summary <- paste(summary, if (pretrend_p < 0.05) sprintf("Pre-treatment effects differ from zero (%s): parallel trends are doubtful.", cs_fmt_p(pretrend_p))
else sprintf("Pre-treatment effects are compatible with parallel trends (%s).", cs_fmt_p(pretrend_p)))
}
values <- list(
estimate = est, se = fin(se), ci_low = ci_low, ci_high = ci_high, p_value = p, n = n,
att_simple = aggs$simple$overall.att, se_simple = fin(aggs$simple$overall.se), att_dynamic = aggs$dynamic$overall.att, se_dynamic = fin(aggs$dynamic$overall.se),
att_group = aggs$group$overall.att, se_group = fin(aggs$group$overall.se), att_calendar = aggs$calendar$overall.att, se_calendar = fin(aggs$calendar$overall.se),
n_cohorts = length(unique(res$group)), n_never_treated = n_never, n_periods = length(unique(res$t)) + if (base_period == "varying") 1L else 0L,
pretrend_chi2 = W, pretrend_p = pretrend_p,
estimand = "ATT", headline = headline,
effect_label = sprintf("Average effect of treatment on %s for treated cohorts after they were treated", Y),
claim_level_max = "L3"
)
for (i in seq_along(dyn$egt)) {
values[[sprintf("es_estimate[%s]", format(dyn$egt[i]))]] <- dyn$att.egt[i]
values[sprintf("es_se[%s]", format(dyn$egt[i]))] <- list(fin(dyn$se.egt[i]))
}
for (i in seq_along(aggs$group$egt)) {
values[[sprintf("group_estimate[%s]", format(aggs$group$egt[i]))]] <- aggs$group$att.egt[i]
values[sprintf("group_se[%s]", format(aggs$group$egt[i]))] <- list(fin(aggs$group$se.egt[i]))
}
for (i in seq_along(aggs$calendar$egt)) values[[sprintf("calendar_estimate[%s]", format(aggs$calendar$egt[i]))]] <- aggs$calendar$att.egt[i]
for (i in seq_along(res$att)) {
values[[sprintf("attgt[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- res$att[i]
values[[sprintf("attgt_se[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- se_cells[i]
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
by_rows <- function(a) data.frame(key = a$egt, estimate = a$att.egt, se = a$se.egt, low = a$att.egt - z * a$se.egt, high = a$att.egt + z * a$se.egt)
cs_publish(list(
method = "causal.staggered",
methodVersion = "1.0.2",
title = "Staggered difference-in-differences (Callaway–Sant'Anna)",
engine = cs_engine_info("did", "DRDID", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("ATT = %s, SE = %s, %.0f%% CI [%s, %s], %s", cs_fmt_num(est), cs_fmt_num(se), conf * 100, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p)),
statistics = list(
list(key = "estimate", label = "ATT", value = est),
list(key = "ci", label = sprintf("%.0f%% CI", conf * 100), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p, format = "p")
),
tables = list(
list(key = "aggregations", title = "Aggregated effects",
columns = list(list(key = "type", label = "Aggregation", type = "string"), list(key = "estimate", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = data.frame(type = names(aggs), estimate = vapply(aggs, function(a) a$overall.att, numeric(1)), se = vapply(aggs, function(a) a$overall.se, numeric(1)))),
list(key = "event_study", title = "By event time (periods since treatment)",
columns = list(list(key = "key", label = "Event time", type = "number"), list(key = "estimate", label = "ATT", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Lower", type = "number"), list(key = "high", label = "Upper", type = "number")),
rows = by_rows(dyn)),
list(key = "att_gt", title = "Group-time effects ATT(g, t)",
columns = list(list(key = "group", label = "Cohort", type = "number"), list(key = "time", label = "Period", type = "number"),
list(key = "att", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = cell_df[, c("group", "time", "att", "se")])
),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
warnings = warnings,
notes = list(sprintf("Estimator %s, %s base period, anticipation %s; analytic standard errors from influence functions (no bootstrap).", estimator, base_period, format(anticipation))),
values = values,
artifacts = artifacts,
charts = list(cs_chart("event_study", "event-study", sprintf("Effect on %s by periods since treatment", Y), list(
rel_time = cs_col("Periods since treatment", dyn$egt, kind = "numeric"),
estimate = cs_col("ATT", dyn$att.egt, kind = "numeric"),
low = cs_col("Lower", dyn$att.egt - z * dyn$se.egt, kind = "numeric"),
high = cs_col("Upper", dyn$att.egt + z * dyn$se.egt, kind = "numeric")
), controls = list(reference = if (base_period == "universal") -1 else NULL)))
))
ATT = 0.83, SE = 0.06, 95% CI [0.71, 0.95], p < .001
- ATT
- 0.8303
- 95% CI
- [0.7090, 0.9516]
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(9) = 12.96, p = .165).
- Comparison units — 0 never-treated units plus not-yet-treated units form the comparison group.
Aggregated effects
| Aggregation | ATT | SE |
|---|---|---|
| simple | 0.8921 | 0.0606 |
| dynamic | 1.003 | 0.0694 |
| group | 0.8421 | 0.0644 |
| calendar | 0.8303 | 0.0619 |
By event time (periods since treatment)
| Event time | ATT | SE | Lower | Upper |
|---|---|---|---|---|
| −5 | −0.0331 | 0.1058 | −0.2406 | 0.1743 |
| −4 | −0.1462 | 0.0978 | −0.3378 | 0.0454 |
| −3 | 0.1134 | 0.0741 | −0.0319 | 0.2587 |
| −2 | −0.0549 | 0.0631 | −0.1786 | 0.0688 |
| −1 | −0.0087 | 0.0626 | −0.1313 | 0.1139 |
| 0 | 0.6100 | 0.0580 | 0.4963 | 0.7237 |
| 1 | 0.8243 | 0.0756 | 0.6762 | 0.9724 |
| 2 | 0.9677 | 0.0770 | 0.8168 | 1.119 |
| 3 | 1.164 | 0.1147 | 0.9391 | 1.389 |
| 4 | 1.451 | 0.1259 | 1.205 | 1.698 |
Group-time effects ATT(g, t)
| Cohort | Period | ATT | SE |
|---|---|---|---|
| 2,004 | 2,003 | −0.0509 | 0.1023 |
| 2,004 | 2,004 | 0.5625 | 0.1003 |
| 2,004 | 2,005 | 0.8074 | 0.0974 |
| 2,004 | 2,006 | 0.8377 | 0.0989 |
| 2,004 | 2,007 | 1.164 | 0.1147 |
| 2,004 | 2,008 | 1.451 | 0.1259 |
| 2,006 | 2,003 | −0.0353 | 0.0995 |
| 2,006 | 2,004 | 0.0297 | 0.0771 |
| 2,006 | 2,005 | −0.0982 | 0.0837 |
| 2,006 | 2,006 | 0.5283 | 0.0779 |
| 2,006 | 2,007 | 0.8411 | 0.1082 |
| 2,006 | 2,008 | 1.098 | 0.1095 |
| 2,008 | 2,003 | −0.0331 | 0.1058 |
| 2,008 | 2,004 | −0.1462 | 0.0978 |
| 2,008 | 2,005 | 0.2621 | 0.1007 |
| 2,008 | 2,006 | −0.1394 | 0.1006 |
| 2,008 | 2,007 | 0.1230 | 0.1205 |
| 2,008 | 2,008 | 0.7393 | 0.1251 |
- No never-treated units: periods from the last cohort's treatment on are dropped (no comparison units).
- Estimator reg, varying base period, anticipation 1; analytic standard errors from influence functions (no bootstrap).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec 1fd64941d07bf8fc
# Dataset: c1_stagger (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import staggered as csdid # twin of R's did::att_gt / did::aggte
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_stagger.parquet", columns=["y", "unit", "year", "cohort", "size"])
n_input = len(df)
df["unit"] = pd.Categorical(df["unit"], categories=sorted(df["unit"].dropna().unique()))
df = df.dropna(subset=["y", "unit", "year", "cohort", "size"]) # listwise deletion over the analysis columns
df["unit"] = df["unit"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y", "unit", "year", "cohort", "size"]) # infinite values stop the run (registry/errors.yaml)
# %% Design: a balanced panel (units × periods)
Y, UNIT, TIME, COHORT = "y", "unit", "year", "cohort"
COVARIATES = ["size"]
control_group = "not_yet_treated"
estimator = "reg"
base_period = "varying"
anticipation = float(1)
headline = "calendar"
conf = 0.95
d = df.assign(_unit=df[UNIT].astype(str), _time=df[TIME].astype(float), _g=df[COHORT].astype(float))
if d.groupby("_unit")["_g"].nunique().max() > 1:
raise ValueError(f"{COHORT} must be constant within each unit (the period it was first treated, 0 if never).")
times_all = np.sort(d["_time"].unique())
counts = d.groupby("_unit")["_time"].nunique()
balanced = counts[counts == len(times_all)].index
if len(balanced) < d["_unit"].nunique():
warnings.append(f"{d['_unit'].nunique() - len(balanced)} unit(s) not observed in every period were dropped (balanced panel).")
d = d[d["_unit"].isin(balanced)]
units = np.sort(d["_unit"].unique())
if len(units) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=len(units))
if np.unique(d[Y].to_numpy(dtype=float)).size < 2: # every ATT(g, t) would be 0 with a zero standard error
cs.cs_error("CS_E_CONSTANT", column=Y)
cohort0 = d.groupby("_unit")["_g"].first().reindex(units).to_numpy()
keep_t, cohort, keep_u, glist, notes = csdid.prepare(times_all, cohort0, control_group, anticipation)
tlist = times_all[keep_t]
units, cohort = units[keep_u], cohort[keep_u]
d = d[d["_unit"].isin(units) & d["_time"].isin(tlist)]
if len(glist) == 0:
cs.cs_error("CS_E_UNDEFINED", what="The staggered difference-in-differences", reason="no treated cohort has a period before its treatment")
wide = d.pivot_table(index="_unit", columns="_time", values=Y, aggfunc="first").reindex(index=units, columns=tlist)
Ym = wide.to_numpy(dtype=float)
Xs = []
for t in tlist:
cols = [np.ones(len(units))]
for c in COVARIATES:
cols.append(d[d["_time"] == t].set_index("_unit")[c].reindex(units).to_numpy(dtype=float))
Xs.append(np.column_stack(cols))
n = len(units)
# %% ATT(g, t), aggregations and the pre-trend test
cells, psi = csdid.att_gt(Ym, Xs, cohort, tlist, glist, control_group, estimator, base_period, anticipation)
se_cells = csdid.cell_se(psi)
agg = csdid.aggregate(cells, psi, cohort, tlist, glist)
W, pretrend_p, n_pre = csdid.pretest(cells, psi)
z = stats.norm.ppf(0.5 + conf / 2)
est, se = agg[headline]["att"], agg[headline]["se"]
p = float(2 * stats.norm.sf(abs(est / se)))
ci_low, ci_high = est - z * se, est + z * se
# %% Checks
checks = []
if pretrend_p is not None:
if pretrend_p < 0.05:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "concern", "downgrade_to": "L2",
"detail": f"Pre-treatment ATT(g, t) differ from zero jointly (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)}): parallel trends are doubtful."})
else:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "pass",
"detail": f"Pre-treatment ATT(g, t) are jointly compatible with zero (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)})."})
else:
checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info", "detail": "No pre-treatment cells to test parallel trends."})
n_never = int((cohort == 0).sum())
if control_group == "never_treated" and n_never < 20:
checks.append({"id": "comparison_group", "label": "Comparison units", "status": "concern",
"detail": f"Only {n_never} never-treated units: estimates rest on a small comparison group; consider not-yet-treated units."})
else:
checks.append({"id": "comparison_group", "label": "Comparison units", "status": "pass",
"detail": f"{n_never} never-treated units" + (" plus not-yet-treated units" if control_group == "not_yet_treated" else "") + " form the comparison group."})
if COVARIATES and estimator in ("dr", "ipw"):
checks.append({"id": "overlap", "label": "Overlap", "status": "info",
"detail": "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units."})
# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.staggered/no-never-treated/out-python")
cell_df = pd.DataFrame(cells).assign(se=se_cells)
cell_df.to_parquet(os.path.join(out, "att_gt.parquet"), index=False)
artifacts = [{"key": "att_gt", "path": os.path.join(out, "att_gt.parquet"), "format": "parquet", "title": "Group-time average treatment effects"}]
dyn = agg["dynamic"]["by"]
summary = (
f"Averaged {'over cohorts and post-treatment periods' if headline == 'simple' else {'dynamic': 'over post-treatment event times', 'group': 'over cohorts', 'calendar': 'over calendar periods'}[headline]}, "
f"treatment changed {Y} by {est:.3g} ({conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p)}), estimated cohort by cohort against "
f"{'never-treated' if control_group == 'never_treated' else 'not-yet-treated'} units."
)
if pretrend_p is not None:
summary += (f" Pre-treatment effects differ from zero ({cs.fmt_p(pretrend_p)}): parallel trends are doubtful." if pretrend_p < 0.05
else f" Pre-treatment effects are compatible with parallel trends ({cs.fmt_p(pretrend_p)}).")
fin = lambda v: None if v is None or not np.isfinite(v) else float(v)
values = {
"estimate": est, "se": fin(se), "ci_low": ci_low, "ci_high": ci_high, "p_value": p, "n": n,
"att_simple": agg["simple"]["att"], "se_simple": fin(agg["simple"]["se"]), "att_dynamic": agg["dynamic"]["att"], "se_dynamic": fin(agg["dynamic"]["se"]),
"att_group": agg["group"]["att"], "se_group": fin(agg["group"]["se"]), "att_calendar": agg["calendar"]["att"], "se_calendar": fin(agg["calendar"]["se"]),
"n_cohorts": len(glist), "n_never_treated": n_never, "n_periods": len(tlist), "pretrend_chi2": W, "pretrend_p": pretrend_p,
"estimand": "ATT", "headline": headline,
"effect_label": f"Average effect of treatment on {Y} for treated cohorts after they were treated",
"claim_level_max": "L3",
}
for e, a, s in dyn:
values[f"es_estimate[{e:g}]"] = a
values[f"es_se[{e:g}]"] = fin(s)
for g, a, s in agg["group"]["by"]:
values[f"group_estimate[{g:g}]"] = a
values[f"group_se[{g:g}]"] = fin(s)
for t, a, s in agg["calendar"]["by"]:
values[f"calendar_estimate[{t:g}]"] = a
for c, s in zip(cells, se_cells):
values[f"attgt[{c['group']:g}:{c['time']:g}]"] = c["att"]
values[f"attgt_se[{c['group']:g}:{c['time']:g}]"] = float(s)
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
by_rows = lambda kind: [{"key": k, "estimate": a, "se": s, "low": a - z * s, "high": a + z * s} for k, a, s in agg[kind]["by"]]
cs.publish({
"method": "causal.staggered",
"methodVersion": "1.0.2",
"title": "Staggered difference-in-differences (Callaway–Sant'Anna)",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"ATT = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p)}",
"statistics": [
{"key": "estimate", "label": "ATT", "value": est},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p, "format": "p"},
],
"tables": [
{"key": "aggregations", "title": "Aggregated effects",
"columns": [{"key": "type", "label": "Aggregation", "type": "string"}, {"key": "estimate", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": [{"type": k, "estimate": agg[k]["att"], "se": agg[k]["se"]} for k in ("simple", "dynamic", "group", "calendar")]},
{"key": "event_study", "title": "By event time (periods since treatment)",
"columns": [{"key": "key", "label": "Event time", "type": "number"}, {"key": "estimate", "label": "ATT", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
"rows": by_rows("dynamic")},
{"key": "att_gt", "title": "Group-time effects ATT(g, t)",
"columns": [{"key": "group", "label": "Cohort", "type": "number"}, {"key": "time", "label": "Period", "type": "number"},
{"key": "att", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": cell_df[["group", "time", "att", "se"]].to_dict("records")},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings + notes,
"notes": [f"Estimator {estimator}, {base_period} base period, anticipation {anticipation:g}; analytic standard errors from influence functions (no bootstrap)."],
"values": values,
"artifacts": artifacts,
"charts": [cs.chart("event_study", "event-study", f"Effect on {Y} by periods since treatment", {
"rel_time": cs.col("Periods since treatment", [r[0] for r in dyn], kind="numeric"),
"estimate": cs.col("ATT", [r[1] for r in dyn], kind="numeric"),
"low": cs.col("Lower", [r[1] - z * r[2] for r in dyn], kind="numeric"),
"high": cs.col("Upper", [r[1] + z * r[2] for r in dyn], kind="numeric"),
}, controls={"reference": -1 if base_period == "universal" else None})],
})
This panel has 0 never-treated units, so not-yet-treated units are the only option. The headline is the calendar average: 0.830.
Check your understanding
CheckpointCheck yourself
Why can two-way fixed effects go wrong here?
Show the answer
Answer: b
The problem appears when effects change over time. If effects were constant across cohorts and time, TWFE would be fine.
Check yourself
You want to know how the effect evolves after adoption. Which summary fits?
Show the answer
Answer: b
Dynamic aggregation lines cohorts up by time since adoption, which is the question you asked.
Check yourself
The pre-trend test gives p = .168. What can you say?
Show the answer
Answer: a
The assumption is about what would have happened after adoption, and no test on earlier periods can check that. This one can also miss a real divergence.
Try it
In the appIn the Causal studio, start from Policy change over time (difference-in-differences), and choose staggered DiD on the Design step when your units adopt at different times.
Method guide · causal.staggeredStaggered difference-in-differences (Callaway–Sant'Anna)What was the effect of a treatment that different units adopted at different times?Recap
Recap- With staggered adoption and changing effects, one TWFE coefficient can mislead.
- Group-time ATTs compare each cohort only with clean controls.
- Choose an aggregation, and a control group, that fit your question.
Concepts in this lesson