Skip to content

Panel diagnostics: Pesaran CD, Wooldridge and panel unit roots

Panel errors can move together across units and drift over time, and whole panels can wander without a mean. Learn the tests for each, what their null hypotheses say, and why rejecting one isn't the same as all units behaving well.

Advanced ~15 min12 steps

What runs in CodeSplash

You will be able to

  • Test cross-sectional dependence with Pesaran CD, and serial correlation with Wooldridge
  • Match what you find to a choice of standard errors
  • State the null and alternative of LLC, IPS, Maddala–Wu, Choi, Hadri and CIPS
  • Say what a rejection does and doesn't tell you about each unit

Read first

01

Do units move together?

Read

Firms share a business cycle, and states share a recession. So residuals can correlate across units, and that breaks the usual assumption that units are independent.

The Pesaran CD testPesaran CD testAverages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock. averages the correlation of residuals over all pairs of units:

CD=2TN(N−1)∑i<jρ^ijCD = \sqrt{\frac{2T}{N(N-1)}} \sum_{i<j} \hat\rho_{ij}

On Grunfeld, it gives zz = 4.66, p < .001, from 45 pairs of firms.

02

Can CD miss it?

Predict

Predict first

CD sums signed correlations. Some pairs of firms move together, and others move in opposition. Which do you expect to be larger: the average correlation, or the average absolute correlation?

Average correlation is largerAverage absolute correlation is largerThey're always equal
Reveal

The absolute one. Here the average correlation is 0.155, and the average absolute correlation is 0.439. Positive and negative pairs cancel in CD, so it can miss dependence when signs are mixed.

03

Do errors persist?

Read

A firm's shock this year often carries into next year. Clustering by unit allows for that, but classical errors don't. The Wooldridge testWooldridge test for serial correlationTests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit. regresses residuals on their previous value, and tests the slope.

There's a subtlety: demeaning creates a small negative correlation by itself, so the slope is compared with −1/(T−1)-1/(T-1). In first differences, it's compared with −0.5-0.5.

On Grunfeld, the correlation among residuals is 0.666, and FF = 68.9, p < .001.

04

Which errors fit?

Checkpoint
What you foundStandard errorsNeeds
Serial correlation onlyCluster by unitMany units
Common shocks onlyCluster by time, or two-wayMany periods
BothTwo-way, or Driscoll–KraayMany periods for Driscoll–Kraay

Check yourself

Your panel has 48 states and 17 years. Pesaran CD and Wooldridge both reject. Which fits best?

Show the answer

Answer: c

Clustering by state handles serial correlation but not common shocks. Two-way clustering and Driscoll–Kraay allow for both, and Driscoll–Kraay works best with about 20 or more periods.

Panel data modelRecorded · Python and R agreeRecorded 2026-11-17 · 86 values compared · largest relative difference 1.8e-10
R

b = −0.030, SE = 0.046, t(16) = -0.66, p = .520, 95% CI [-0.127, 0.067]

Coefficient of log_pcap
−0.0302
95% CI
[−0.1274, 0.0670]
p
.520
Units
48
Periods
17
Share of variance between units
0.8246

Assumptions

  • Fixed or random effects — Hausman p = .017, Mundlak (cluster-robust) p = .007; the Hausman difference matrix is not positive definite, so trust the Mundlak row: unit differences are related to the regressors, which is why fixed effects are needed.
  • One slope for all units — Poolability test p < .001: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.
  • Treatment changes within units — Only 1.3% of the variation in log_pcap is within units; the estimate rests on little change and is noisy.
  • No feedback to later treatment — Next period's log_pcap does not predict today's outcome (p = .109): compatible with strict exogeneity.
  • Errors across units — Pesaran CD p < .001, mean |ρ| 0.44: errors move together across units; the chosen standard errors allow for it.
  • Errors over time — Wooldridge test p < .001: errors are correlated over time; the chosen standard errors allow for it.
  • Enough periods — Only 17 periods: Driscoll–Kraay tests reject too often on short panels, about 12% at 10 periods, 9% at 20 and 8% at 40 at the 5% level in simulations with no effect. Aim for 50 or more.

Two-way fixed effects, Driscoll–Kraay standard errors

TermEstimateSEtpLowHigh
log_pcap−0.03020.0459−0.65800.5199−0.12740.0670
log_pc0.16880.07322.3060.03490.01360.3241
log_emp0.76930.071210.8059.255e-90.61840.9202
unemp−0.00420.0021−2.0020.0626−0.00870.0002

The coefficient of log_pcap under each model

ModelEstimateSELowHighp
Fixed effects (within)−0.02610.0594−0.15210.09980.6658
Two-way fixed effects−0.03020.0459−0.12740.06700.5199
Random effects (Swamy–Arora)0.00440.0857−0.17720.18610.9593
First differences−0.00660.1470−0.31990.30670.9648
Pooled OLS0.15500.03820.07400.23600.0009
Between (unit means)0.17940.07200.03420.32450.0166

Specification tests

TestStatisticdfpA small p suggests
Hausman10.13230.0175Random effects are biased: unit differences relate to the regressors
Mundlak (cluster-robust)4.0624, 470.0066The same question as Hausman, robust to clustering
Breusch–Pagan LM, unit effects4134.9610Unit effects exist (random effects rather than pooled)
Honda, unit effects64.3040The same, one-sided: a variance can't be negative
King–Wu, unit and period effects34.2541.886e-257Unit or period effects, one-sided
F test, unit effects75.82047, 7641.164e-253Fixed effects fit better than pooled OLS
F test, period effects12.31916, 7484.117e-29Two-way fixed effects fit better than one-way
Poolability of slopes7.250188, 5764.388e-76Slopes differ across units
Pesaran CD30.3691.432e-202Errors move together across units
Breusch–Pagan LM, cross-section5079.2911280The same, for few units and many periods
Wooldridge, fixed effects680.301, 471.323e-29Errors are correlated over time
Wooldridge, first differences92.8981, 471.037e-12The same, on differenced errors
Lead of the treatment−1.6340.1090Outcomes feed into later treatment
  • Standard errors Driscoll–Kraay (lag 2); t statistics use 16 degrees of freedom.
The exact R script · R R version 4.5.1 (2025-06-13)
# Panel data models (fixed effects, random effects, first differences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.panel 1.0.4 · spec c8a59bf4dd6feb97
# Dataset: panel_produc (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/panel_produc.parquet", col_select = c("log_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp")))
n_input <- nrow(df)
df[["state"]] <- factor(df[["state"]], levels = c("ALABAMA", "ARIZONA", "ARKANSAS", "CALIFORNIA", "COLORADO", "CONNECTICUT", "DELAWARE", "FLORIDA", "GEORGIA", "IDAHO", "ILLINOIS", "INDIANA", "IOWA", "KANSAS", "KENTUCKY", "LOUISIANA", "MAINE", "MARYLAND", "MASSACHUSETTS", "MICHIGAN", "MINNESOTA", "MISSISSIPPI", "MISSOURI", "MONTANA", "NEBRASKA", "NEVADA", "NEW_HAMPSHIRE", "NEW_JERSEY", "NEW_MEXICO", "NEW_YORK", "NORTH_CAROLINA", "NORTH_DAKOTA", "OHIO", "OKLAHOMA", "OREGON", "PENNSYLVANIA", "RHODE_ISLAND", "SOUTH_CAROLINA", "SOUTH_DAKOTA", "TENNESSE", "TEXAS", "UTAH", "VERMONT", "VIRGINIA", "WASHINGTON", "WEST_VIRGINIA", "WISCONSIN", "WYOMING"))  # stored level order
df <- df[stats::complete.cases(df[c("log_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp")]), , 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_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp"))  # infinite values stop the run (registry/errors.yaml)

# %% Panel: rows sorted by unit and time, with integer ids
Y <- "log_gsp"
TREAT <- "log_pcap"
UNIT <- "state"
TIME <- "year"
COVARIATES <- c("log_pc", "log_emp", "unemp")
UNIT_NUMERIC <- FALSE
TEMPORAL <- FALSE
MODEL <- "twfe"
SE <- "driscoll_kraay"
LAG <- NULL
conf <- 0.95

# A numeric column as is; a two-level column as 0/1 (1 = the chosen level).
as_number <- function(col, chosen = NULL) {
  s <- df[[col]]
  if (is.factor(s)) {
    levels_s <- levels(s)
    level <- if (!is.null(chosen)) chosen else if ("true" %in% levels_s) "true" else levels_s[length(levels_s)]
    return(list(values = as.numeric(as.character(s) == level), level = level))
  }
  list(values = as.numeric(s), level = NULL)
}

if (is.factor(df[[TREAT]]) && nlevels(df[[TREAT]]) != 2L) stop(sprintf("%s has %d levels. A treatment must be numeric or have exactly two levels.", TREAT, nlevels(df[[TREAT]])))
tr <- as_number(TREAT, NULL)
treated_level <- tr$level
X <- do.call(cbind, c(list(tr$values), lapply(COVARIATES, function(c) as_number(c)$values)))
names_x <- c(TREAT, COVARIATES)
y <- as.numeric(df[[Y]])
unit_raw <- if (UNIT_NUMERIC) as.numeric(df[[UNIT]]) else as.character(df[[UNIT]])
unit_values <- sort(unique(unit_raw), method = "radix")
uid <- match(unit_raw, unit_values)
time_raw <- if (TEMPORAL) as.numeric(as.Date(df[[TIME]])) else as.numeric(df[[TIME]])
time_values <- sort(unique(time_raw))
tid <- match(time_raw, time_values)
N <- length(unit_values); T_ <- length(time_values)
if (N < 2L) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = N)
if (T_ < 2L) cs_error("CS_E_TOO_FEW_GROUPS", column = TIME, min = 2, k = T_)
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
ord <- order(uid, tid)
y <- y[ord]; X <- X[ord, , drop = FALSE]; uid <- uid[ord]; tid <- tid[ord]
if (any(uid[-1L] == uid[-length(uid)] & tid[-1L] == tid[-length(tid)])) stop(sprintf("Each unit must have one row per period; %s and %s repeat. Aggregate first.", UNIT, TIME))
unit_labels <- if (UNIT_NUMERIC) vapply(unit_values, function(v) if (v == round(v)) sprintf("%d", as.integer(v)) else as.character(v), "") else unit_values

# %% Which regressors change within units
within <- codesplashr:::.cs_pn_demean(X, uid, N)
sizes <- sqrt(colSums(X * X))
varying <- codesplashr:::.cs_pn_independent(within, sizes)$keep
total_ss <- sum((X[, 1L] - mean(X[, 1L]))^2)
if (total_ss == 0) cs_error("CS_E_CONSTANT", column = TREAT)
within_share <- sum(within[, 1L]^2) / total_ss
absorbing <- MODEL %in% c("fe", "twfe", "fd")
if (absorbing && !(1L %in% varying)) stop(sprintf("%s does not change within units, so this model removes it. Choose random effects or between, or a design for a treatment fixed at the unit level.", TREAT))

# %% Fit
fit <- cs_panel_fit(MODEL, y, X, uid, tid, names_x, SE, LAG)
if (!(TREAT %in% fit$terms)) stop(sprintf("%s cannot be separated from the fixed effects in this model (it may move only with time).", TREAT))
if (length(fit$dropped)) warnings <- c(warnings, paste0("Removed by the model (constant within units or collinear): ", paste(fit$dropped, collapse = ", "), "."))
coefs <- cs_panel_coef_table(fit, conf)
main <- coefs[coefs$term == TREAT, ]
est <- main$estimate; se <- main$se; t_stat <- main$t; p_value <- main$p; ci_low <- main$low; ci_high <- main$high

# %% Specification tests (on the regressors that change within units)
Xw <- X[, varying, drop = FALSE]; names_w <- names_x[varying]
diag <- if (length(varying)) cs_panel_diagnostics(y, Xw, uid, tid, names_w) else list(n_units = N, n_periods = T_, balanced = codesplashr:::.cs_pn_balanced(uid, tid))
rho_matrix <- diag$.rho_matrix
diag$.rho_matrix <- NULL
strict <- if (length(varying) && varying[1L] == 1L) cs_panel_strict_exogeneity(y, Xw, uid, tid, 1L) else NULL
if (!is.null(strict)) { diag$strict_exog_estimate <- strict$estimate; diag$strict_exog_t <- strict$t; diag$strict_exog_p <- strict$p }

