Skip to content

Difference-in-differences

Compare changes over time between treated and untreated groups, and test what you can of parallel trends.

Applied ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Compute a 2 × 2 difference-in-differences by hand
  • State the parallel trends assumption and why it can't be fully tested
  • Read an event study's leads and lags

Read first

01

Two differences

Read

Treated firms changed after a policy, but so did everything else. Use the untreated group's change as an estimate of what would have happened anyway:

DiD^=(YˉT,post−YˉT,pre)−(YˉC,post−YˉC,pre)\widehat{\text{DiD}} = (\bar Y_{T,\text{post}} - \bar Y_{T,\text{pre}}) - (\bar Y_{C,\text{post}} - \bar Y_{C,\text{pre}})
PrePost
Treated2.244.61
Control1.752.68
02

Compute it

Checkpoint

Check yourself

Using the table, compute the difference-in-differences. Give two decimals.

Show the answer

Answer: 1.439865

Treated changed by 2.37, and control by 0.93. So 2.37 − 0.93 = 1.44.

03

The assumption that matters

Read

Parallel trendsParallel trendsDifference-in-differences assumes treated and control groups would have moved in parallel without treatment.: without treatment, both groups would have changed by the same amount. Levels can differ. Trends can't.

05

Read an event study

In the app

An event studyEvent studyEffects estimated for each period before and after treatment; flat leads support parallel trends. estimates a separate effect for each period, relative to the last one before treatment. Flat leads support parallel trends.

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

DiD = 1.44, SE = 0.15, t(49) = 9.35, p < .001, 95% CI [1.13, 1.75]

Difference-in-differences
1.440
95% CI
[1.131, 1.749]
SE
0.1539
p
< .001

Plots

Effect on log wage 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
0.18670.7240−0.3507−4
−0.00830.5712−0.5879−3
0.32820.9619−0.3055−2
000−1
1.3712.0480.69520
1.1111.8270.39631
1.4762.0270.92542
1.9672.5561.3783
Mean log wage by groupWhere is the series heading, and how uncertain is the forecast?
View data
kindGroupyearlog wage
actualComparison2,0111.500
actualComparison2,0121.517
actualComparison2,0131.919
actualComparison2,0141.738
actualComparison2,0152.080
actualComparison2,0162.195
actualComparison2,0172.568
actualComparison2,0182.851
actualComparison2,0192.722
actualComparison2,0203.067
actualTreated2,0112.172
actualTreated2,0121.922
actualTreated2,0132.262
actualTreated2,0142.418
actualTreated2,0152.431
actualTreated2,0163.918
actualTreated2,0174.032
actualTreated2,0184.678
actualTreated2,0194.925
actualTreated2,0205.501

Assumptions

  • Parallel pre-trends — Leads before treatment are jointly compatible with zero (F = 0.69, p = .562). This supports, but cannot prove, parallel trends after treatment.
  • 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)1.4400.1539

Group means

GroupBeforeAfterChange
Treated2.2414.6112.370
Comparison1.7512.6810.9299

Event study (reference: period −1)

PeriodEstimateSELowerUpperp
−40.18670.2674−0.35070.72400.4884
−3−0.00830.2884−0.58790.57120.9770
−20.32820.3153−0.30550.96190.3031
−10000—
01.3710.33650.69522.0480.0002
11.1110.35580.39631.8270.0030
21.4760.27400.92542.0272.030e-6
31.9670.29321.3782.5561.878e-8
  • 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 7889921d0111f11d
# 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("log wage", "treated", "firm", "year")))
n_input <- nrow(df)
df[["treated"]] <- factor(df[["treated"]], 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("log wage", "treated", "firm", "year")]), , 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("log wage", "treated", "firm", "year"))  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y <- "log wage"
TREAT <- "treated"
POST <- NULL
UNIT <- "firm"
TIME <- "year"
CLUSTER <- NULL
COVARIATES <- c()
TIME_TEMPORAL <- FALSE
conf <- 0.95
event_study <- TRUE
leads <- as.integer(4)
lags <- as.integer(3)

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 <- 2016
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/event-study/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 = 1.44, SE = 0.15, t(49) = 9.35, p < .001, 95% CI [1.13, 1.75]

Difference-in-differences
1.440
95% CI
[1.131, 1.749]
SE
0.1539
p
< .001

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

Assumptions

  • Parallel pre-trends — Leads before treatment are jointly compatible with zero (F = 0.69, p = .562). This supports, but cannot prove, parallel trends after treatment.
  • 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)1.4400.1539

Group means

GroupBeforeAfterChange
Treated2.2414.6112.370
Comparison1.7512.6810.9299

Event study (reference: period −1)

PeriodEstimateSELowerUpperp
−40.18670.2674−0.35070.72400.4884
−3−0.00830.2884−0.58790.57120.9770
−20.32820.3153−0.30550.96190.3031
−10000—
01.3710.33650.69522.0480.0002
11.1110.35580.39631.8270.0030
21.4760.27400.92542.0272.030e-6
31.9670.29321.3782.5561.878e-8
  • 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 7889921d0111f11d
# 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=["log wage", "treated", "firm", "year"])
n_input = len(df)
df["treated"] = pd.Categorical(df["treated"], 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=["log wage", "treated", "firm", "year"])  # listwise deletion over the analysis columns
df["treated"] = df["treated"].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, ["log wage", "treated", "firm", "year"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y = "log wage"
TREAT = "treated"
POST = None
UNIT = "firm"
TIME = "year"
CLUSTER = None
COVARIATES = []
TIME_TEMPORAL = False
conf = 0.95
event_study = True
leads, lags = int(4), int(3)


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 = 2016
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/event-study/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 joint test of the leads gives p = .562, and the estimate is 1.44.

Now a case where it fails. On another outcome the estimate looks huge (3.19), but the pre-trend test gives p < .001. The groups were already diverging, so that number isn't an effect you can trust.

06

Check your understanding

Checkpoint

Check yourself

Treated firms have much higher wages than control firms before the policy. Does that break the design?

Show the answer

Answer: b

Differencing removes stable differences between the groups. It's changes that have to be comparable.

Check yourself

A policy applies to whole states, with firm-level data. How should you compute standard errors?

Show the answer

Answer: b

Outcomes within a state move together over time. Ignoring that makes intervals far too narrow, a problem well known from DiD studies.

07

Try it

In the app

In the Causal studio, start from Policy change over time (difference-in-differences). The Assumptions step checks pre-trends and Interpret adjusts the claim level to match.

Method guide · causal.didDifference-in-differences (2 × 2, two-way fixed effects, event study)Did the outcome change more for the treated group than for the comparison group after treatment began?
08

Recap

Recap
  • DiD subtracts the control group's change from the treated group's.
  • Parallel trends concerns a counterfactual, so it can only be supported, not proved.
  • An event study shows the dynamics, and flat leads are evidence in its favor.

Concepts in this lesson