Skip to content

How strong a claim can you make?

Match your wording to the design. The claim ladder runs from description to experimental evidence.

Applied ~8 min7 steps

What runs in CodeSplash

You will be able to

  • Place a study on the five-level claim ladder
  • Choose wording that fits the claim level
  • Say what would have to change to reach a higher level

Read first

01

Five rungs

Read

The design limits what you may say, however good the estimate looks. The studio's claim ladderClaim levelHow strong a causal statement the design supports, from association up to a causal effect. has five levels:

LevelNameWhat backs it
L0DescriptiveSummaries only
L1Adjusted associationA model with controls, no causal design
L2Conditional causalA DAG, measured confounders, sensitivity analysis
L3Quasi-experimentalVariation from a credible design (DiD, RDD, IV)
L4ExperimentalRandomized assignment
02

Place each design

Predict

Predict first

You estimate the effect of a scholarship with a regression discontinuity at the eligibility cutoff. What's the highest level the design supports?

L1L2L3L4
Reveal

L3: a cutoff gives quasi-experimental variation. For comparison, a pooled panel regression reaches L1, matching reaches L2, a difference-in-differences reaches L3, and a randomized uplift study reaches L4.

03

The ceiling isn't guaranteed

In the app

Each design sets a maximum. You earn it by passing the checks. A DiD whose pre-trends fail, or a matched study with no sensitivity analysis, sits lower than its ceiling. This run's pre-trends fail, so look at what its checks say.

Difference-in-differencesRecorded · Python and R agreeRecorded 2026-11-17 · 52 values compared
R

DiD = 3.19, SE = 0.11, t(49) = 30.27, p < .001, 90% CI [3.01, 3.37]

Difference-in-differences
3.190
90% CI
[3.014, 3.367]
SE
0.1054
p
< .001

Plots

Effect on sales by period relative to treatmentWere treated and control units on parallel paths before treatment, and how did the effect evolve after?
View data
EstimateUpperLowerPeriods relative to treatment
−1.212−0.8675−1.557−5
−0.9017−0.5744−1.229−4
−0.4093−0.1442−0.6744−3
−0.3461−0.0539−0.6383−2
000−1
1.4031.7421.0630
1.9462.2451.6471
2.5832.9422.2242
3.3543.6523.0563
3.7964.1263.4664
Mean sales by groupWhere is the series heading, and how uncertain is the forecast?
View data
kindGroupdatesales
actualComparison1,293,840,000,0009.523
actualComparison1,325,376,000,0009.786
actualComparison1,356,998,400,0009.777
actualComparison1,388,534,400,0009.957
actualComparison1,420,070,400,0009.911
actualComparison1,451,606,400,00010.399
actualComparison1,483,228,800,00010.460
actualComparison1,514,764,800,00010.636
actualComparison1,546,300,800,00010.712
actualComparison1,577,836,800,00011.025
actualTreated1,293,840,000,0009.865
actualTreated1,325,376,000,00010.439
actualTreated1,356,998,400,00010.923
actualTreated1,388,534,400,00011.165
actualTreated1,420,070,400,00011.465
actualTreated1,451,606,400,00013.356
actualTreated1,483,228,800,00013.961
actualTreated1,514,764,800,00014.774
actualTreated1,546,300,800,00015.621
actualTreated1,577,836,800,00016.376

Assumptions

  • Parallel pre-trends — Leads before treatment differ from zero jointly (F = 10.36, p < .001): the groups were already diverging, so parallel trends are doubtful.
  • Clustered standard errors — Standard errors clustered on 50 clusters.
  • Common treatment timing — All treated units start treatment in the same period.

Difference-in-differences regression (fixed effects: unit + time)

TermEstimateSE
Treated × post (treated)3.1900.1054

Group means

GroupBeforeAfterChange
Treated10.77214.8184.046
Comparison9.79110.6460.8557

Event study (reference: period −1)

PeriodEstimateSELowerUpperp
−5−1.2120.2056−1.557−0.86753.393e-7
−4−0.90170.1952−1.229−0.57442.822e-5
−3−0.40930.1581−0.6744−0.14420.0127
−2−0.34610.1743−0.6383−0.05390.0526
−10000—
01.4030.20251.0631.7428.659e-9
11.9460.17841.6472.2451.035e-14
22.5830.21412.2242.9422.758e-16
33.3540.17773.0563.6524.024e-24
43.7960.19683.4664.1261.574e-24
  • Design: twfe; standard errors clustered by firm; t with 49 df.