# %% The same treatment coefficient under every model
MODEL_LABELS <- c(fe = "Fixed effects (within)", twfe = "Two-way fixed effects", re = "Random effects (Swamy–Arora)", fd = "First differences", pooled = "Pooled OLS", between = "Between (unit means)")
SE_LABELS <- c(classical = "classical", cluster_unit = "clustered by unit", cluster_twoway = "clustered by unit and period", driscoll_kraay = "Driscoll–Kraay", newey_west = "Newey–West within unit")
compare_rows <- list()
for (m in names(MODEL_LABELS)) {
  f2 <- if (m == MODEL) fit else tryCatch(cs_panel_fit(m, y, X, uid, tid, names_x, SE, LAG), error = function(e) NULL)
  if (is.null(f2) || !(TREAT %in% f2$terms)) next
  tb <- cs_panel_coef_table(f2, conf)
  r <- tb[tb$term == TREAT, ]
  compare_rows[[length(compare_rows) + 1L]] <- list(model = m, label = unname(MODEL_LABELS[m]), estimate = r$estimate, se = r$se, low = r$low, high = r$high, p = r$p, chosen = m == MODEL)
}

# %% Checks: what the tests say about this model and these standard errors
checks <- list()
add_check <- function(id, label, status, detail, downgrade = NULL, fix = NULL) {
  c_ <- list(id = id, label = label, status = status, detail = detail)
  if (!is.null(downgrade)) c_$downgrade_to <- downgrade
  if (!is.null(fix)) c_$fix <- fix
  checks[[length(checks) + 1L]] <<- c_
}
pct1 <- function(v) sprintf("%.1f%%", 100 * v)

hp <- diag$hausman_p; mp <- diag$mundlak_p
# The Mundlak row decides when there is one: it holds near 5%, while Hausman reaches 8–15% in short panels whose regressors vary little between units.
effects_reject <- if (!is.null(mp)) mp < 0.05 else (!is.null(hp) && hp < 0.05)
if (!is.null(hp) || !is.null(mp)) {
  parts <- character(0)
  if (!is.null(hp)) parts <- c(parts, sprintf("Hausman %s", cs_fmt_p(hp)))
  if (!is.null(mp)) parts <- c(parts, sprintf("Mundlak (cluster-robust) %s", cs_fmt_p(mp)))
  reading <- paste(parts, collapse = ", ")
  if (isFALSE(diag$hausman_full_rank)) reading <- paste0(reading, "; the Hausman difference matrix is not positive definite, so trust the Mundlak row")
  if (isTRUE(diag$hausman_full_rank) && !is.null(hp) && !is.null(mp) && hp < 0.05 && mp >= 0.05) reading <- paste0(reading, "; Hausman runs high in short panels, so trust the Mundlak row")
  use_fe <- list(label = "Use fixed effects", options = list(model = "fe"))
  if (MODEL == "re" && effects_reject) {
    add_check("hausman", "Fixed or random effects", "concern", sprintf("%s: unit differences are related to the regressors, so random effects are biased. Use fixed effects.", reading), "L1", use_fe)
  } else if (MODEL == "re") {
    add_check("hausman", "Fixed or random effects", "pass", sprintf("%s: no sign that unit differences are related to the regressors; random effects are defensible and more precise.", reading))
  } else if (MODEL %in% c("pooled", "between") && effects_reject) {
    add_check("hausman", "Fixed or random effects", "concern", sprintf("%s: unit differences are related to the regressors, so this model is biased. Use fixed effects.", reading), "L1", use_fe)
  } else if (effects_reject) {
    add_check("hausman", "Fixed or random effects", "pass", sprintf("%s: unit differences are related to the regressors, which is why fixed effects are needed.", reading))
  } else {
    add_check("hausman", "Fixed or random effects", "info", sprintf("%s: random effects would also be consistent here and more precise; fixed effects stay safe.", reading))
  }
}
fu <- diag$f_unit_p
if (MODEL == "pooled" && !is.null(fu) && fu < 0.05) add_check("poolability", "Pooling units", "concern", sprintf("The F test of unit effects %s: units differ, so pooled OLS mixes within and between differences. Use fixed effects.", cs_fmt_p(fu)), "L1", list(label = "Use fixed effects", options = list(model = "fe")))
pl <- diag$poolability_p
if (!is.null(pl) && pl < 0.05 && MODEL %in% c("fe", "twfe", "fd", "re")) add_check("poolability", "One slope for all units", "info", sprintf("Poolability test %s: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.", cs_fmt_p(pl)))
if (within_share < 0.05 && absorbing) {
  add_check("within_variation", "Treatment changes within units", "concern", sprintf("Only %s of the variation in %s is within units; the estimate rests on little change and is noisy.", pct1(within_share), TREAT))
} else if (absorbing) {
  add_check("within_variation", "Treatment changes within units", "pass", sprintf("%s of the variation in %s is within units.", pct1(within_share), TREAT))
}
if (!is.null(strict)) {
  if (strict$p < 0.05) {
    add_check("strict_exog", "No feedback to later treatment", "concern", sprintf("Next period's %s predicts today's outcome (%s): outcomes may drive later treatment, which biases fixed effects.", TREAT, cs_fmt_p(strict$p)), "L1")
  } else {
    add_check("strict_exog", "No feedback to later treatment", "pass", sprintf("Next period's %s does not predict today's outcome (%s): compatible with strict exogeneity.", TREAT, cs_fmt_p(strict$p)))
  }
}
cd_p <- diag$cd_p
if (!is.null(cd_p)) {
  robust_cd <- fit$se %in% c("driscoll_kraay", "cluster_twoway")
  long_enough <- T_ >= 20L
  if (cd_p < 0.05 && !robust_cd) {
    fix <- if (long_enough) list(label = "Use Driscoll–Kraay standard errors", options = list(se = "driscoll_kraay")) else list(label = "Cluster by unit and period", options = list(se = "cluster_twoway"))
    add_check("cross_section", "Errors across units", "concern", sprintf("Pesaran CD %s, mean |ρ| %.2f: errors move together across units, so these standard errors are too small. %s.", cs_fmt_p(cd_p), diag$rho_abs_mean, fix$label), NULL, fix)
  } else if (cd_p < 0.05) {
    add_check("cross_section", "Errors across units", "pass", sprintf("Pesaran CD %s, mean |ρ| %.2f: errors move together across units; the chosen standard errors allow for it.", cs_fmt_p(cd_p), diag$rho_abs_mean))
  } else {
    add_check("cross_section", "Errors across units", "pass", sprintf("Pesaran CD %s: no sign that errors move together across units.", cs_fmt_p(cd_p)))
  }
}
wp <- diag$wooldridge_p
if (!is.null(wp)) {
  if (wp < 0.05 && fit$se == "classical") {
    add_check("serial_correlation", "Errors over time", "concern", sprintf("Wooldridge test %s: errors are correlated over time, so classical standard errors are too small. Cluster by unit.", cs_fmt_p(wp)), NULL, list(label = "Cluster by unit", options = list(se = "cluster_unit")))
  } else if (wp < 0.05) {
    add_check("serial_correlation", "Errors over time", "pass", sprintf("Wooldridge test %s: errors are correlated over time; the chosen standard errors allow for it.", cs_fmt_p(wp)))
  } else {
    add_check("serial_correlation", "Errors over time", "pass", sprintf("Wooldridge test %s: no sign of serial correlation in the errors.", cs_fmt_p(wp)))
  }
}
if (fit$se %in% c("cluster_unit", "cluster_twoway") && N < 30L) add_check("clusters", "Enough clusters", "concern", sprintf("Only %d units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.", N))
if (fit$se == "driscoll_kraay" && T_ < 50L) add_check("clusters", "Enough periods", "concern", sprintf("Only %d periods: Driscoll–Kraay tests reject too often on short panels, about 12%% at 10 periods, 9%% at 20 and 8%% at 40 at the 5%% level in simulations with no effect. Aim for 50 or more.", T_))
if (isTRUE(diag$re_negative_variance) && MODEL == "re") add_check("re_variance", "Random effects variance", "info", "The estimated unit variance came out negative, so it was set to 0 and random effects equal pooled OLS.")

# %% Result
level_note <- if (!is.null(treated_level)) sprintf(" being %s", treated_level) else ""
MODEL_LABEL <- unname(MODEL_LABELS[MODEL])
n <- length(y)
claim <- c(fe = "L2", twfe = "L2", fd = "L2", re = "L2", pooled = "L1", between = "L1")[[MODEL]]
keys <- c("sigma_e", "sigma_u", "rho_icc", "theta_mean", "re_negative_variance", "hausman_stat", "hausman_df", "hausman_p", "hausman_full_rank", "mundlak_f", "mundlak_df1", "mundlak_df2", "mundlak_p",
          "bp_lm_stat", "bp_lm_p", "honda_z", "honda_p", "bp_time_stat", "bp_time_p", "bp_twoway_stat", "bp_twoway_p", "honda_twoway_z", "honda_twoway_p", "king_wu_z", "king_wu_p",
          "f_unit_stat", "f_unit_df1", "f_unit_df2", "f_unit_p", "f_time_stat", "f_time_df1", "f_time_df2", "f_time_p", "poolability_stat", "poolability_df1", "poolability_df2", "poolability_p",
          "cd_stat", "cd_p", "cd_lm_stat", "cd_lm_df", "cd_lm_p", "cd_sclm_stat", "cd_sclm_p", "cd_pairs", "rho_mean", "rho_abs_mean",
          "wooldridge_stat", "wooldridge_df1", "wooldridge_df2", "wooldridge_p", "wooldridge_rho", "wooldridge_fd_stat", "wooldridge_fd_df2", "wooldridge_fd_p", "wooldridge_fd_rho",
          "strict_exog_estimate", "strict_exog_t", "strict_exog_p")
values <- list(
  estimate = est, se = se, t = t_stat, p_value = p_value, ci_low = ci_low, ci_high = ci_high, df_t = fit$df_t, n = n, n_units = N, n_periods = T_,
  balanced = isTRUE(diag$balanced), model = MODEL, model_label = tolower(MODEL_LABEL), se_type = fit$se, lag = fit$lag, r2 = fit$r2, within_share = within_share
)
for (k in keys) values[k] <- list(diag[[k]])
values$estimand <- if (absorbing) "Average within-unit effect" else if (MODEL == "re") "Average effect, assuming unit differences are unrelated to treatment" else "Association across units"
values$effect_label <- sprintf("Change in %s per unit of %s%s", Y, TREAT, level_note)
values$claim_level_max <- claim
for (c_ in checks) values[[sprintf("check[%s]", c_$id)]] <- c_$status

diag_rows <- list()
add_row <- function(key, test, stat, dof, p, looks_for) {
  if (!is.null(stat)) diag_rows[[length(diag_rows) + 1L]] <<- list(test = test, statistic = stat, df = dof, p = if (is.null(p)) NA_real_ else p, looks_for = looks_for)
}
dof2 <- function(a, b) if (!is.null(diag[[a]])) sprintf("%d, %d", as.integer(diag[[a]]), as.integer(diag[[b]])) else ""
add_row("hausman", "Hausman", diag$hausman_stat, if (!is.null(diag$hausman_df)) sprintf("%d", as.integer(diag$hausman_df)) else "", hp, "Random effects are biased: unit differences relate to the regressors")
add_row("mundlak", "Mundlak (cluster-robust)", diag$mundlak_f, dof2("mundlak_df1", "mundlak_df2"), mp, "The same question as Hausman, robust to clustering")
add_row("bp_lm", "Breusch–Pagan LM, unit effects", diag$bp_lm_stat, "1", diag$bp_lm_p, "Unit effects exist (random effects rather than pooled)")
add_row("honda", "Honda, unit effects", diag$honda_z, "", diag$honda_p, "The same, one-sided: a variance can't be negative")
add_row("king_wu", "King–Wu, unit and period effects", diag$king_wu_z, "", diag$king_wu_p, "Unit or period effects, one-sided")
add_row("f_unit", "F test, unit effects", diag$f_unit_stat, dof2("f_unit_df1", "f_unit_df2"), fu, "Fixed effects fit better than pooled OLS")
add_row("f_time", "F test, period effects", diag$f_time_stat, dof2("f_time_df1", "f_time_df2"), diag$f_time_p, "Two-way fixed effects fit better than one-way")
add_row("poolability", "Poolability of slopes", diag$poolability_stat, dof2("poolability_df1", "poolability_df2"), pl, "Slopes differ across units")
add_row("cd", "Pesaran CD", diag$cd_stat, "", cd_p, "Errors move together across units")
add_row("cd_lm", "Breusch–Pagan LM, cross-section", diag$cd_lm_stat, if (!is.null(diag$cd_lm_df)) sprintf("%d", as.integer(diag$cd_lm_df)) else "", diag$cd_lm_p, "The same, for few units and many periods")
add_row("wooldridge", "Wooldridge, fixed effects", diag$wooldridge_stat, dof2("wooldridge_df1", "wooldridge_df2"), wp, "Errors are correlated over time")
add_row("wooldridge_fd", "Wooldridge, first differences", diag$wooldridge_fd_stat, if (!is.null(diag$wooldridge_fd_df2)) sprintf("1, %d", as.integer(diag$wooldridge_fd_df2)) else "", diag$wooldridge_fd_p, "The same, on differenced errors")
add_row("strict_exog", "Lead of the treatment", diag$strict_exog_t, "", diag$strict_exog_p, "Outcomes feed into later treatment")

