Skip to content

When units adopt at different times

See why two-way fixed effects can mislead under staggered adoption, and estimate group-time effects instead.

Advanced ~11 min8 steps

What runs in CodeSplash

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

01

The trouble with one regression

Read

When 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.

02

Group-time effects

Read

Callaway and Sant'Anna estimate a separate effect for each adoption cohort gg in each period tt, using only clean controls:

ATT(g,t)=E[Yt−Yg−1∣G=g]−E[Yt−Yg−1∣C]\text{ATT}(g, t) = \mathbb{E}[Y_t - Y_{g-1} \mid G = g] - \mathbb{E}[Y_t - Y_{g-1} \mid C]

Those many small effects are then averaged in a way that fits your question.

03

Which summary is largest?

Predict

Predict 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?

They are all equalDynamic is larger in sizeSimple 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.

04

Read it

In the app
Staggered difference-in-differences (Callaway–Sant'Anna)Recorded · Python and R agreeRecorded 2026-11-17 · 73 values compared
R

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

Plots

Effect on lemp by periods since treatmentWere treated and control units on parallel paths before treatment, and how did the effect evolve after?
View data
ATTUpperLowerPeriods since treatment
0.03050.06000.0010−3
−0.00060.0255−0.0266−2
−0.02450.0034−0.0524−1
−0.01990.0032−0.04310
−0.0510−0.0178−0.08411
−0.1373−0.0658−0.20872
−0.1008−0.0335−0.16823

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

AggregationATTSE
simple−0.04000.0120
dynamic−0.07720.0200
group−0.03100.0124
calendar−0.04170.0160

By event time (periods since treatment)

Event timeATTSELowerUpper
−30.03050.01500.00100.0600
−2−0.00060.0133−0.02660.0255
−1−0.02450.0142−0.05240.0034
0−0.01990.0118−0.04310.0032
1−0.05100.0169−0.0841−0.0178
2−0.13730.0364−0.2087−0.0658
3−0.10080.0344−0.1682−0.0335

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,004−0.01050.0233
2,0042,005−0.07040.0310
2,0042,006−0.13730.0364
2,0042,007−0.10080.0344
2,0062,0040.00650.0233
2,0062,005−0.00280.0196
2,0062,006−0.00460.0178
2,0062,007−0.04120.0202
2,0072,0040.03050.0150
2,0072,005−0.00270.0164
2,0072,006−0.03110.0179
2,0072,007−0.02610.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)))
))
Python

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

AggregationATTSE
simple−0.04000.0120
dynamic−0.07720.0200
group−0.03100.0124
calendar−0.04170.0160

By event time (periods since treatment)

Event timeATTSELowerUpper
−30.03050.01500.00100.0600
−2−0.00060.0133−0.02660.0255
−1−0.02450.0142−0.05240.0034
0−0.01990.0118−0.04310.0032
1−0.05100.0169−0.0841−0.0178
2−0.13730.0364−0.2087−0.0658
3−0.10080.0344−0.1682−0.0335

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,004−0.01050.0233
2,0042,005−0.07040.0310
2,0042,006−0.13730.0364
2,0042,007−0.10080.0344
2,0062,0040.00650.0233
2,0062,005−0.00280.0196
2,0062,006−0.00460.0178
2,0062,007−0.04120.0202
2,0072,0040.03050.0150
2,0072,005−0.00270.0164
2,0072,006−0.03110.0179
2,0072,007−0.02610.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.

05

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.
Staggered difference-in-differences (Callaway–Sant'Anna)Recorded · Python and R agreeRecorded 2026-11-17 · 92 values compared
R

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

Effect on y by periods since treatmentWere treated and control units on parallel paths before treatment, and how did the effect evolve after?
View data
ATTUpperLowerPeriods since treatment
−0.03310.1743−0.2406−5
−0.14620.0454−0.3378−4
0.11340.2587−0.0319−3
−0.05490.0688−0.1786−2
−0.00870.1139−0.1313−1
0.61000.72370.49630
0.82430.97240.67621
0.96771.1190.81682
1.1641.3890.93913
1.4511.6981.2054

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

AggregationATTSE
simple0.89210.0606
dynamic1.0030.0694
group0.84210.0644
calendar0.83030.0619

By event time (periods since treatment)

Event timeATTSELowerUpper
−5−0.03310.1058−0.24060.1743
−4−0.14620.0978−0.33780.0454
−30.11340.0741−0.03190.2587
−2−0.05490.0631−0.17860.0688
−1−0.00870.0626−0.13130.1139
00.61000.05800.49630.7237
10.82430.07560.67620.9724
20.96770.07700.81681.119
31.1640.11470.93911.389
41.4510.12591.2051.698

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,003−0.05090.1023
2,0042,0040.56250.1003
2,0042,0050.80740.0974
2,0042,0060.83770.0989
2,0042,0071.1640.1147
2,0042,0081.4510.1259
2,0062,003−0.03530.0995
2,0062,0040.02970.0771
2,0062,005−0.09820.0837
2,0062,0060.52830.0779
2,0062,0070.84110.1082
2,0062,0081.0980.1095
2,0082,003−0.03310.1058
2,0082,004−0.14620.0978
2,0082,0050.26210.1007
2,0082,006−0.13940.1006
2,0082,0070.12300.1205
2,0082,0080.73930.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)))
))
Python

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

AggregationATTSE
simple0.89210.0606
dynamic1.0030.0694
group0.84210.0644
calendar0.83030.0619

By event time (periods since treatment)

Event timeATTSELowerUpper
−5−0.03310.1058−0.24060.1743
−4−0.14620.0978−0.33780.0454
−30.11340.0741−0.03190.2587
−2−0.05490.0631−0.17860.0688
−1−0.00870.0626−0.13130.1139
00.61000.05800.49630.7237
10.82430.07560.67620.9724
20.96770.07700.81681.119
31.1640.11470.93911.389
41.4510.12591.2051.698

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,003−0.05090.1023
2,0042,0040.56250.1003
2,0042,0050.80740.0974
2,0042,0060.83770.0989
2,0042,0071.1640.1147
2,0042,0081.4510.1259
2,0062,003−0.03530.0995
2,0062,0040.02970.0771
2,0062,005−0.09820.0837
2,0062,0060.52830.0779
2,0062,0070.84110.1082
2,0062,0081.0980.1095
2,0082,003−0.03310.1058
2,0082,004−0.14620.0978
2,0082,0050.26210.1007
2,0082,006−0.13940.1006
2,0082,0070.12300.1205
2,0082,0080.73930.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.

06

Check your understanding

Checkpoint

Check 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.

07

Try it

In the app

In 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?
08

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