The exact R script · R R version 4.5.1 (2025-06-13)
# Difference-in-differences (2 × 2, two-way fixed effects, event study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.did 1.0.2 · spec 392db9697b64eaff
# Dataset: c1_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
library(fixest)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_panel.parquet", col_select = c("sales", "treated", "post", "firm", "date")))
n_input <- nrow(df)
df[["treated"]] <- factor(df[["treated"]], levels = c("false", "true"))  # stored level order
df[["post"]] <- factor(df[["post"]], levels = c("false", "true"))  # stored level order
df[["firm"]] <- factor(df[["firm"]], levels = c("f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39", "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49", "f50"))  # stored level order
df <- df[stats::complete.cases(df[c("sales", "treated", "post", "firm", "date")]), , 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("sales", "treated", "post", "firm", "date"))  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y <- "sales"
TREAT <- "treated"
POST <- "post"
UNIT <- "firm"
TIME <- "date"
CLUSTER <- NULL
COVARIATES <- c()
TIME_TEMPORAL <- TRUE
conf <- 0.9
event_study <- TRUE
leads <- as.integer(5)
lags <- as.integer(4)

level_of <- function(col, chosen) {
  lv <- levels(df[[col]])
  if (!is.null(chosen)) chosen else if ("true" %in% lv) "true" else lv[length(lv)]
}