cmp <- function(k) vapply(compare_rows, function(r) r[[k]], if (k %in% c("label", "model")) "" else 0)
charts <- list(cs_chart("compare", "forest", sprintf("Coefficient of %s under each model", TREAT), list(
  label = cs_col("model", cmp("label"), kind = "categorical"),
  estimate = cs_col("estimate", cmp("estimate")),
  low = cs_col("low", cmp("low")),
  high = cs_col("high", cmp("high")),
  group = cs_col("model", ifelse(vapply(compare_rows, function(r) r$chosen, TRUE), "This analysis", "Other models"), kind = "categorical", levels = c("This analysis", "Other models"))
)))

# Within vs between: the slope of the outcome on the treatment alone, three ways.
x0 <- X[, 1L]
one_x <- matrix(x0, ncol = 1L)
slope_of <- function(m) {
  f1 <- cs_panel_fit(m, y, one_x, uid, tid, TREAT, "classical")
  f1$b[match(TREAT, f1$terms)]
}
stride <- max(1L, as.integer(ceiling(n / 2000)))
pick <- seq(1L, n, by = stride)
means_x <- codesplashr:::.cs_pn_group_mean(x0, uid, N)
means_y <- codesplashr:::.cs_pn_group_mean(y, uid, N)
charts[[length(charts) + 1L]] <- cs_chart("within_between", "within-between", sprintf("%s and %s: within and between units", Y, TREAT), list(
  x = cs_col(TREAT, c(x0[pick], means_x)),
  y = cs_col(Y, c(y[pick], means_y)),
  kind = cs_col("kind", c(rep("observation", length(pick)), rep("unit mean", N)), kind = "categorical", levels = c("observation", "unit mean"))
), controls = list(withinSlope = if (1L %in% varying) slope_of("fe") else NULL, betweenSlope = slope_of("between"), pooledSlope = slope_of("pooled"), xMean = mean(x0), yMean = mean(y)))

if (MODEL %in% c("fe", "twfe")) {
  fe_fit <- cs_panel_fit("fe", y, X, uid, tid, names_x, "classical")
  ue <- cs_panel_unit_effects(fe_fit, y, X, uid, names_x)
  keep_units <- sort(order(-abs(ue$effect - ue$mean))[seq_len(min(40L, N))])
  z <- qnorm(0.5 + conf / 2)
  charts[[length(charts) + 1L]] <- cs_chart("unit_effects", "unit-effects", "Unit fixed effects", list(
    label = cs_col(UNIT, unit_labels[keep_units], kind = "categorical"),
    effect = cs_col("effect", ue$effect[keep_units]),
    low = cs_col("low", ue$effect[keep_units] - z * ue$se[keep_units]),
    high = cs_col("high", ue$effect[keep_units] + z * ue$se[keep_units])
  ), controls = list(reference = ue$mean), note = if (N > 40L) sprintf("The 40 units furthest from the mean, of %d.", N) else NULL)
}

if (!is.null(rho_matrix) && N <= 30L) {
  cells <- expand.grid(j = seq_len(N), i = seq_len(N))
  vals_h <- as.numeric(t(rho_matrix))
  vals_h[!is.finite(vals_h)] <- NA
  charts[[length(charts) + 1L]] <- cs_chart("residual_correlation", "matrix-heatmap", "Residual correlations between units", list(
    row = cs_col(UNIT, unit_labels[cells$i], kind = "categorical", levels = unit_labels),
    col = cs_col(UNIT, unit_labels[cells$j], kind = "categorical", levels = unit_labels),
    value = cs_col("correlation", vals_h, kind = "numeric")
  ))
}

se_label <- unname(SE_LABELS[fit$se])
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("With %s and %s standard errors, a one-unit change in %s%s goes with a change of %.3f in %s (%s CI [%.3f, %.3f], %s), across %d units and %d periods.",
                   tolower(MODEL_LABEL), se_label, TREAT, level_note, est, Y, pct, ci_low, ci_high, cs_fmt_p(p_value), N, T_)
concerns <- Filter(function(c_) c_$status == "concern", checks)
if (length(concerns)) summary <- paste(summary, concerns[[1]]$detail)
notes <- list(sprintf("Standard errors %s%s; t statistics use %d degrees of freedom.", se_label, if (!is.null(fit$lag)) sprintf(" (lag %d)", fit$lag) else "", as.integer(fit$df_t)))
if (!isTRUE(diag$balanced)) notes <- c(notes, sprintf("The panel is unbalanced: %d rows of a possible %d.", n, N * T_))
if (MODEL == "between" && SE != "classical") notes <- c(notes, "The between model has one row per unit, so its standard errors are classical.")
status_map <- c(concern = "warn", fail = "fail", pass = "pass", info = "info")
cs_publish(list(
  method = "causal.panel",
  methodVersion = "1.0.4",
  title = "Panel data model",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("b = %s, SE = %s, t(%d) = %.2f, %s, %s CI [%.3f, %.3f]", cs_fmt_num(est, 3), cs_fmt_num(se, 3), as.integer(fit$df_t), t_stat, cs_fmt_p(p_value), pct, ci_low, ci_high),
  statistics = list(
    list(key = "estimate", label = sprintf("Coefficient of %s", TREAT), value = est),
    list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
    list(key = "p_value", label = "p", value = p_value, format = "p"),
    list(key = "n_units", label = "Units", value = N, format = "int"),
    list(key = "n_periods", label = "Periods", value = T_, format = "int"),
    list(key = "rho_icc", label = "Share of variance between units", value = diag$rho_icc)
  ),
  tables = list(
    list(key = "coefficients", title = sprintf("%s, %s standard errors", MODEL_LABEL, se_label),
         columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
                        list(key = "p", label = "p", type = "p"), list(key = "low", label = "Low", type = "number"), list(key = "high", label = "High", type = "number")),
         rows = coefs),
    list(key = "compare", title = sprintf("The coefficient of %s under each model", TREAT),
         columns = list(list(key = "label", label = "Model", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Low", type = "number"),
                        list(key = "high", label = "High", type = "number"), list(key = "p", label = "p", type = "p")),
         rows = data.frame(label = cmp("label"), estimate = cmp("estimate"), se = cmp("se"), low = cmp("low"), high = cmp("high"), p = cmp("p"), stringsAsFactors = FALSE)),
    list(key = "diagnostics", title = "Specification tests",
         columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
                        list(key = "df", label = "df", type = "string"), list(key = "p", label = "p", type = "p"),
                        list(key = "looks_for", label = "A small p suggests", type = "string")),
         rows = do.call(rbind, lapply(diag_rows, as.data.frame, stringsAsFactors = FALSE)))
  ),
  assumptions = lapply(checks, function(c_) list(key = c_$id, label = c_$label, status = unname(status_map[c_$status]), detail = c_$detail)),
  checks = checks,
  warnings = warnings,
  notes = notes,
  values = values,
  charts = charts
))
Python

b = −0.030, SE = 0.046, t(16) = -0.66, p = .520, 95% CI [-0.127, 0.067]

Coefficient of log_pcap
−0.0302
95% CI
[−0.1274, 0.0670]
p
.520
Units
48
Periods
17
Share of variance between units
0.8246

Assumptions

  • Fixed or random effects — Hausman p = .017, Mundlak (cluster-robust) p = .007; the Hausman difference matrix is not positive definite, so trust the Mundlak row: unit differences are related to the regressors, which is why fixed effects are needed.
  • One slope for all units — Poolability test p < .001: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.
  • Treatment changes within units — Only 1.3% of the variation in log_pcap is within units; the estimate rests on little change and is noisy.
  • No feedback to later treatment — Next period's log_pcap does not predict today's outcome (p = .109): compatible with strict exogeneity.
  • Errors across units — Pesaran CD p < .001, mean |ρ| 0.44: errors move together across units; the chosen standard errors allow for it.
  • Errors over time — Wooldridge test p < .001: errors are correlated over time; the chosen standard errors allow for it.
  • Enough periods — Only 17 periods: Driscoll–Kraay tests reject too often on short panels, about 12% at 10 periods, 9% at 20 and 8% at 40 at the 5% level in simulations with no effect. Aim for 50 or more.

Two-way fixed effects, Driscoll–Kraay standard errors

TermEstimateSEtpLowHigh
log_pcap−0.03020.0459−0.65800.5199−0.12740.0670
log_pc0.16880.07322.3060.03490.01360.3241
log_emp0.76930.071210.8059.255e-90.61840.9202
unemp−0.00420.0021−2.0020.0626−0.00870.0002

The coefficient of log_pcap under each model

ModelEstimateSELowHighp
Fixed effects (within)−0.02610.0594−0.15210.09980.6658
Two-way fixed effects−0.03020.0459−0.12740.06700.5199
Random effects (Swamy–Arora)0.00440.0857−0.17720.18610.9593
First differences−0.00660.1470−0.31990.30670.9648
Pooled OLS0.15500.03820.07400.23600.0009
Between (unit means)0.17940.07200.03420.32450.0166

Specification tests

TestStatisticdfpA small p suggests
Hausman10.13230.0175Random effects are biased: unit differences relate to the regressors
Mundlak (cluster-robust)4.0624, 470.0066The same question as Hausman, robust to clustering
Breusch–Pagan LM, unit effects4134.9610Unit effects exist (random effects rather than pooled)
Honda, unit effects64.3040The same, one-sided: a variance can't be negative
King–Wu, unit and period effects34.2541.886e-257Unit or period effects, one-sided
F test, unit effects75.82047, 7641.164e-253Fixed effects fit better than pooled OLS
F test, period effects12.31916, 7484.117e-29Two-way fixed effects fit better than one-way
Poolability of slopes7.250188, 5764.388e-76Slopes differ across units
Pesaran CD30.3691.432e-202Errors move together across units
Breusch–Pagan LM, cross-section5079.2911280The same, for few units and many periods
Wooldridge, fixed effects680.301, 471.323e-29Errors are correlated over time
Wooldridge, first differences92.8981, 471.037e-12The same, on differenced errors
Lead of the treatment−1.6340.1090Outcomes feed into later treatment
  • Standard errors Driscoll–Kraay (lag 2); t statistics use 16 degrees of freedom.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Panel data models (fixed effects, random effects, first differences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.panel 1.0.4 · spec c8a59bf4dd6feb97
# Dataset: panel_produc (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.causal import panel as pn

# %% Data
df = pd.read_parquet("tests/parity/fixtures/panel_produc.parquet", columns=["log_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp"])
n_input = len(df)
df["state"] = pd.Categorical(df["state"], categories=["ALABAMA", "ARIZONA", "ARKANSAS", "CALIFORNIA", "COLORADO", "CONNECTICUT", "DELAWARE", "FLORIDA", "GEORGIA", "IDAHO", "ILLINOIS", "INDIANA", "IOWA", "KANSAS", "KENTUCKY", "LOUISIANA", "MAINE", "MARYLAND", "MASSACHUSETTS", "MICHIGAN", "MINNESOTA", "MISSISSIPPI", "MISSOURI", "MONTANA", "NEBRASKA", "NEVADA", "NEW_HAMPSHIRE", "NEW_JERSEY", "NEW_MEXICO", "NEW_YORK", "NORTH_CAROLINA", "NORTH_DAKOTA", "OHIO", "OKLAHOMA", "OREGON", "PENNSYLVANIA", "RHODE_ISLAND", "SOUTH_CAROLINA", "SOUTH_DAKOTA", "TENNESSE", "TEXAS", "UTAH", "VERMONT", "VIRGINIA", "WASHINGTON", "WEST_VIRGINIA", "WISCONSIN", "WYOMING"])  # stored level order
df = df.dropna(subset=["log_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp"])  # listwise deletion over the analysis columns
df["state"] = df["state"].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_gsp", "log_pcap", "state", "year", "log_pc", "log_emp", "unemp"])  # infinite values stop the run (registry/errors.yaml)

# %% Panel: rows sorted by unit and time, with integer ids
Y, TREAT, UNIT, TIME = "log_gsp", "log_pcap", "state", "year"
COVARIATES = ["log_pc", "log_emp", "unemp"]
UNIT_NUMERIC = False
TEMPORAL = False
MODEL, SE = "twfe", "driscoll_kraay"
LAG = None
conf = 0.95


def as_number(col, chosen=None):
    """A numeric column as is; a two-level column as 0/1 (1 = the chosen level)."""
    s = df[col]
    if isinstance(s.dtype, pd.CategoricalDtype):
        levels = [str(x) for x in s.cat.categories]
        level = chosen if chosen is not None else ("true" if "true" in levels else levels[-1])
        return (s.astype(str) == level).astype(float).to_numpy(), level
    return s.astype(float).to_numpy(), None


if isinstance(df[TREAT].dtype, pd.CategoricalDtype) and len(df[TREAT].cat.categories) != 2:
    raise ValueError(f"{TREAT} has {len(df[TREAT].cat.categories)} levels. A treatment must be numeric or have exactly two levels.")
treatment, treated_level = as_number(TREAT, None)
X = np.column_stack([treatment] + [as_number(c)[0] for c in COVARIATES])
names = [TREAT] + COVARIATES
y = df[Y].astype(float).to_numpy()
unit_values, uid = np.unique(df[UNIT].astype(float).to_numpy() if UNIT_NUMERIC else df[UNIT].astype(str).to_numpy(), return_inverse=True)
time_values, tid = np.unique(pd.to_datetime(df[TIME]).to_numpy() if TEMPORAL else df[TIME].astype(float).to_numpy(), return_inverse=True)
N, T = len(unit_values), len(time_values)
if N < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=N)
if T < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=TIME, min=2, k=T)
if np.unique(y).size < 2:
    cs.cs_error("CS_E_CONSTANT", column=Y)
order = np.lexsort((tid, uid))
y, X, uid, tid = y[order], X[order], uid[order], tid[order]
if np.any((uid[1:] == uid[:-1]) & (tid[1:] == tid[:-1])):
    raise ValueError(f"Each unit must have one row per period; {UNIT} and {TIME} repeat. Aggregate first.")
unit_labels = [str(int(v)) if UNIT_NUMERIC and float(v).is_integer() else str(v) for v in unit_values]

# %% Which regressors change within units
within = pn.demean(X, uid, N)
sizes = np.sqrt(np.sum(X * X, axis=0))
varying, _ = pn.independent(within, sizes)
total_ss = np.sum((X[:, 0] - X[:, 0].mean()) ** 2)
within_share = float(np.sum(within[:, 0] ** 2) / total_ss) if total_ss > 0 else 0.0
if total_ss == 0:
    cs.cs_error("CS_E_CONSTANT", column=TREAT)
absorbing = MODEL in ("fe", "twfe", "fd")
if absorbing and 0 not in varying:
    raise ValueError(f"{TREAT} does not change within units, so this model removes it. Choose random effects or between, or a design for a treatment fixed at the unit level.")

# %% Fit
fit = pn.fit(MODEL, y, X, uid, tid, names, SE, LAG)
if TREAT not in fit["terms"]:
    raise ValueError(f"{TREAT} cannot be separated from the fixed effects in this model (it may move only with time).")
if fit["dropped"]:
    warnings.append("Removed by the model (constant within units or collinear): " + ", ".join(fit["dropped"]) + ".")
coefs = pn.coef_table(fit, conf)
main = next(r for r in coefs if r["term"] == TREAT)
est, se, t_stat, p_value, ci_low, ci_high = main["estimate"], main["se"], main["t"], main["p"], main["low"], main["high"]

# %% Specification tests (on the regressors that change within units)
Xw, names_w = X[:, varying], [names[j] for j in varying]
diag = pn.diagnostics(y, Xw, uid, tid, names_w) if varying else {"n_units": N, "n_periods": T, "balanced": bool(pn.is_balanced(uid, tid))}
rho_matrix = diag.pop("_rho_matrix", None)
strict = pn.strict_exogeneity(y, Xw, uid, tid, 0) if varying and varying[0] == 0 else None
if strict:
    diag["strict_exog_estimate"], diag["strict_exog_t"], diag["strict_exog_p"] = strict["estimate"], strict["t"], strict["p"]

# %% The same treatment coefficient under every model
compare_rows = []
for m in pn.MODELS:
    try:
        f2 = fit if m == MODEL else pn.fit(m, y, X, uid, tid, names, SE, LAG)
    except (ValueError, np.linalg.LinAlgError):
        continue
    if TREAT in f2["terms"]:
        r = next(x for x in pn.coef_table(f2, conf) if x["term"] == TREAT)
        compare_rows.append({"model": m, "label": pn.MODEL_LABEL[m], "estimate": r["estimate"], "se": r["se"], "low": r["low"], "high": r["high"], "p": r["p"], "chosen": m == MODEL})

# %% Checks: what the tests say about this model and these standard errors
checks = []


def add_check(id_, label, status, detail, downgrade=None, fix=None):
    c = {"id": id_, "label": label, "status": status, "detail": detail}
    if downgrade:
        c["downgrade_to"] = downgrade
    if fix:
        c["fix"] = fix
    checks.append(c)