treated_level <- level_of(TREAT, NULL)
d <- data.frame(y = as.numeric(df[[Y]]))
d$treated <- as.numeric(as.character(df[[TREAT]]) == treated_level)
if (!is.null(TIME)) {
  tvals <- if (TIME_TEMPORAL) as.Date(df[[TIME]], tz = "UTC") else as.numeric(df[[TIME]])
  periods <- sort(unique(tvals))
  d$time <- match(tvals, periods) - 1L  # period index
}
treatment_start <- NULL
if (!is.null(POST)) {
  d$post <- as.numeric(as.character(df[[POST]]) == level_of(POST, NULL))
} else if (!is.null(treatment_start) && !is.null(TIME) && !TIME_TEMPORAL) {
  d$post <- as.numeric(tvals >= treatment_start)
} else {
  stop("Choose an 'After treatment' column, or a numeric time column and 'Treatment starts'.")
}
if (!is.null(UNIT)) d$unit <- as.character(df[[UNIT]])
cluster_col <- if (!is.null(CLUSTER)) CLUSTER else UNIT
if (!is.null(cluster_col)) d$cl <- as.character(df[[cluster_col]])
xs <- character(0)
for (j in seq_along(COVARIATES)) {
  d[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
  xs <- c(xs, paste0("x", j))
}
d$d <- d$treated * d$post
if (sum(d$d) == 0 || all(d$d == 1)) {
  cs_error("CS_E_UNDEFINED", what = "Difference-in-differences", reason = "it needs both treated post-treatment rows and other rows")
}
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
if (!is.null(UNIT)) {
  rows_per_unit <- table(d$unit)
  if (length(rows_per_unit) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = length(rows_per_unit))
  if (max(rows_per_unit) < 2) {  # unit fixed effects would absorb every row
    cs_error("CS_E_UNDEFINED", what = "Difference-in-differences with unit fixed effects", reason = sprintf("every value of %s has only one row", UNIT))
  }
}
if (!is.null(UNIT) && max(tapply(d$treated, d$unit, function(v) length(unique(v)))) > 1) {
  warnings <- c(warnings, sprintf("%s changes within some units; the treated group is defined row by row.", TREAT))
}

# %% Fit: two-way fixed effects with fixest (default small-sample corrections)
vc <- if (!is.null(cluster_col)) ~cl else "hetero"
if (!is.null(UNIT) && !is.null(TIME)) {
  rhs <- "d"; fe <- "unit + time"
} else if (!is.null(UNIT)) {
  rhs <- c("d", "post"); fe <- "unit"
} else if (!is.null(TIME)) {
  rhs <- c("d", "treated"); fe <- "time"
} else {
  rhs <- c("d", "treated", "post"); fe <- NULL
}
fml <- as.formula(paste("y ~", paste(c(rhs, xs), collapse = " + "), if (!is.null(fe)) paste("|", fe) else ""))
fit <- feols(fml, data = d, vcov = vc)
b <- coef(fit)
V <- vcov(fit)
df_t <- unname(degrees_freedom(fit, "t"))
qt_ <- qt(0.5 + conf / 2, df_t)
est <- unname(b["d"])
se <- sqrt(V["d", "d"])
tstat <- est / se
p <- 2 * pt(-abs(tstat), df_t)
ci_low <- est - qt_ * se
ci_high <- est + qt_ * se
n <- nobs(fit)
n_clusters <- if (!is.null(cluster_col)) length(unique(d$cl)) else NULL

# Raw 2 × 2 means.
cell <- function(tr, po) { v <- d$y[d$treated == tr & d$post == po]; if (length(v)) mean(v) else NA_real_ }
m <- list(tp = cell(1, 0), tq = cell(1, 1), cp = cell(0, 0), cq = cell(0, 1))
did_raw <- (m$tq - m$tp) - (m$cq - m$cp)

# %% Event study: leads and lags relative to each treated unit's first post-treatment period
es_rows <- NULL
pretrend_f <- NULL
pretrend_p <- NULL
starts <- NULL
if (!is.null(UNIT) && !is.null(TIME)) {
  tp <- d[d$treated == 1 & d$post == 1, ]
  first_post <- tapply(tp$time, tp$unit, min)
  starts <- unique(as.numeric(first_post))
}
if (event_study) {
  if (is.null(UNIT) || is.null(TIME)) stop("The event study needs a unit and a time column.")
  rel <- d$time - as.numeric(first_post[d$unit])
  rel <- pmin(pmax(rel, -leads), lags)
  ev <- list()
  for (e in seq(-leads, lags)) {
    if (e == -1) next  # reference period
    nm <- if (e < 0) paste0("lead", -e) else paste0("lag", e)
    col <- as.numeric(!is.na(rel) & rel == e)
    if (sum(col) > 0) {
      d[[nm]] <- col
      ev[[length(ev) + 1]] <- list(e = e, name = nm)
    }
  }
  ev_names <- vapply(ev, function(x) x$name, character(1))
  es_fit <- feols(as.formula(paste("y ~", paste(c(ev_names, xs), collapse = " + "), "| unit + time")), data = d, vcov = vc)
  eb <- coef(es_fit)
  eV <- vcov(es_fit)
  edf <- unname(degrees_freedom(es_fit, "t"))
  eq <- qt(0.5 + conf / 2, edf)
  es_rows <- do.call(rbind, lapply(ev, function(x) {
    s <- sqrt(eV[x$name, x$name])
    data.frame(rel_time = x$e, estimate = unname(eb[x$name]), se = s, low = unname(eb[x$name]) - eq * s,
               high = unname(eb[x$name]) + eq * s, p = 2 * pt(-abs(unname(eb[x$name]) / s), edf))
  }))
  es_rows <- rbind(es_rows, data.frame(rel_time = -1, estimate = 0, se = 0, low = 0, high = 0, p = NA_real_))
  es_rows <- es_rows[order(es_rows$rel_time), ]
  pre <- vapply(ev, function(x) x$e <= -2, logical(1))
  if (any(pre)) {
    bp <- eb[ev_names[pre]]
    Vp <- eV[ev_names[pre], ev_names[pre], drop = FALSE]
    pretrend_f <- as.numeric(t(bp) %*% solve(Vp, bp)) / sum(pre)
    pretrend_p <- pf(pretrend_f, sum(pre), edf, lower.tail = FALSE)
  }
}

# %% 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("Leads before treatment differ from zero jointly (F = %.2f, %s): the groups were already diverging, so parallel trends are doubtful.", pretrend_f, cs_fmt_p(pretrend_p)))
  } else {
    add_check(id = "pretrend", label = "Parallel pre-trends", status = "pass",
              detail = sprintf("Leads before treatment are jointly compatible with zero (F = %.2f, %s). This supports, but cannot prove, parallel trends after treatment.", pretrend_f, cs_fmt_p(pretrend_p)))
  }
} else if (!is.null(UNIT) && !is.null(TIME)) {
  add_check(id = "pretrend", label = "Parallel pre-trends", status = "info",
            detail = "Turn on the event study to test whether the groups trended in parallel before treatment.")
} else {
  add_check(id = "pretrend", label = "Parallel pre-trends", status = "info",
            detail = "With only before/after periods, parallel trends cannot be tested; attest why the comparison group's change is a good counterfactual.")
}
if (is.null(cluster_col)) {
  add_check(id = "clusters", label = "Clustered standard errors", status = "concern",
            detail = "No unit or cluster column: standard errors assume independent rows, which overstates precision when units are observed repeatedly.")
} else if (n_clusters < 30) {
  add_check(id = "clusters", label = "Clustered standard errors", status = "concern",
            detail = sprintf("Only %d clusters: clustered standard errors can be too small; consider a wild cluster bootstrap.", n_clusters))
} else {
  add_check(id = "clusters", label = "Clustered standard errors", status = "pass", detail = sprintf("Standard errors clustered on %d clusters.", n_clusters))
}
if (!is.null(starts) && length(starts) > 1) {
  add_check(id = "staggered_timing", label = "Common treatment timing", status = "concern", downgrade_to = "L2",
            detail = sprintf("Treated units start in %d different periods: two-way fixed effects can be biased with staggered adoption and changing effects. Use the staggered (Callaway–Sant'Anna) design.", length(starts)))
} else if (!is.null(starts)) {
  add_check(id = "staggered_timing", label = "Common treatment timing", status = "pass", detail = "All treated units start treatment in the same period.")
}

# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.did/pretrend-fails/out-r")
artifacts <- list()
charts <- list()
if (!is.null(es_rows)) {
  nanoparquet::write_parquet(es_rows, file.path(out, "event_study.parquet"))
  artifacts[[1]] <- list(key = "event_study", path = file.path(out, "event_study.parquet"), format = "parquet", title = "Event-study coefficients")
  charts[[length(charts) + 1]] <- cs_chart("event_study", "event-study", sprintf("Effect on %s by period relative to treatment", Y), list(
    rel_time = cs_col("Periods relative to treatment", es_rows$rel_time, kind = "numeric"),
    estimate = cs_col("Estimate", es_rows$estimate, kind = "numeric"),
    low = cs_col("Lower", es_rows$low, kind = "numeric"),
    high = cs_col("Upper", es_rows$high, kind = "numeric")
  ), controls = list(reference = -1))
}
if (!is.null(TIME)) {
  trend <- aggregate(y ~ time + treated, data = d, FUN = mean)
  trend <- trend[order(trend$treated, trend$time), ]
  label <- if (TIME_TEMPORAL) format(periods[trend$time + 1], "%Y-%m-%d") else as.numeric(periods[trend$time + 1])
  charts[[length(charts) + 1]] <- cs_chart("trends", "forecast-fan", sprintf("Mean %s by group", Y), list(
    time = cs_col(TIME, label, kind = if (TIME_TEMPORAL) "temporal" else "numeric"),
    value = cs_col(Y, trend$y, kind = "numeric"),
    kind = cs_col("kind", rep("actual", nrow(trend)), kind = "categorical", levels = "actual"),
    series = cs_col("Group", ifelse(trend$treated == 1, "Treated", "Comparison"), kind = "categorical", levels = c("Comparison", "Treated"))
  ))
}
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("After treatment began, %s changed by %.2f %s in the treated group than in the comparison group (difference-in-differences %.2f, %s CI [%.2f, %.2f], %s).",
                   Y, abs(est), if (est > 0) "more" else "less", est, pct, ci_low, ci_high, cs_fmt_p(p))
if (!is.null(pretrend_p)) {
  summary <- paste(summary, if (pretrend_p < 0.05) sprintf("Leads before treatment differ from zero (%s): parallel trends are doubtful.", cs_fmt_p(pretrend_p))
                   else sprintf("Leads before treatment are compatible with parallel trends (%s).", cs_fmt_p(pretrend_p)))
}
design <- if (!is.null(UNIT) && !is.null(TIME)) "twfe" else if (!is.null(UNIT)) "unit_fe" else if (!is.null(TIME)) "time_fe" else "2x2"
values <- list(
  estimate = est, se = se, t = tstat, p_value = p, ci_low = ci_low, ci_high = ci_high, n = n,
  n_units = if (!is.null(UNIT)) length(unique(d$unit)) else NULL,
  n_treated_units = if (!is.null(UNIT)) length(unique(d$unit[d$treated == 1])) else NULL,
  n_clusters = n_clusters, df_t = df_t, design = design,
  did_raw = did_raw, mean_treated_pre = m$tp, mean_treated_post = m$tq, mean_control_pre = m$cp, mean_control_post = m$cq,
  pretrend_f = pretrend_f, pretrend_p = pretrend_p,
  estimand = "ATT",
  effect_label = sprintf("Average effect of treatment on %s for the treated group after treatment began", Y),
  claim_level_max = "L3"
)
if (!is.null(es_rows)) {
  for (i in seq_len(nrow(es_rows))) {
    e <- es_rows$rel_time[i]
    if (e == -1) next
    values[[sprintf("es_estimate[%d]", e)]] <- es_rows$estimate[i]
    values[[sprintf("es_se[%d]", e)]] <- es_rows$se[i]
    values[[sprintf("es_p[%d]", e)]] <- es_rows$p[i]
  }
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
term_label <- function(nm) {
  if (nm == "d") return(sprintf("Treated × post (%s)", TREAT))
  if (nm == "post") return("Post")
  if (nm == "treated") return("Treated group")
  if (startsWith(nm, "x")) return(COVARIATES[as.integer(substring(nm, 2))])
  nm
}
coef_rows <- data.frame(term = vapply(names(b), term_label, character(1)), estimate = unname(b), se = unname(sqrt(diag(V))))
tables <- list(
  list(key = "coefficients", title = paste0("Difference-in-differences regression", if (!is.null(fe)) sprintf(" (fixed effects: %s)", fe) else ""),
       columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                      list(key = "se", label = "SE", type = "number")),
       rows = coef_rows),
  list(key = "means", title = "Group means",
       columns = list(list(key = "group", label = "Group", type = "string"), list(key = "pre", label = "Before", type = "number"),
                      list(key = "post", label = "After", type = "number"), list(key = "change", label = "Change", type = "number")),
       rows = data.frame(group = c("Treated", "Comparison"), pre = c(m$tp, m$cp), post = c(m$tq, m$cq), change = c(m$tq - m$tp, m$cq - m$cp)))
)
if (!is.null(es_rows)) {
  tables[[length(tables) + 1]] <- list(key = "event_study", title = "Event study (reference: period −1)",
    columns = list(list(key = "rel_time", label = "Period", type = "integer"), list(key = "estimate", label = "Estimate", type = "number"),
                   list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Lower", type = "number"),
                   list(key = "high", label = "Upper", type = "number"), list(key = "p", label = "p", type = "p")),
    rows = es_rows)
}
cs_publish(list(
  method = "causal.did",
  methodVersion = "1.0.2",
  title = "Difference-in-differences",
  engine = cs_engine_info("fixest", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("DiD = %s, SE = %s, t(%.0f) = %s, %s, %s CI [%s, %s]", cs_fmt_num(est), cs_fmt_num(se), df_t, cs_fmt_num(tstat), cs_fmt_p(p), pct,
                cs_fmt_num(ci_low), cs_fmt_num(ci_high)),
  statistics = list(
    list(key = "estimate", label = "Difference-in-differences", value = est),
    list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
    list(key = "se", label = "SE", value = se),
    list(key = "p_value", label = "p", value = p, format = "p")
  ),
  tables = tables,
  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("Design: %s; standard errors %s; t with %.0f df.", design,
                       if (!is.null(cluster_col)) paste("clustered by", cluster_col) else "heteroskedasticity-robust (HC1)", df_t)),
  values = values,
  artifacts = artifacts,
  charts = charts
))
Python