hp, mp = diag.get("hausman_p"), diag.get("mundlak_p")
# The Mundlak row decides when there is one: it holds near 5%, while Hausman reaches 8–15% in short panels whose regressors vary little between units.
effects_reject = mp < 0.05 if mp is not None else (hp is not None and hp < 0.05)
if hp is not None or mp is not None:
    parts = []
    if hp is not None:
        parts.append(f"Hausman {cs.fmt_p(hp)}")
    if mp is not None:
        parts.append(f"Mundlak (cluster-robust) {cs.fmt_p(mp)}")
    reading = ", ".join(parts)
    if not diag.get("hausman_full_rank", True):
        reading += "; the Hausman difference matrix is not positive definite, so trust the Mundlak row"
    elif hp is not None and mp is not None and hp < 0.05 <= mp:
        reading += "; Hausman runs high in short panels, so trust the Mundlak row"
    if MODEL == "re" and effects_reject:
        add_check("hausman", "Fixed or random effects", "concern", f"{reading}: unit differences are related to the regressors, so random effects are biased. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
    elif MODEL == "re":
        add_check("hausman", "Fixed or random effects", "pass", f"{reading}: no sign that unit differences are related to the regressors; random effects are defensible and more precise.")
    elif MODEL in ("pooled", "between") and effects_reject:
        add_check("hausman", "Fixed or random effects", "concern", f"{reading}: unit differences are related to the regressors, so this model is biased. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
    elif effects_reject:
        add_check("hausman", "Fixed or random effects", "pass", f"{reading}: unit differences are related to the regressors, which is why fixed effects are needed.")
    else:
        add_check("hausman", "Fixed or random effects", "info", f"{reading}: random effects would also be consistent here and more precise; fixed effects stay safe.")
fu = diag.get("f_unit_p")
if MODEL == "pooled" and fu is not None and fu < 0.05:
    add_check("poolability", "Pooling units", "concern", f"The F test of unit effects {cs.fmt_p(fu)}: units differ, so pooled OLS mixes within and between differences. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
pl = diag.get("poolability_p")
if pl is not None and pl < 0.05 and MODEL in ("fe", "twfe", "fd", "re"):
    add_check("poolability", "One slope for all units", "info", f"Poolability test {cs.fmt_p(pl)}: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.")
if within_share < 0.05 and absorbing:
    add_check("within_variation", "Treatment changes within units", "concern", f"Only {within_share:.1%} of the variation in {TREAT} is within units; the estimate rests on little change and is noisy.")
elif absorbing:
    add_check("within_variation", "Treatment changes within units", "pass", f"{within_share:.1%} of the variation in {TREAT} is within units.")
if strict:
    if strict["p"] < 0.05:
        add_check("strict_exog", "No feedback to later treatment", "concern", f"Next period's {TREAT} predicts today's outcome ({cs.fmt_p(strict['p'])}): outcomes may drive later treatment, which biases fixed effects.", "L1")
    else:
        add_check("strict_exog", "No feedback to later treatment", "pass", f"Next period's {TREAT} does not predict today's outcome ({cs.fmt_p(strict['p'])}): compatible with strict exogeneity.")
cd_p = diag.get("cd_p")
if cd_p is not None:
    robust_cd = fit["se"] in ("driscoll_kraay", "cluster_twoway")
    long_enough = T >= 20
    if cd_p < 0.05 and not robust_cd:
        fix = {"label": "Use Driscoll–Kraay standard errors", "options": {"se": "driscoll_kraay"}} if long_enough else {"label": "Cluster by unit and period", "options": {"se": "cluster_twoway"}}
        add_check("cross_section", "Errors across units", "concern", f"Pesaran CD {cs.fmt_p(cd_p)}, mean |ρ| {diag['rho_abs_mean']:.2f}: errors move together across units, so these standard errors are too small. {fix['label']}.", None, fix)
    elif cd_p < 0.05:
        add_check("cross_section", "Errors across units", "pass", f"Pesaran CD {cs.fmt_p(cd_p)}, mean |ρ| {diag['rho_abs_mean']:.2f}: errors move together across units; the chosen standard errors allow for it.")
    else:
        add_check("cross_section", "Errors across units", "pass", f"Pesaran CD {cs.fmt_p(cd_p)}: no sign that errors move together across units.")
wp = diag.get("wooldridge_p")
if wp is not None:
    if wp < 0.05 and fit["se"] == "classical":
        add_check("serial_correlation", "Errors over time", "concern", f"Wooldridge test {cs.fmt_p(wp)}: errors are correlated over time, so classical standard errors are too small. Cluster by unit.", None, {"label": "Cluster by unit", "options": {"se": "cluster_unit"}})
    elif wp < 0.05:
        add_check("serial_correlation", "Errors over time", "pass", f"Wooldridge test {cs.fmt_p(wp)}: errors are correlated over time; the chosen standard errors allow for it.")
    else:
        add_check("serial_correlation", "Errors over time", "pass", f"Wooldridge test {cs.fmt_p(wp)}: no sign of serial correlation in the errors.")
if fit["se"] in ("cluster_unit", "cluster_twoway") and N < 30:
    add_check("clusters", "Enough clusters", "concern", f"Only {N} units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.")
if fit["se"] == "driscoll_kraay" and T < 50:
    add_check("clusters", "Enough periods", "concern", f"Only {T} periods: Driscoll–Kraay tests reject too often on short panels, about 12% at 10 periods, 9% at 20 and 8% at 40 at the 5% level in simulations with no effect. Aim for 50 or more.")
if diag.get("re_negative_variance") and MODEL == "re":
    add_check("re_variance", "Random effects variance", "info", "The estimated unit variance came out negative, so it was set to 0 and random effects equal pooled OLS.")

# %% Result
level_note = f" being {treated_level}" if treated_level is not None else ""
MODEL_LABEL = pn.MODEL_LABEL[MODEL]
n = len(y)
claim = {"fe": "L2", "twfe": "L2", "fd": "L2", "re": "L2", "pooled": "L1", "between": "L1"}[MODEL]
keys = ["sigma_e", "sigma_u", "rho_icc", "theta_mean", "re_negative_variance", "hausman_stat", "hausman_df", "hausman_p", "hausman_full_rank", "mundlak_f", "mundlak_df1", "mundlak_df2", "mundlak_p",
        "bp_lm_stat", "bp_lm_p", "honda_z", "honda_p", "bp_time_stat", "bp_time_p", "bp_twoway_stat", "bp_twoway_p", "honda_twoway_z", "honda_twoway_p", "king_wu_z", "king_wu_p",
        "f_unit_stat", "f_unit_df1", "f_unit_df2", "f_unit_p", "f_time_stat", "f_time_df1", "f_time_df2", "f_time_p", "poolability_stat", "poolability_df1", "poolability_df2", "poolability_p",
        "cd_stat", "cd_p", "cd_lm_stat", "cd_lm_df", "cd_lm_p", "cd_sclm_stat", "cd_sclm_p", "cd_pairs", "rho_mean", "rho_abs_mean",
        "wooldridge_stat", "wooldridge_df1", "wooldridge_df2", "wooldridge_p", "wooldridge_rho", "wooldridge_fd_stat", "wooldridge_fd_df2", "wooldridge_fd_p", "wooldridge_fd_rho",
        "strict_exog_estimate", "strict_exog_t", "strict_exog_p"]
values = {
    "estimate": est, "se": se, "t": t_stat, "p_value": p_value, "ci_low": ci_low, "ci_high": ci_high, "df_t": fit["df_t"], "n": n, "n_units": N, "n_periods": T,
    "balanced": bool(diag["balanced"]), "model": MODEL, "model_label": MODEL_LABEL.lower(), "se_type": fit["se"], "lag": fit["lag"], "r2": fit["r2"], "within_share": within_share,
    **{k: diag.get(k) for k in keys},
    "estimand": "Average within-unit effect" if absorbing else ("Average effect, assuming unit differences are unrelated to treatment" if MODEL == "re" else "Association across units"),
    "effect_label": f"Change in {Y} per unit of {TREAT}{level_note}",
    "claim_level_max": claim,
}
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]

diag_rows = []


def add_row(key, test, stat, dof, p, looks_for):
    if stat is not None:
        diag_rows.append({"key": key, "test": test, "statistic": stat, "df": dof, "p": p, "looks_for": looks_for})


def dof2(a, b):
    return f"{int(diag[a])}, {int(diag[b])}" if diag.get(a) is not None else ""


add_row("hausman", "Hausman", diag.get("hausman_stat"), str(int(diag["hausman_df"])) if diag.get("hausman_df") is not None else "", hp, "Random effects are biased: unit differences relate to the regressors")
add_row("mundlak", "Mundlak (cluster-robust)", diag.get("mundlak_f"), dof2("mundlak_df1", "mundlak_df2"), mp, "The same question as Hausman, robust to clustering")
add_row("bp_lm", "Breusch–Pagan LM, unit effects", diag.get("bp_lm_stat"), "1", diag.get("bp_lm_p"), "Unit effects exist (random effects rather than pooled)")
add_row("honda", "Honda, unit effects", diag.get("honda_z"), "", diag.get("honda_p"), "The same, one-sided: a variance can't be negative")
add_row("king_wu", "King–Wu, unit and period effects", diag.get("king_wu_z"), "", diag.get("king_wu_p"), "Unit or period effects, one-sided")
add_row("f_unit", "F test, unit effects", diag.get("f_unit_stat"), dof2("f_unit_df1", "f_unit_df2"), fu, "Fixed effects fit better than pooled OLS")
add_row("f_time", "F test, period effects", diag.get("f_time_stat"), dof2("f_time_df1", "f_time_df2"), diag.get("f_time_p"), "Two-way fixed effects fit better than one-way")
add_row("poolability", "Poolability of slopes", diag.get("poolability_stat"), dof2("poolability_df1", "poolability_df2"), pl, "Slopes differ across units")
add_row("cd", "Pesaran CD", diag.get("cd_stat"), "", cd_p, "Errors move together across units")
add_row("cd_lm", "Breusch–Pagan LM, cross-section", diag.get("cd_lm_stat"), str(int(diag["cd_lm_df"])) if diag.get("cd_lm_df") is not None else "", diag.get("cd_lm_p"), "The same, for few units and many periods")
add_row("wooldridge", "Wooldridge, fixed effects", diag.get("wooldridge_stat"), dof2("wooldridge_df1", "wooldridge_df2"), wp, "Errors are correlated over time")
add_row("wooldridge_fd", "Wooldridge, first differences", diag.get("wooldridge_fd_stat"), f"1, {int(diag['wooldridge_fd_df2'])}" if diag.get("wooldridge_fd_df2") is not None else "", diag.get("wooldridge_fd_p"), "The same, on differenced errors")
add_row("strict_exog", "Lead of the treatment", diag.get("strict_exog_t"), "", diag.get("strict_exog_p"), "Outcomes feed into later treatment")

charts = [cs.chart("compare", "forest", f"Coefficient of {TREAT} under each model", {
    "label": cs.col("model", [r["label"] for r in compare_rows], kind="categorical"),
    "estimate": cs.col("estimate", [r["estimate"] for r in compare_rows]),
    "low": cs.col("low", [r["low"] for r in compare_rows]),
    "high": cs.col("high", [r["high"] for r in compare_rows]),
    "group": cs.col("model", ["This analysis" if r["chosen"] else "Other models" for r in compare_rows], kind="categorical", levels=["This analysis", "Other models"]),
})]

# Within vs between: the slope of the outcome on the treatment alone, three ways.
x0 = X[:, 0]
single = {m: pn.fit(m, y, x0[:, None], uid, tid, [TREAT], "classical") for m in ("pooled", "between") }
if 0 in varying:
    single["fe"] = pn.fit("fe", y, x0[:, None], uid, tid, [TREAT], "classical")
stride = max(1, int(np.ceil(n / 2000)))
means_x, means_y = pn.group_mean(x0, uid, N), pn.group_mean(y, uid, N)
x_points = list(x0[::stride]) + list(means_x)
y_points = list(y[::stride]) + list(means_y)
kinds_points = ["observation"] * len(x0[::stride]) + ["unit mean"] * N
slope = lambda m: float(single[m]["b"][single[m]["terms"].index(TREAT)]) if m in single else None
charts.append(cs.chart("within_between", "within-between", f"{Y} and {TREAT}: within and between units", {
    "x": cs.col(TREAT, x_points),
    "y": cs.col(Y, y_points),
    "kind": cs.col("kind", kinds_points, kind="categorical", levels=["observation", "unit mean"]),
}, controls={"withinSlope": slope("fe"), "betweenSlope": slope("between"), "pooledSlope": slope("pooled"), "xMean": float(x0.mean()), "yMean": float(y.mean())}))

if MODEL in ("fe", "twfe"):
    fe_fit = pn.fit("fe", y, X, uid, tid, names, "classical")
    ue = pn.unit_effects(fe_fit, y, X, uid, names)
    keep_units = np.argsort(-np.abs(ue["effect"] - ue["mean"]), kind="mergesort")[:40]
    keep_units = np.sort(keep_units)
    z = float(pn.stats.norm.ppf(0.5 + conf / 2))
    charts.append(cs.chart("unit_effects", "unit-effects", "Unit fixed effects", {
        "label": cs.col(UNIT, [unit_labels[i] for i in keep_units], kind="categorical"),
        "effect": cs.col("effect", ue["effect"][keep_units]),
        "low": cs.col("low", ue["effect"][keep_units] - z * ue["se"][keep_units]),
        "high": cs.col("high", ue["effect"][keep_units] + z * ue["se"][keep_units]),
    }, controls={"reference": ue["mean"]}, note=f"The 40 units furthest from the mean, of {N}." if N > 40 else None))

if rho_matrix is not None and N <= 30:
    rows_h = [unit_labels[i] for i in range(N) for j in range(N)]
    cols_h = [unit_labels[j] for i in range(N) for j in range(N)]
    vals_h = [None if not np.isfinite(rho_matrix[i, j]) else float(rho_matrix[i, j]) for i in range(N) for j in range(N)]
    charts.append(cs.chart("residual_correlation", "matrix-heatmap", "Residual correlations between units", {
        "row": cs.col(UNIT, rows_h, kind="categorical", levels=unit_labels),
        "col": cs.col(UNIT, cols_h, kind="categorical", levels=unit_labels),
        "value": cs.col("correlation", vals_h, kind="numeric"),
    }))

se_label = pn.SE_LABEL[fit["se"]]
summary = (
    f"With {MODEL_LABEL.lower()} and {se_label} standard errors, a one-unit change in {TREAT}{level_note} goes with a change of {est:.3f} in {Y} "
    f"({conf:.0%} CI [{ci_low:.3f}, {ci_high:.3f}], {cs.fmt_p(p_value)}), across {N} units and {T} periods."
)
concerns = [c for c in checks if c["status"] == "concern"]
if concerns:
    summary += " " + concerns[0]["detail"]
notes = [f"Standard errors {se_label}" + (f" (lag {fit['lag']})" if fit["lag"] is not None else "") + f"; t statistics use {int(fit['df_t'])} degrees of freedom."]
if not diag["balanced"]:
    notes.append(f"The panel is unbalanced: {n} rows of a possible {N * T}.")
if MODEL == "between" and SE != "classical":
    notes.append("The between model has one row per unit, so its standard errors are classical.")
cs.publish({
    "method": "causal.panel",
    "methodVersion": "1.0.4",
    "title": "Panel data model",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"b = {cs.fmt_num(est, 3)}, SE = {cs.fmt_num(se, 3)}, t({int(fit['df_t'])}) = {t_stat:.2f}, {cs.fmt_p(p_value)}, {conf:.0%} CI [{ci_low:.3f}, {ci_high:.3f}]",
    "statistics": [
        {"key": "estimate", "label": f"Coefficient of {TREAT}", "value": est},
        {"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
        {"key": "p_value", "label": "p", "value": p_value, "format": "p"},
        {"key": "n_units", "label": "Units", "value": N, "format": "int"},
        {"key": "n_periods", "label": "Periods", "value": T, "format": "int"},
        {"key": "rho_icc", "label": "Share of variance between units", "value": diag.get("rho_icc")},
    ],
    "tables": [
        {"key": "coefficients", "title": f"{MODEL_LABEL}, {se_label} standard errors",
         "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
                     {"key": "p", "label": "p", "type": "p"}, {"key": "low", "label": "Low", "type": "number"}, {"key": "high", "label": "High", "type": "number"}],
         "rows": coefs},
        {"key": "compare", "title": f"The coefficient of {TREAT} under each model",
         "columns": [{"key": "label", "label": "Model", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Low", "type": "number"},
                     {"key": "high", "label": "High", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": [{k: r[k] for k in ("label", "estimate", "se", "low", "high", "p")} for r in compare_rows]},
        {"key": "diagnostics", "title": "Specification tests",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
                     {"key": "df", "label": "df", "type": "string"}, {"key": "p", "label": "p", "type": "p"},
                     {"key": "looks_for", "label": "A small p suggests", "type": "string"}],
         "rows": [{k: r[k] for k in ("test", "statistic", "df", "p", "looks_for")} for r in diag_rows]},
    ],
    "assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn", "fail": "fail"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
    "checks": checks,
    "warnings": warnings,
    "notes": notes,
    "values": values,
    "charts": charts,
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

05

Now the series themselves

Explore

If an outcome has a unit root, shocks never fade, and it wanders with no mean to return to.

DExplorable · Unit roots and spurious regression

Why do two unrelated trending series look strongly related?

How often does this regression find a "significant" link between independent series?

0.50
How sure?
1.00

φ = 1 is a random walk, which never returns to a mean.

100
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

These two series are independent. With Persistence φ at 1, regression finds a "significant" link far more than 5% of the time. Lower φ, or turn on Regress the differences, and it stops.

Panel unit-root testsPanel unit-root testA unit-root test that pools many short series (countries, stores) to gain the power a single short series lacks. pool the units to gain power over testing one short series at a time.

06

Read the null first

Read

Five of the tests have the same null: every unit has a unit root. They differ in the alternative and in how they combine units.

TestWhat it doesAlternative
Levin–Lin–ChuLevin–Lin–Chu testA panel unit-root test that pools one common root. Its alternative is that all units are stationary with that root.Pools one rootAll stationary, with a common root
Im–Pesaran–ShinIm–Pesaran–Shin testA panel unit-root test that averages each unit's ADF t. Its alternative lets only some units be stationary.Averages unit ADF tt valuesSome units stationary
Maddala–WuMaddala–Wu testCombines units' unit-root p-values as −2 Σ ln p, referred to χ² with 2N df. It handles unbalanced panels.Combines unit p-values: −2∑ln⁡pi-2\sum\ln p_iSome units stationary
ChoiChoi testCombines units' unit-root p-values through the inverse normal. Its Pm form suits many units.Combines p-values through Φ−1(pi)\Phi^{-1}(p_i)Some units stationary
Pesaran CIPSPesaran CIPS testAdds cross-section averages to each unit's ADF regression, so common shocks don't produce false rejections.Adds cross-section averages to each ADFSome units stationary

HadriHadri testPools KPSS across units, with "all units stationary" as its null. It over-rejects when series are autocorrelated. reverses it: its null is that every unit is stationary.

07

What does rejection mean?

Predict

Predict first

A simulated panel has 4 stationary units and 4 random walks. With each unit's own trend and no lags, Choi's test rejects its null. What may you conclude?

All 8 units are stationaryAt least some units are stationaryNo unit is stationary
Reveal

At least some are stationary: ZZ = −4.33, p < .001, and half the units truly have unit roots. With a constant only, IPS on the same series gives p = .072. Look at the unit ADF table on the card, not only the pooled result.

Panel unit-root testsRecorded · Python and R agreeRecorded 2026-11-21 · 9 values compared
R

Im–Pesaran–Shin W_t̄ = -1.46, p = .072

Im–Pesaran–Shin W_t̄
−1.458
p
0.0725
Units
8

Plots

y_mixed by unitHow does the series move over time, and where is an estimated break?
View data
unityeary_mixed
u011,9816.640
u011,9825.576
u011,9833.343
u011,9844.398
u011,9854.602
u011,9865.953
u011,9873.694
u011,9885.993
u011,9895.376
u011,9904.472
u011,9915.255
u011,9927.020
u011,9936.626
u011,9946.489
u011,9956.990
u011,9966.428
u011,9978.473
u011,9986.603
u011,9996.287
u012,0004.507
u012,0014.908
u012,0024.485
u012,0037.569
u012,0047.814
u012,0057.562
u012,0067.882
u012,0077.806
u012,0086.492
u012,0097.177
u012,0105.990
u012,0116.136
u012,0126.259
u012,0135.212
u012,0145.305
u012,0156.431
u012,0165.016
u012,0176.154
u012,0186.156
u012,0197.045
u012,0205.095
u021,9816.617
u021,9826.445
u021,9836.024
u021,9847.787
u021,9857.480
u021,9867.515
u021,9877.025
u021,9886.091
u021,9896.188
u021,9905.754
u021,9915.729
u021,9925.987
u021,9936.922
u021,9945.858
u021,9958.335
u021,9967.975
u021,9976.714
u021,9988.016
u021,9996.086
u022,0005.728

First 60 of 320 rows.

Unit ADF tests

unitPeriodsADF tp (MacKinnon)
u0140−2.603.092
u0240−3.034.032
u0340−3.153.023
u0440−3.710.004
u0540−2.071.256
u0640−1.702.430
u07400.6451.989
u0840−1.023.745
  • Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).
  • Lags 1 per unit; simulated quantities use seed 42 (identical in Python and R).
The exact R script · R R version 4.5.1 (2025-06-13)
# Panel unit-root tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.panel_unitroot 1.2.0 · spec 85e5b903765d03d0
# Dataset: ts_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_panel.parquet", col_select = c("y_mixed", "unit", "year")))
n_input <- nrow(df)
df[["unit"]] <- factor(df[["unit"]], levels = c("u01", "u02", "u03", "u04", "u05", "u06", "u07", "u08"))  # stored level order
df <- df[stats::complete.cases(df[c("y_mixed", "unit", "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("y_mixed", "unit", "year"))  # infinite values stop the run (registry/errors.yaml)

# %% Panel
VALUE <- "y_mixed"
UNIT <- "unit"
TIME <- "year"
TEMPORAL <- FALSE
TEST <- "ips"
DET <- "c"
LAGS <- 1
REPS <- 100
SEED <- 42
df <- df[order(df[[UNIT]], df[[TIME]], method = "radix"), , drop = FALSE]
units <- levels(df[[UNIT]])
panel <- lapply(units, function(u) as.numeric(df[[VALUE]][df[[UNIT]] == u]))
lengths <- vapply(panel, length, integer(1))
need <- LAGS + 6
keep <- which(lengths >= need)
if (length(keep) < length(units)) warnings <- c(warnings, sprintf("%d unit(s) with fewer than %d periods were left out.", length(units) - length(keep), need))
if (!length(keep)) {  # no unit is long enough: name the longest one (registry/errors.yaml; the same in Python)
  longest <- which.max(lengths)
  cs_error("CS_E_SMALL_GROUP", min = need, group = units[longest], n = lengths[longest])
}
units <- units[keep]
panel <- panel[keep]
cs_check_not_constant(unlist(panel), VALUE)
LABELS <- list(ips = "Im–Pesaran–Shin W_t̄", llc = "Levin–Lin–Chu t*", maddala_wu = "Maddala–Wu χ²", choi = "Choi Z",
               hadri = "Hadri Z", cips = "Pesaran CIPS")
values <- list(n_units = length(units), n_periods = min(vapply(panel, length, integer(1))), test = TEST, test_label = LABELS[[TEST]])

# %% Test
if (TEST == "ips") {
  r <- cs_ts_ips(panel, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$tbar <- r$tbar; values$reps <- REPS
} else if (TEST == "llc") {
  r <- cs_ts_llc(panel, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$t_pooled <- r$t_pooled; values$reps <- REPS
} else if (TEST %in% c("maddala_wu", "choi")) {
  r <- cs_ts_fisher_type(panel, DET, LAGS)
  values$mw_stat <- r$mw_stat; values$mw_p <- r$mw_p; values$choi_z <- r$choi_z; values$choi_p <- r$choi_p
  values$choi_pm <- r$choi_pm; values$choi_pm_p <- r$choi_pm_p
  if (TEST == "maddala_wu") { values$stat <- r$mw_stat; values$p <- r$mw_p } else { values$stat <- r$choi_z; values$p <- r$choi_p }
  if (TEST == "choi" && FALSE) values <- c(values, cs_ts_choi_logit(panel, DET, LAGS))  # Choi's inverse-logit L*
} else if (TEST == "hadri") {
  r <- cs_ts_hadri(panel, DET, "unit")
  values$stat <- r$stat; values$p <- r$p; values$lm <- r$lm
} else {
  times <- lapply(units, function(u) df[[TIME]][df[[UNIT]] == u])
  common <- sort(Reduce(intersect, times))
  if (length(common) < max(lengths)) warnings <- c(warnings, sprintf("CIPS needs a balanced panel: %d periods common to every unit were used.", length(common)))
  P <- do.call(rbind, lapply(units, function(u) as.numeric(df[[VALUE]][df[[UNIT]] == u & df[[TIME]] %in% common])))
  r <- cs_ts_cips(P, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$reps <- REPS; values$n_periods <- ncol(P)
}
values$reject <- as.integer(values$p < 0.05)
verdict <- if (TEST == "hadri") {
  if (values$p < 0.05) "stationarity is rejected in at least some units." else "no evidence against stationarity in any unit."
} else {
  if (values$p < 0.05) "the unit-root null is rejected — at least some units are stationary." else "the unit-root null is not rejected."
}
summary <- sprintf("%s across %d units (%d+ periods): %.3f, %s — %s", LABELS[[TEST]], length(units), values$n_periods, values$stat, cs_fmt_p(values$p), verdict)
unit_rows <- lapply(seq_along(units), function(i) {
  a <- cs_ts_adf(panel[[i]], DET, lags = LAGS)
  list(unit = units[i], periods = length(panel[[i]]), adf_t = a$stat, p = a$p)
})
shown <- units[seq_len(min(8, length(units)))]
kind <- if (TEMPORAL) "temporal" else "numeric"
sub <- df[df[[UNIT]] %in% shown, , drop = FALSE]
cs_publish(list(
  method = "ts.panel_unitroot",
  methodVersion = "1.2.0",
  title = "Panel unit-root tests",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = sum(vapply(panel, length, integer(1))),
  summary = summary,
  apa = sprintf("%s = %.2f, %s", LABELS[[TEST]], values$stat, cs_fmt_p(values$p)),
  statistics = list(list(key = "stat", label = LABELS[[TEST]], value = values$stat), list(key = "p", label = "p", value = values$p),
                    list(key = "units", label = "Units", value = length(units))),
  tables = list(list(
    key = "units", title = "Unit ADF tests",
    columns = list(list(key = "unit", label = UNIT, type = "string"), list(key = "periods", label = "Periods", type = "integer"),
                   list(key = "adf_t", label = "ADF t", type = "number"), list(key = "p", label = "p (MacKinnon)", type = "pvalue")),
    rows = unit_rows
  )),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = c(list("Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).",
               if (TEST %in% c("ips", "llc", "cips")) sprintf("Lags %d per unit; simulated quantities use seed %d (identical in Python and R).", LAGS, SEED) else sprintf("Lags %d per unit.", LAGS)),
            if (!is.null(values$choi_l)) list(sprintf("Choi's inverse-logit L* = %.3f on t(%.0f), %s (lower tail, as plm::purtest test = \"logit\").", values$choi_l, values$choi_l_df, cs_fmt_p(values$choi_l_p)))),
  charts = list(cs_chart("series", "series-line", paste0(sprintf("%s by %s", VALUE, UNIT), if (length(units) > 8) " (first 8 units)" else ""), list(
    x = cs_col(TIME, cs_ts_time_labels(sub[[TIME]], TEMPORAL), kind = kind), y = cs_col(VALUE, as.numeric(sub[[VALUE]])),
    group = cs_col(UNIT, as.character(sub[[UNIT]]), kind = "categorical", levels = shown)))),
  values = values
))
Python

Im–Pesaran–Shin W_t̄ = -1.46, p = .072

Im–Pesaran–Shin W_t̄
−1.458
p
0.0725
Units
8

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

Unit ADF tests

unitPeriodsADF tp (MacKinnon)
u0140−2.603.092
u0240−3.034.032
u0340−3.153.023
u0440−3.710.004
u0540−2.071.256
u0640−1.702.430
u07400.6451.989
u0840−1.023.745
  • Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).
  • Lags 1 per unit; simulated quantities use seed 42 (identical in Python and R).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Panel unit-root tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.panel_unitroot 1.2.0 · spec 85e5b903765d03d0
# Dataset: ts_panel (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_panel.parquet", columns=["y_mixed", "unit", "year"])
n_input = len(df)
df["unit"] = pd.Categorical(df["unit"], categories=["u01", "u02", "u03", "u04", "u05", "u06", "u07", "u08"])  # stored level order
df = df.dropna(subset=["y_mixed", "unit", "year"])  # 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_mixed", "unit", "year"])  # infinite values stop the run (registry/errors.yaml)

# %% Panel
VALUE = "y_mixed"
UNIT = "unit"
TIME = "year"
TEMPORAL = False
TEST = "ips"
DET = "c"
LAGS = 1
REPS = 100
SEED = 42
df = df.sort_values([UNIT, TIME], kind="mergesort")
units = [str(u) for u in df[UNIT].cat.categories]
panel = [df.loc[df[UNIT] == u, VALUE].to_numpy(dtype=float) for u in units]
lengths = [len(y) for y in panel]
need = LAGS + 6
keep = [i for i, y in enumerate(panel) if len(y) >= need]
if len(keep) < len(units):
    warnings.append(f"{len(units) - len(keep)} unit(s) with fewer than {need} periods were left out.")
if not keep:  # no unit is long enough: name the longest one (registry/errors.yaml; the same in R)
    longest = int(np.argmax(lengths))
    cs.cs_error("CS_E_SMALL_GROUP", min=need, group=units[longest], n=lengths[longest])
units = [units[i] for i in keep]
panel = [panel[i] for i in keep]
check_not_constant(np.concatenate(panel), VALUE)
LABELS = {"ips": "Im–Pesaran–Shin W_t̄", "llc": "Levin–Lin–Chu t*", "maddala_wu": "Maddala–Wu χ²", "choi": "Choi Z",
          "hadri": "Hadri Z", "cips": "Pesaran CIPS"}
values = {"n_units": len(units), "n_periods": min(len(y) for y in panel), "test": TEST, "test_label": LABELS[TEST]}

# %% Test
if TEST == "ips":
    r = ts.ips(panel, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "tbar": r["tbar"], "reps": REPS})
elif TEST == "llc":
    r = ts.llc(panel, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "t_pooled": r["t_pooled"], "reps": REPS})
elif TEST in ("maddala_wu", "choi"):
    r = ts.fisher_type(panel, DET, LAGS)
    values.update({"mw_stat": r["mw_stat"], "mw_p": r["mw_p"], "choi_z": r["choi_z"], "choi_p": r["choi_p"], "choi_pm": r["choi_pm"], "choi_pm_p": r["choi_pm_p"]})
    values.update({"stat": r["mw_stat"], "p": r["mw_p"]} if TEST == "maddala_wu" else {"stat": r["choi_z"], "p": r["choi_p"]})
    if TEST == "choi" and False:
        from codesplash.stats import panel_logit as pl  # Choi's inverse-logit L* (twin of R's cs_ts_choi_logit)
        values.update(pl.choi_logit(panel, DET, LAGS))
elif TEST == "hadri":
    r = ts.hadri(panel, DET, "unit")
    values.update({"stat": r["stat"], "p": r["p"], "lm": r["lm"]})
else:
    times = [set(df.loc[df[UNIT] == u, TIME].tolist()) for u in units]
    common = sorted(set.intersection(*times))
    if len(common) < max(lengths):
        warnings.append(f"CIPS needs a balanced panel: {len(common)} periods common to every unit were used.")
    P = np.vstack([df.loc[(df[UNIT] == u) & (df[TIME].isin(common)), VALUE].to_numpy(dtype=float) for u in units])
    r = ts.cips(P, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "reps": REPS, "n_periods": P.shape[1]})
values["reject"] = int(values["p"] < 0.05)
if TEST == "hadri":
    verdict = "stationarity is rejected in at least some units." if values["p"] < 0.05 else "no evidence against stationarity in any unit."
else:
    verdict = "the unit-root null is rejected — at least some units are stationary." if values["p"] < 0.05 else "the unit-root null is not rejected."
summary = f"{LABELS[TEST]} across {len(units)} units ({values['n_periods']}+ periods): {values['stat']:.3f}, {cs.fmt_p(values['p'])} — {verdict}"
unit_rows = []
for u, y in zip(units, panel):
    a = ts.adf(y, DET, lags=LAGS)
    unit_rows.append({"unit": u, "periods": len(y), "adf_t": a["stat"], "p": a["p"]})
shown = units[:8]
kind = "temporal" if TEMPORAL else "numeric"
sub = df[df[UNIT].isin(shown)]
cs.publish({
    "method": "ts.panel_unitroot",
    "methodVersion": "1.2.0",
    "title": "Panel unit-root tests",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(sum(len(y) for y in panel)),
    "summary": summary,
    "apa": f"{LABELS[TEST]} = {values['stat']:.2f}, {cs.fmt_p(values['p'])}",
    "statistics": [{"key": "stat", "label": LABELS[TEST], "value": values["stat"]}, {"key": "p", "label": "p", "value": values["p"]},
                   {"key": "units", "label": "Units", "value": len(units)}],
    "tables": [{
        "key": "units", "title": "Unit ADF tests",
        "columns": [{"key": "unit", "label": UNIT, "type": "string"}, {"key": "periods", "label": "Periods", "type": "integer"},
                    {"key": "adf_t", "label": "ADF t", "type": "number"}, {"key": "p", "label": "p (MacKinnon)", "type": "pvalue"}],
        "rows": unit_rows,
    }],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).",
              f"Lags {LAGS} per unit; simulated quantities use seed {SEED} (identical in Python and R)." if TEST in ("ips", "llc", "cips") else f"Lags {LAGS} per unit."]
    + ([f"Choi's inverse-logit L* = {values['choi_l']:.3f} on t({values['choi_l_df']:.0f}), {cs.fmt_p(values['choi_l_p'])} (lower tail, as plm::purtest test = \"logit\")."] if "choi_l" in values else []),
    "charts": [cs.chart("series", "series-line", f"{VALUE} by {UNIT}" + (" (first 8 units)" if len(units) > 8 else ""), {
        "x": cs.col(TIME, ts.time_labels(sub[TIME].to_numpy(), TEMPORAL), kind=kind), "y": cs.col(VALUE, sub[VALUE].to_numpy(dtype=float)),
        "group": cs.col(UNIT, [str(u) for u in sub[UNIT]], kind="categorical", levels=shown)})],
    "values": values,
})
08

Three cases to read

In the app

LLC on stationary series. It rejects, as it should: t∗t^* = −5.13, p < .001.

Maddala–Wu on random walks. It doesn't reject: χ2\chi^2 = 21.6, p = .156. Choi's PmP_m, built for many units, agrees: p = .161.

CIPS on random walks. It doesn't reject either: p = .361. Run CD first: if units share shocks, the others can reject too often, and CIPS is the one built for that.

Panel unit-root testsRecorded · Python and R agreeRecorded 2026-11-21 · 8 values compared
R

Pesaran CIPS = -1.83, p = .361

Pesaran CIPS
−1.825
p
0.3607
Units
8

Plots

y_unit_root by unitHow does the series move over time, and where is an estimated break?
View data
unityeary_unit_root
u011,981−0.7700
u011,982−0.5200
u011,983−1.585
u011,984−1.808
u011,985−1.324
u011,986−2.031
u011,987−1.798
u011,988−2.739
u011,989−2.197
u011,990−3.023
u011,991−2.676
u011,992−1.195
u011,9930.7282
u011,9940.6807
u011,9951.546
u011,9961.162
u011,9971.468
u011,9982.366
u011,9992.398
u012,0001.238
u012,0010.7810
u012,0021.292
u012,0031.418
u012,0042.366
u012,0052.350
u012,0062.110
u012,0071.302
u012,0080.6672
u012,0092.021
u012,0101.188
u012,0112.726
u012,0123.256
u012,0131.991
u012,0141.872
u012,015−0.0214
u012,0160.4322
u012,0171.241
u012,0180.7164
u012,0191.236
u012,0202.772
u021,9810.9999
u021,982−0.1889
u021,983−0.1700
u021,984−0.7531
u021,9850.0364
u021,9860.1146
u021,9870.3761
u021,9880.4027
u021,9890.5972
u021,990−0.1216
u021,991−2.066
u021,992−2.299
u021,993−0.3221
u021,9940.0787
u021,995−2.501
u021,996−3.556
u021,997−3.212
u021,998−3.972
u021,999−3.524
u022,000−4.725

First 60 of 320 rows.

Unit ADF tests

unitPeriodsADF tp (MacKinnon)
u0140−1.336.613
u0240−2.142.228
u0340−1.552.508
u0440−3.663.005
u0540−0.0904.950
u0640−0.5537.881
u0740−1.456.555
u0840−2.436.132
  • Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).
  • Lags 1 per unit; simulated quantities use seed 42 (identical in Python and R).
The exact R script · R R version 4.5.1 (2025-06-13)
# Panel unit-root tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.panel_unitroot 1.2.0 · spec 79d1e6784a6215df
# Dataset: ts_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_panel.parquet", col_select = c("y_unit_root", "unit", "year")))
n_input <- nrow(df)
df[["unit"]] <- factor(df[["unit"]], levels = c("u01", "u02", "u03", "u04", "u05", "u06", "u07", "u08"))  # stored level order
df <- df[stats::complete.cases(df[c("y_unit_root", "unit", "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("y_unit_root", "unit", "year"))  # infinite values stop the run (registry/errors.yaml)

# %% Panel
VALUE <- "y_unit_root"
UNIT <- "unit"
TIME <- "year"
TEMPORAL <- FALSE
TEST <- "cips"
DET <- "c"
LAGS <- 1
REPS <- 60
SEED <- 42
df <- df[order(df[[UNIT]], df[[TIME]], method = "radix"), , drop = FALSE]
units <- levels(df[[UNIT]])
panel <- lapply(units, function(u) as.numeric(df[[VALUE]][df[[UNIT]] == u]))
lengths <- vapply(panel, length, integer(1))
need <- LAGS + 6
keep <- which(lengths >= need)
if (length(keep) < length(units)) warnings <- c(warnings, sprintf("%d unit(s) with fewer than %d periods were left out.", length(units) - length(keep), need))
if (!length(keep)) {  # no unit is long enough: name the longest one (registry/errors.yaml; the same in Python)
  longest <- which.max(lengths)
  cs_error("CS_E_SMALL_GROUP", min = need, group = units[longest], n = lengths[longest])
}
units <- units[keep]
panel <- panel[keep]
cs_check_not_constant(unlist(panel), VALUE)
LABELS <- list(ips = "Im–Pesaran–Shin W_t̄", llc = "Levin–Lin–Chu t*", maddala_wu = "Maddala–Wu χ²", choi = "Choi Z",
               hadri = "Hadri Z", cips = "Pesaran CIPS")
values <- list(n_units = length(units), n_periods = min(vapply(panel, length, integer(1))), test = TEST, test_label = LABELS[[TEST]])

# %% Test
if (TEST == "ips") {
  r <- cs_ts_ips(panel, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$tbar <- r$tbar; values$reps <- REPS
} else if (TEST == "llc") {
  r <- cs_ts_llc(panel, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$t_pooled <- r$t_pooled; values$reps <- REPS
} else if (TEST %in% c("maddala_wu", "choi")) {
  r <- cs_ts_fisher_type(panel, DET, LAGS)
  values$mw_stat <- r$mw_stat; values$mw_p <- r$mw_p; values$choi_z <- r$choi_z; values$choi_p <- r$choi_p
  values$choi_pm <- r$choi_pm; values$choi_pm_p <- r$choi_pm_p
  if (TEST == "maddala_wu") { values$stat <- r$mw_stat; values$p <- r$mw_p } else { values$stat <- r$choi_z; values$p <- r$choi_p }
  if (TEST == "choi" && FALSE) values <- c(values, cs_ts_choi_logit(panel, DET, LAGS))  # Choi's inverse-logit L*
} else if (TEST == "hadri") {
  r <- cs_ts_hadri(panel, DET, "unit")
  values$stat <- r$stat; values$p <- r$p; values$lm <- r$lm
} else {
  times <- lapply(units, function(u) df[[TIME]][df[[UNIT]] == u])
  common <- sort(Reduce(intersect, times))
  if (length(common) < max(lengths)) warnings <- c(warnings, sprintf("CIPS needs a balanced panel: %d periods common to every unit were used.", length(common)))
  P <- do.call(rbind, lapply(units, function(u) as.numeric(df[[VALUE]][df[[UNIT]] == u & df[[TIME]] %in% common])))
  r <- cs_ts_cips(P, DET, LAGS, REPS, SEED)
  values$stat <- r$stat; values$p <- r$p; values$reps <- REPS; values$n_periods <- ncol(P)
}
values$reject <- as.integer(values$p < 0.05)
verdict <- if (TEST == "hadri") {
  if (values$p < 0.05) "stationarity is rejected in at least some units." else "no evidence against stationarity in any unit."
} else {
  if (values$p < 0.05) "the unit-root null is rejected — at least some units are stationary." else "the unit-root null is not rejected."
}
summary <- sprintf("%s across %d units (%d+ periods): %.3f, %s — %s", LABELS[[TEST]], length(units), values$n_periods, values$stat, cs_fmt_p(values$p), verdict)
unit_rows <- lapply(seq_along(units), function(i) {
  a <- cs_ts_adf(panel[[i]], DET, lags = LAGS)
  list(unit = units[i], periods = length(panel[[i]]), adf_t = a$stat, p = a$p)
})
shown <- units[seq_len(min(8, length(units)))]
kind <- if (TEMPORAL) "temporal" else "numeric"
sub <- df[df[[UNIT]] %in% shown, , drop = FALSE]
cs_publish(list(
  method = "ts.panel_unitroot",
  methodVersion = "1.2.0",
  title = "Panel unit-root tests",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = sum(vapply(panel, length, integer(1))),
  summary = summary,
  apa = sprintf("%s = %.2f, %s", LABELS[[TEST]], values$stat, cs_fmt_p(values$p)),
  statistics = list(list(key = "stat", label = LABELS[[TEST]], value = values$stat), list(key = "p", label = "p", value = values$p),
                    list(key = "units", label = "Units", value = length(units))),
  tables = list(list(
    key = "units", title = "Unit ADF tests",
    columns = list(list(key = "unit", label = UNIT, type = "string"), list(key = "periods", label = "Periods", type = "integer"),
                   list(key = "adf_t", label = "ADF t", type = "number"), list(key = "p", label = "p (MacKinnon)", type = "pvalue")),
    rows = unit_rows
  )),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = c(list("Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).",
               if (TEST %in% c("ips", "llc", "cips")) sprintf("Lags %d per unit; simulated quantities use seed %d (identical in Python and R).", LAGS, SEED) else sprintf("Lags %d per unit.", LAGS)),
            if (!is.null(values$choi_l)) list(sprintf("Choi's inverse-logit L* = %.3f on t(%.0f), %s (lower tail, as plm::purtest test = \"logit\").", values$choi_l, values$choi_l_df, cs_fmt_p(values$choi_l_p)))),
  charts = list(cs_chart("series", "series-line", paste0(sprintf("%s by %s", VALUE, UNIT), if (length(units) > 8) " (first 8 units)" else ""), list(
    x = cs_col(TIME, cs_ts_time_labels(sub[[TIME]], TEMPORAL), kind = kind), y = cs_col(VALUE, as.numeric(sub[[VALUE]])),
    group = cs_col(UNIT, as.character(sub[[UNIT]]), kind = "categorical", levels = shown)))),
  values = values
))
Python

Pesaran CIPS = -1.83, p = .361

Pesaran CIPS
−1.825
p
0.3607
Units
8

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

Unit ADF tests

unitPeriodsADF tp (MacKinnon)
u0140−1.336.613
u0240−2.142.228
u0340−1.552.508
u0440−3.663.005
u0540−0.0904.950
u0640−0.5537.881
u0740−1.456.555
u0840−2.436.132
  • Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).
  • Lags 1 per unit; simulated quantities use seed 42 (identical in Python and R).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Panel unit-root tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.panel_unitroot 1.2.0 · spec 79d1e6784a6215df
# Dataset: ts_panel (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_panel.parquet", columns=["y_unit_root", "unit", "year"])
n_input = len(df)
df["unit"] = pd.Categorical(df["unit"], categories=["u01", "u02", "u03", "u04", "u05", "u06", "u07", "u08"])  # stored level order
df = df.dropna(subset=["y_unit_root", "unit", "year"])  # 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_root", "unit", "year"])  # infinite values stop the run (registry/errors.yaml)

# %% Panel
VALUE = "y_unit_root"
UNIT = "unit"
TIME = "year"
TEMPORAL = False
TEST = "cips"
DET = "c"
LAGS = 1
REPS = 60
SEED = 42
df = df.sort_values([UNIT, TIME], kind="mergesort")
units = [str(u) for u in df[UNIT].cat.categories]
panel = [df.loc[df[UNIT] == u, VALUE].to_numpy(dtype=float) for u in units]
lengths = [len(y) for y in panel]
need = LAGS + 6
keep = [i for i, y in enumerate(panel) if len(y) >= need]
if len(keep) < len(units):
    warnings.append(f"{len(units) - len(keep)} unit(s) with fewer than {need} periods were left out.")
if not keep:  # no unit is long enough: name the longest one (registry/errors.yaml; the same in R)
    longest = int(np.argmax(lengths))
    cs.cs_error("CS_E_SMALL_GROUP", min=need, group=units[longest], n=lengths[longest])
units = [units[i] for i in keep]
panel = [panel[i] for i in keep]
check_not_constant(np.concatenate(panel), VALUE)
LABELS = {"ips": "Im–Pesaran–Shin W_t̄", "llc": "Levin–Lin–Chu t*", "maddala_wu": "Maddala–Wu χ²", "choi": "Choi Z",
          "hadri": "Hadri Z", "cips": "Pesaran CIPS"}
values = {"n_units": len(units), "n_periods": min(len(y) for y in panel), "test": TEST, "test_label": LABELS[TEST]}

# %% Test
if TEST == "ips":
    r = ts.ips(panel, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "tbar": r["tbar"], "reps": REPS})
elif TEST == "llc":
    r = ts.llc(panel, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "t_pooled": r["t_pooled"], "reps": REPS})
elif TEST in ("maddala_wu", "choi"):
    r = ts.fisher_type(panel, DET, LAGS)
    values.update({"mw_stat": r["mw_stat"], "mw_p": r["mw_p"], "choi_z": r["choi_z"], "choi_p": r["choi_p"], "choi_pm": r["choi_pm"], "choi_pm_p": r["choi_pm_p"]})
    values.update({"stat": r["mw_stat"], "p": r["mw_p"]} if TEST == "maddala_wu" else {"stat": r["choi_z"], "p": r["choi_p"]})
    if TEST == "choi" and False:
        from codesplash.stats import panel_logit as pl  # Choi's inverse-logit L* (twin of R's cs_ts_choi_logit)
        values.update(pl.choi_logit(panel, DET, LAGS))
elif TEST == "hadri":
    r = ts.hadri(panel, DET, "unit")
    values.update({"stat": r["stat"], "p": r["p"], "lm": r["lm"]})
else:
    times = [set(df.loc[df[UNIT] == u, TIME].tolist()) for u in units]
    common = sorted(set.intersection(*times))
    if len(common) < max(lengths):
        warnings.append(f"CIPS needs a balanced panel: {len(common)} periods common to every unit were used.")
    P = np.vstack([df.loc[(df[UNIT] == u) & (df[TIME].isin(common)), VALUE].to_numpy(dtype=float) for u in units])
    r = ts.cips(P, DET, LAGS, REPS, SEED)
    values.update({"stat": r["stat"], "p": r["p"], "reps": REPS, "n_periods": P.shape[1]})
values["reject"] = int(values["p"] < 0.05)
if TEST == "hadri":
    verdict = "stationarity is rejected in at least some units." if values["p"] < 0.05 else "no evidence against stationarity in any unit."
else:
    verdict = "the unit-root null is rejected — at least some units are stationary." if values["p"] < 0.05 else "the unit-root null is not rejected."
summary = f"{LABELS[TEST]} across {len(units)} units ({values['n_periods']}+ periods): {values['stat']:.3f}, {cs.fmt_p(values['p'])} — {verdict}"
unit_rows = []
for u, y in zip(units, panel):
    a = ts.adf(y, DET, lags=LAGS)
    unit_rows.append({"unit": u, "periods": len(y), "adf_t": a["stat"], "p": a["p"]})
shown = units[:8]
kind = "temporal" if TEMPORAL else "numeric"
sub = df[df[UNIT].isin(shown)]
cs.publish({
    "method": "ts.panel_unitroot",
    "methodVersion": "1.2.0",
    "title": "Panel unit-root tests",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(sum(len(y) for y in panel)),
    "summary": summary,
    "apa": f"{LABELS[TEST]} = {values['stat']:.2f}, {cs.fmt_p(values['p'])}",
    "statistics": [{"key": "stat", "label": LABELS[TEST], "value": values["stat"]}, {"key": "p", "label": "p", "value": values["p"]},
                   {"key": "units", "label": "Units", "value": len(units)}],
    "tables": [{
        "key": "units", "title": "Unit ADF tests",
        "columns": [{"key": "unit", "label": UNIT, "type": "string"}, {"key": "periods", "label": "Periods", "type": "integer"},
                    {"key": "adf_t", "label": "ADF t", "type": "number"}, {"key": "p", "label": "p (MacKinnon)", "type": "pvalue"}],
        "rows": unit_rows,
    }],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Rejecting a panel unit root means at least some units are stationary, not all (except for LLC's common-root alternative).",
              f"Lags {LAGS} per unit; simulated quantities use seed {SEED} (identical in Python and R)." if TEST in ("ips", "llc", "cips") else f"Lags {LAGS} per unit."]
    + ([f"Choi's inverse-logit L* = {values['choi_l']:.3f} on t({values['choi_l_df']:.0f}), {cs.fmt_p(values['choi_l_p'])} (lower tail, as plm::purtest test = \"logit\")."] if "choi_l" in values else []),
    "charts": [cs.chart("series", "series-line", f"{VALUE} by {UNIT}" + (" (first 8 units)" if len(units) > 8 else ""), {
        "x": cs.col(TIME, ts.time_labels(sub[TIME].to_numpy(), TEMPORAL), kind=kind), "y": cs.col(VALUE, sub[VALUE].to_numpy(dtype=float)),
        "group": cs.col(UNIT, [str(u) for u in sub[UNIT]], kind="categorical", levels=shown)})],
    "values": values,
})
09

A warning about Hadri

Predict

Predict first

Hadri's null is that all units are stationary. The series in this panel are simulated as stationary, with moderate autocorrelation. What do you expect?

Doesn't reject, as it shouldRejects, even though it's trueCan't run on these data
Reveal

It rejects: ZZ = 6.74, p < .001. Hadri's test is known to over-reject when series are autocorrelated. Use it alongside a test with the opposite null, and don't lean on it alone.

10

Check your understanding

Checkpoint

Check yourself

Which test has "all units are stationary" as its null?

Show the answer

Answer: c

Hadri is KPSS pooled across units. The other tests here start from a unit root in every unit.

Check yourself

Countries plausibly return to their means at different speeds. Which test's alternative doesn't fit?

Show the answer

Answer: a

LLC pools a single autoregressive root. IPS, Maddala–Wu and Choi allow units to differ, and for only some to be stationary.

Check yourself

Maddala–Wu combines unit p-values as −2∑ln⁡pi-2\sum\ln p_i. With 8 units, how many degrees of freedom does its χ2\chi^2 reference have?

Show the answer

Answer: 16

Each unit adds 2: 2 × 8 = 16. Combining p-values this way also handles unbalanced panels.

Check yourself

Pesaran CD rejects strongly on your panel, and you want a unit-root test. Which is designed for this?

Show the answer

Answer: c

CIPS adds cross-section averages to each unit's regression, which absorb common shocks. First-generation tests assume units are independent.

Check yourself

Wooldridge's test on fixed-effects residuals rejects. What's the most direct response?

Show the answer

Answer: a

Serial correlation makes classical errors too small. Clustering by unit allows any correlation over time within a unit.

11

Run these on your panel

In the app

Panel models report Pesaran CD and Wooldridge on every run, and the Standard errors option offers each remedy. For unit roots, set Value, Unit and Time, then Test, Deterministic terms and ADF lags per unit.

Python
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.tsa.stattools import adfuller

df = pd.read_csv("ts_panel.csv")

# Maddala-Wu by hand: one ADF test per unit, then combine the p-values
p = df.groupby("unit")["y_unit_root"].apply(
    lambda y: adfuller(y, maxlag=1, autolag=None, regression="c")[1])
mw = -2 * np.log(p).sum()
print(f"Maddala-Wu chi2 = {mw:.2f}, p = {stats.chi2.sf(mw, 2 * len(p)):.3f}")
R
library(plm)

panel <- pdata.frame(read.csv("ts_panel.csv"), index = c("unit", "year"))
purtest(y_unit_root ~ 1, data = panel, test = "madwu", lags = 1)
purtest(y_stationary ~ 1, data = panel, test = "levinlin", lags = 1)
purtest(y_mixed ~ 1, data = panel, test = "ips", lags = 1)
purtest(y_stationary ~ 1, data = panel, test = "hadri", exo = "intercept")

grunfeld <- pdata.frame(read.csv("panel_grunfeld.csv"), index = c("firm", "year"))
fe <- plm(inv ~ value + capital, data = grunfeld, model = "within")
pcdtest(fe, test = "cd")  # Pesaran CD
pwartest(fe)              # Wooldridge, fixed-effects residuals

These scripts use their own critical values or simulation draws, so they can differ somewhat from the card. CodeSplash shares one random stream between Python and R for its simulated p-values.

12

Recap

Recap
  • Pesaran CD looks across units, and Wooldridge looks over time. Together they guide your standard errors.
  • Most panel unit-root tests have a unit root everywhere as the null, while Hadri has the reverse.
  • Rejecting says some units are stationary, not all. Read the unit table.
  • First-generation tests assume independent units, so check CD and use CIPS if it rejects.

Concepts in this lesson