DiD = 3.19, SE = 0.11, t(49) = 30.27, p < .001, 90% CI [3.01, 3.37]

Difference-in-differences
3.190
90% CI
[3.014, 3.367]
SE
0.1054
p
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Parallel pre-trends — Leads before treatment differ from zero jointly (F = 10.36, p < .001): the groups were already diverging, so parallel trends are doubtful.
  • Clustered standard errors — Standard errors clustered on 50 clusters.
  • Common treatment timing — All treated units start treatment in the same period.

Difference-in-differences regression (fixed effects: unit + time)

TermEstimateSE
Treated × post (treated)3.1900.1054

Group means

GroupBeforeAfterChange
Treated10.77214.8184.046
Comparison9.79110.6460.8557

Event study (reference: period −1)

PeriodEstimateSELowerUpperp
−5−1.2120.2056−1.557−0.86753.393e-7
−4−0.90170.1952−1.229−0.57442.822e-5
−3−0.40930.1581−0.6744−0.14420.0127
−2−0.34610.1743−0.6383−0.05390.0526
−10000—
01.4030.20251.0631.7428.659e-9
11.9460.17841.6472.2451.035e-14
22.5830.21412.2242.9422.758e-16
33.3540.17773.0563.6524.024e-24
43.7960.19683.4664.1261.574e-24
  • Design: twfe; standard errors clustered by firm; t with 49 df.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Difference-in-differences (2 × 2, two-way fixed effects, event study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.did 1.0.2 · spec 392db9697b64eaff
# Dataset: c1_panel (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
import pyfixest as pf
from scipy import stats

import codesplash as cs
from codesplash import ml as csml

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_panel.parquet", columns=["sales", "treated", "post", "firm", "date"])
n_input = len(df)
df["treated"] = pd.Categorical(df["treated"], categories=["false", "true"])  # stored level order
df["post"] = pd.Categorical(df["post"], categories=["false", "true"])  # stored level order
df["firm"] = pd.Categorical(df["firm"], categories=["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39", "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49", "f50"])  # stored level order
df = df.dropna(subset=["sales", "treated", "post", "firm", "date"])  # listwise deletion over the analysis columns
df["treated"] = df["treated"].cat.remove_unused_categories()
df["post"] = df["post"].cat.remove_unused_categories()
df["firm"] = df["firm"].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, ["sales", "treated", "post", "firm", "date"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y = "sales"
TREAT = "treated"
POST = "post"
UNIT = "firm"
TIME = "date"
CLUSTER = None
COVARIATES = []
TIME_TEMPORAL = True
conf = 0.9
event_study = True
leads, lags = int(5), int(4)


def level_of(col, chosen):
    levels = [str(x) for x in df[col].cat.categories]
    return chosen if chosen is not None else ("true" if "true" in levels else levels[-1])


treated_level = level_of(TREAT, None)
d = pd.DataFrame({"y": df[Y].astype(float).to_numpy()})
d["treated"] = (df[TREAT].astype(str) == treated_level).astype(float).to_numpy()
if TIME:
    tvals = pd.to_datetime(df[TIME]) if TIME_TEMPORAL else df[TIME].astype(float)
    periods = np.sort(tvals.unique())
    d["time"] = np.searchsorted(periods, tvals.to_numpy()).astype(int)  # period index
treatment_start = None
if POST:
    d["post"] = (df[POST].astype(str) == level_of(POST, None)).astype(float).to_numpy()
elif treatment_start is not None and TIME and not TIME_TEMPORAL:
    d["post"] = (tvals.to_numpy() >= float(treatment_start)).astype(float)
else:
    raise ValueError("Choose an 'After treatment' column, or a numeric time column and 'Treatment starts'.")
if UNIT:
    d["unit"] = df[UNIT].astype(str).to_numpy()
cluster_col = CLUSTER or UNIT
if cluster_col:
    d["cl"] = df[cluster_col].astype(str).to_numpy()
for j, c in enumerate(COVARIATES):
    d[f"x{j + 1}"] = df[c].astype(float).to_numpy()
xs = [f"x{j + 1}" for j in range(len(COVARIATES))]
d["d"] = d["treated"] * d["post"]
if d["d"].sum() == 0 or (d["d"] == 1).all():
    cs.cs_error("CS_E_UNDEFINED", what="Difference-in-differences", reason="it needs both treated post-treatment rows and other rows")
if d["y"].nunique() < 2:
    cs.cs_error("CS_E_CONSTANT", column=Y)
if UNIT:
    rows_per_unit = d["unit"].value_counts()
    if len(rows_per_unit) < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=len(rows_per_unit))
    if rows_per_unit.max() < 2:  # unit fixed effects would absorb every row
        cs.cs_error("CS_E_UNDEFINED", what="Difference-in-differences with unit fixed effects", reason=f"every value of {UNIT} has only one row")
if UNIT and d.groupby("unit")["treated"].nunique().max() > 1:
    warnings.append(f"{TREAT} changes within some units; the treated group is defined row by row.")

# %% Fit: two-way fixed effects (pyfixest ≡ R fixest; fixest small-sample conventions)
vcov = {"CRV1": "cl"} if cluster_col else "hetero"
if UNIT and TIME:
    rhs, fe = ["d"], "unit + time"
elif UNIT:
    rhs, fe = ["d", "post"], "unit"
elif TIME:
    rhs, fe = ["d", "treated"], "time"
else:
    rhs, fe = ["d", "treated", "post"], None
formula = "y ~ " + " + ".join(rhs + xs) + (f" | {fe}" if fe else "")
fit = pf.feols(formula, data=d, vcov=vcov)
names = list(fit.coef().index)
b = fit.coef().to_numpy()
V = np.asarray(fit._vcov)
df_t = float(fit._df_t)
qt = stats.t.ppf(0.5 + conf / 2, df_t)
i = names.index("d")
est, se = float(b[i]), float(np.sqrt(V[i, i]))
tstat = est / se
p = float(2 * stats.t.sf(abs(tstat), df_t))
ci_low, ci_high = est - qt * se, est + qt * se
n = int(fit._N)
n_clusters = int(d["cl"].nunique()) if cluster_col else None

# Raw 2 × 2 means.
means = d.groupby(["treated", "post"])["y"].mean()
m = {(int(a), int(b_)): float(v) for (a, b_), v in means.items()}
did_raw = (m.get((1, 1), np.nan) - m.get((1, 0), np.nan)) - (m.get((0, 1), np.nan) - m.get((0, 0), np.nan))

# %% Event study: leads and lags relative to each treated unit's first post-treatment period
es_rows, pretrend_f, pretrend_p = [], None, None
starts = None
if UNIT and TIME:
    first_post = d[(d["treated"] == 1) & (d["post"] == 1)].groupby("unit")["time"].min()
    starts = first_post.unique()
if event_study:
    if not (UNIT and TIME):
        raise ValueError("The event study needs a unit and a time column.")
    rel = d["unit"].map(first_post)
    rel = (d["time"] - rel).where(rel.notna())
    rel = rel.clip(lower=-leads, upper=lags)
    ev = []
    for e in range(-leads, lags + 1):
        if e == -1:
            continue  # reference period
        name = f"lead{-e}" if e < 0 else f"lag{e}"
        col = (rel == e).astype(float)
        if col.sum() > 0:
            d[name] = col
            ev.append((e, name))
    es_fit = pf.feols("y ~ " + " + ".join([nm for _, nm in ev] + xs) + " | unit + time", data=d, vcov=vcov)
    es_names = list(es_fit.coef().index)
    eb, eV, edf = es_fit.coef().to_numpy(), np.asarray(es_fit._vcov), float(es_fit._df_t)
    eq = stats.t.ppf(0.5 + conf / 2, edf)
    for e, nm in ev:
        j = es_names.index(nm)
        s = float(np.sqrt(eV[j, j]))
        es_rows.append({"rel_time": e, "estimate": float(eb[j]), "se": s, "low": float(eb[j]) - eq * s, "high": float(eb[j]) + eq * s,
                        "p": float(2 * stats.t.sf(abs(eb[j] / s), edf))})
    es_rows.append({"rel_time": -1, "estimate": 0.0, "se": 0.0, "low": 0.0, "high": 0.0, "p": None})
    es_rows.sort(key=lambda r: r["rel_time"])
    pre = [es_names.index(nm) for e, nm in ev if e <= -2]
    if pre:
        bp = eb[pre]
        Vp = eV[np.ix_(pre, pre)]
        pretrend_f = float(bp @ np.linalg.solve(Vp, bp) / len(pre))
        pretrend_p = float(stats.f.sf(pretrend_f, len(pre), edf))

# %% 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"Leads before treatment differ from zero jointly (F = {pretrend_f:.2f}, {cs.fmt_p(pretrend_p)}): the groups were already diverging, so parallel trends are doubtful."})
    else:
        checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "pass",
                       "detail": f"Leads before treatment are jointly compatible with zero (F = {pretrend_f:.2f}, {cs.fmt_p(pretrend_p)}). This supports, but cannot prove, parallel trends after treatment."})
elif UNIT and TIME:
    checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info",
                   "detail": "Turn on the event study to test whether the groups trended in parallel before treatment."})
else:
    checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info",
                   "detail": "With only before/after periods, parallel trends cannot be tested; attest why the comparison group's change is a good counterfactual."})
if not cluster_col:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "concern",
                   "detail": "No unit or cluster column: standard errors assume independent rows, which overstates precision when units are observed repeatedly."})
elif n_clusters < 30:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "concern",
                   "detail": f"Only {n_clusters} clusters: clustered standard errors can be too small; consider a wild cluster bootstrap."})
else:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "pass", "detail": f"Standard errors clustered on {n_clusters} clusters."})
if starts is not None and len(starts) > 1:
    checks.append({"id": "staggered_timing", "label": "Common treatment timing", "status": "concern", "downgrade_to": "L2",
                   "detail": f"Treated units start in {len(starts)} different periods: two-way fixed effects can be biased with staggered adoption and changing effects. Use the staggered (Callaway–Sant'Anna) design."})
elif starts is not None:
    checks.append({"id": "staggered_timing", "label": "Common treatment timing", "status": "pass", "detail": "All treated units start treatment in the same period."})

# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.did/pretrend-fails/out-python")
artifacts = []
if es_rows:
    pd.DataFrame(es_rows).to_parquet(os.path.join(out, "event_study.parquet"), index=False)
    artifacts.append({"key": "event_study", "path": os.path.join(out, "event_study.parquet"), "format": "parquet", "title": "Event-study coefficients"})
charts = []
if es_rows:
    charts.append(cs.chart("event_study", "event-study", f"Effect on {Y} by period relative to treatment", {
        "rel_time": cs.col("Periods relative to treatment", [r["rel_time"] for r in es_rows], kind="numeric"),
        "estimate": cs.col("Estimate", [r["estimate"] for r in es_rows], kind="numeric"),
        "low": cs.col("Lower", [r["low"] for r in es_rows], kind="numeric"),
        "high": cs.col("Upper", [r["high"] for r in es_rows], kind="numeric"),
    }, controls={"reference": -1}))
if TIME:
    trend = d.groupby(["time", "treated"])["y"].mean().reset_index().sort_values(["treated", "time"], kind="mergesort")
    label = (lambda t: pd.Timestamp(periods[t]).strftime("%Y-%m-%d")) if TIME_TEMPORAL else (lambda t: float(periods[t]))
    charts.append(cs.chart("trends", "forecast-fan", f"Mean {Y} by group", {
        "time": cs.col(TIME, [label(int(t)) for t in trend["time"]], kind="temporal" if TIME_TEMPORAL else "numeric"),
        "value": cs.col(Y, trend["y"].to_numpy(dtype=float), kind="numeric"),
        "kind": cs.col("kind", ["actual"] * len(trend), kind="categorical", levels=["actual"]),
        "series": cs.col("Group", np.where(trend["treated"] == 1, "Treated", "Comparison"), kind="categorical", levels=["Comparison", "Treated"]),
    }))
direction = "more" if est > 0 else "less"
summary = (
    f"After treatment began, {Y} changed by {abs(est):.2f} {direction} in the treated group than in the comparison group "
    f"(difference-in-differences {est:.2f}, {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}], {cs.fmt_p(p)})."
)
if pretrend_p is not None:
    summary += (f" Leads before treatment differ from zero ({cs.fmt_p(pretrend_p)}): parallel trends are doubtful." if pretrend_p < 0.05
                else f" Leads before treatment are compatible with parallel trends ({cs.fmt_p(pretrend_p)}).")
design = "twfe" if (UNIT and TIME) else ("unit_fe" if UNIT else ("time_fe" if TIME else "2x2"))
values = {
    "estimate": est, "se": se, "t": tstat, "p_value": p, "ci_low": ci_low, "ci_high": ci_high, "n": n,
    "n_units": int(d["unit"].nunique()) if UNIT else None,
    "n_treated_units": int(d.loc[d["treated"] == 1, "unit"].nunique()) if UNIT else None,
    "n_clusters": n_clusters, "df_t": df_t, "design": design,
    "did_raw": did_raw, "mean_treated_pre": m.get((1, 0)), "mean_treated_post": m.get((1, 1)),
    "mean_control_pre": m.get((0, 0)), "mean_control_post": m.get((0, 1)),
    "pretrend_f": pretrend_f, "pretrend_p": pretrend_p,
    "estimand": "ATT",
    "effect_label": f"Average effect of treatment on {Y} for the treated group after treatment began",
    "claim_level_max": "L3",
}
for r in es_rows:
    if r["rel_time"] != -1:
        values[f"es_estimate[{r['rel_time']}]"] = r["estimate"]
        values[f"es_se[{r['rel_time']}]"] = r["se"]
        values[f"es_p[{r['rel_time']}]"] = r["p"]
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]
coef_rows = [{"term": nm, "estimate": float(b[j]), "se": float(np.sqrt(V[j, j]))} for j, nm in enumerate(names)]
for r in coef_rows:
    r["term"] = {"d": f"Treated × post ({TREAT})", "post": "Post", "treated": "Treated group"}.get(r["term"], COVARIATES[int(r["term"][1:]) - 1] if r["term"].startswith("x") else r["term"])
tables = [
    {"key": "coefficients", "title": "Difference-in-differences regression" + (f" (fixed effects: {fe})" if fe else ""),
     "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                 {"key": "se", "label": "SE", "type": "number"}],
     "rows": coef_rows},
    {"key": "means", "title": "Group means",
     "columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "pre", "label": "Before", "type": "number"},
                 {"key": "post", "label": "After", "type": "number"}, {"key": "change", "label": "Change", "type": "number"}],
     "rows": [{"group": "Treated", "pre": m.get((1, 0)), "post": m.get((1, 1)), "change": m.get((1, 1), np.nan) - m.get((1, 0), np.nan)},
              {"group": "Comparison", "pre": m.get((0, 0)), "post": m.get((0, 1)), "change": m.get((0, 1), np.nan) - m.get((0, 0), np.nan)}]},
]
if es_rows:
    tables.append({"key": "event_study", "title": "Event study (reference: period −1)",
                   "columns": [{"key": "rel_time", "label": "Period", "type": "integer"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                               {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                               {"key": "high", "label": "Upper", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
                   "rows": es_rows})
cs.publish({
    "method": "causal.did",
    "methodVersion": "1.0.2",
    "title": "Difference-in-differences",
    "engine": cs.engine_info("pandas", "numpy", "pyfixest"),
    "n": n,
    "summary": summary,
    "apa": f"DiD = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, t({df_t:.0f}) = {cs.fmt_num(tstat)}, {cs.fmt_p(p)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}]",
    "statistics": [
        {"key": "estimate", "label": "Difference-in-differences", "value": est},
        {"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
        {"key": "se", "label": "SE", "value": se},
        {"key": "p_value", "label": "p", "value": p, "format": "p"},
    ],
    "tables": tables,
    "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": [f"Design: {design}; standard errors " + (f"clustered by {cluster_col}" if cluster_col else "heteroskedasticity-robust (HC1)") + f"; t with {df_t:.0f} df."],
    "values": values,
    "artifacts": artifacts,
    "charts": charts,
})

The studio's Interpret step works out the level from what you've done, and suggests wording that fits. It updates when a check fails.

04

Words that fit

Read
LevelFitsAvoid
L1"is associated with, after adjusting for""increases"
L2"assuming no unmeasured confounding, the estimated effect is""causes"
L3"under parallel trends, the policy reduced""proves"
L4"the randomized treatment increased""for everyone, always"
05

Check your understanding

Checkpoint

Check yourself

A regression with controls on survey data finds exercise predicts lower blood pressure. Which sentence fits?

Show the answer

Answer: b

Without a causal design, this is an adjusted association: level L1.

Check yourself

Your DiD design can reach L3, but its event study shows clear pre-trends. What happens?

Show the answer

Answer: b

The ceiling isn't a promise. Evidence against the key assumption lowers what you can claim.

06

Reflect

Reflect

Find a causal sentence you've written or read recently. Which rung does the study behind it support? Rewrite the sentence to match, and note what would let you climb one rung.

07

Recap

Recap
  • The design sets the highest claim you can make; passing its checks earns it.
  • Match your verbs to the level.
  • Going up a rung means a better design, not a fancier estimator.

Concepts in this lesson