Skip to content

Is the relationship stable? Chow, sup-F and CUSUM

Test whether a regression's coefficients changed over time, at a known date or an unknown one, and learn why CUSUM and sup-F can give opposite answers on the same data.

Advanced ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Choose between a known-date Chow test and an unknown-date sup-F
  • Read fluctuation tests such as CUSUM, MOSUM and Nyblom–Hansen, and what each detects
  • Date several breaks with Bai–Perron using BIC

Read first

01

A coefficient can move

Read

You fit y=α+βxy = \alpha + \beta x. It assumes one β\beta across all the data. Price sensitivity before and after a new competitor, or a sensor's calibration before and after a repair, may not share one.

Structural changeStructural changeA change over time in a regression's coefficients — the relationship itself shifts, not just the level of one series. tests ask if the coefficients are stable over time. They work on regressions, including a model with only a mean.

02

A known date

Read

The Chow testChow testAn F test of whether a regression's coefficients differ before and after a date fixed in advance. splits the data at a date you name, in advance, for a reason that isn't in the data. It compares one model with two:

F=(RSS0−RSS1−RSS2)/k(RSS1+RSS2)/(n−2k)F = \frac{(RSS_0 - RSS_1 - RSS_2) / k}{(RSS_1 + RSS_2) / (n - 2k)}

For a simulated stable regression, split after observation 50: F(2, 96) = 0.05, p = .950.

03

An unknown date

Predict

Predict first

You don't know the date, so you compute Chow's F at every candidate, and take the largest. That's the sup-Fsup-F testThe largest Chow F over every candidate break date, with a p-value that accounts for having searched for the worst one. statistic. What do you compare it with?

The same F tableIts own larger critical valueNo test is possible
Reveal

Its own, larger critical value: the maximum of many Fs. On the stable regression, the largest F is 4.75, well below the 5% value of 11.6, with p = 0.58. An ordinary F table would have called that F significant.

04

Fluctuation tests

Read

Instead of searching for a date, these track how residuals or coefficients move through time:

TestWatchesGood at
Recursive CUSUMCUSUM testTracks the running sum of (recursive or OLS) residuals; a stable regression keeps it inside the boundary lines.Running sum of one-step errorsChanges that shift the mean level
OLS-CUSUMRunning sum of OLS residualsSame, with simpler residuals
OLS-MOSUMMOSUM testLike CUSUM but over a moving window, so a change that later reverses (a temporary regime) still shows.Sums in a moving windowTemporary changes
Nyblom–HansenScore path of the parametersGradual drift

On the stable regression, recursive CUSUM gives 0.86, MOSUM 0.98 and Nyblom–Hansen 1.00.

05

When the tests disagree

Predict

Predict first

A simulated series has a clear change in slope, with a regressor that varies around zero. The mean of yy doesn't move. What will the battery show?

All of them rejectsup-F and Nyblom–Hansen reject, and CUSUM misses itNone of them reject
Reveal

sup-F and Nyblom–Hansen reject, at 0.002 and 0.002. Recursive CUSUM has 0.84 and OLS-MOSUM has 0.82. CUSUM tests are weak against changes that don't move the mean of the residuals (Ploberger & Krämer, 1990).

06

Date the breaks

In the app
Structural change in a regressionRecorded · Python and R agreeRecorded 2026-11-17 · 21 values compared
R

BIC chooses 1 break in the regression of yreg: after 2023-09-11. The sup-F test of no break gives p = .001.

Breaks (BIC)
1
p (sup-F)
0.0010

Plots

Chow F at each candidate breakAt which date would a break in the regression be most pronounced, and is the largest F beyond chance?
View data
weekF
1,655,078,400,0008.282
1,655,683,200,0006.382
1,656,288,000,0006.651
1,656,892,800,0005.025
1,657,497,600,0005.288
1,658,102,400,0007.716
1,658,707,200,0007.109
1,659,312,000,0006.746
1,659,916,800,0006.846
1,660,521,600,0007.851
1,661,126,400,0007.941
1,661,731,200,0007.685
1,662,336,000,0007.681
1,662,940,800,0006.863
1,663,545,600,0007.974
1,664,150,400,0008.970
1,664,755,200,0009.344
1,665,360,000,0009.331
1,665,964,800,0009.705
1,666,569,600,00010.045
1,667,174,400,0009.856
1,667,779,200,00010.771
1,668,384,000,00010.579
1,668,988,800,00010.731
1,669,593,600,00015.908
1,670,198,400,00016.108
1,670,803,200,00015.835
1,671,408,000,00013.863
1,672,012,800,00013.172
1,672,617,600,00013.066
1,673,222,400,00015.926
1,673,827,200,00017.460
1,674,432,000,00019.692
1,675,036,800,00020.648
1,675,641,600,00030.153
1,676,246,400,00030.182
1,676,851,200,00032.700
1,677,456,000,00032.677
1,678,060,800,00034.404
1,678,665,600,00034.199
1,679,270,400,00036.524
1,679,875,200,00040.522
1,680,480,000,00040.530
1,681,084,800,00040.756
1,681,689,600,00039.217
1,682,294,400,00038.138
1,682,899,200,00039.063
1,683,504,000,00037.307
1,684,108,800,00042.423
1,684,713,600,00045.645
1,685,318,400,00049.210
1,685,923,200,00051.291
1,686,528,000,00051.103
1,687,132,800,00050.685
1,687,737,600,00057.433
1,688,342,400,00057.465
1,688,947,200,00056.702
1,689,552,000,00061.656
1,690,156,800,00060.399
1,690,761,600,00062.959

First 60 of 113 rows.

yreg with the first estimated breakHow does the series move over time, and where is an estimated break?
View data
weekyreg
1,641,168,000,0001.272
1,641,772,800,0000.1495
1,642,377,600,000−0.5436
1,642,982,400,0001.245
1,643,587,200,0001.198
1,644,192,000,0000.3668
1,644,796,800,0001.463
1,645,401,600,0000.9496
1,646,006,400,0002.419
1,646,611,200,0000.5458
1,647,216,000,0000.3816
1,647,820,800,0000.2477
1,648,425,600,0000.9947
1,649,030,400,0001.092
1,649,635,200,0000.3362
1,650,240,000,0002.182
1,650,844,800,000−0.0930
1,651,449,600,0000.0962
1,652,054,400,0000.6654
1,652,659,200,0000.6069
1,653,264,000,0002.417
1,653,868,800,0001.601
1,654,473,600,0000.3383
1,655,078,400,0000.0119
1,655,683,200,000−1.055
1,656,288,000,0000.4831
1,656,892,800,000−1.327
1,657,497,600,0001.775
1,658,102,400,0000.8089
1,658,707,200,0001.879
1,659,312,000,000−0.6065
1,659,916,800,0000.6200
1,660,521,600,0000.7867
1,661,126,400,0000.1178
1,661,731,200,0001.589
1,662,336,000,0000.8929
1,662,940,800,0002.005
1,663,545,600,0000.6252
1,664,150,400,0003.051
1,664,755,200,0001.460
1,665,360,000,0000.6253
1,665,964,800,0000.5582
1,666,569,600,0000.4215
1,667,174,400,0001.397
1,667,779,200,0001.059
1,668,384,000,0000.1432
1,668,988,800,0000.2465
1,669,593,600,0001.513
1,670,198,400,0000.9304
1,670,803,200,0000.0384
1,671,408,000,0002.833
1,672,012,800,000−0.5545
1,672,617,600,0001.370
1,673,222,400,0001.825
1,673,827,200,0001.040
1,674,432,000,0000.5174
1,675,036,800,0001.118
1,675,641,600,0000.8686
1,676,246,400,0000.7041
1,676,851,200,0002.010

First 60 of 160 rows.

Assumptions

  • Independent errors — Lag-1 autocorrelation of the residuals is -0.00.
  • Constant error variance — Residual variance in the second half is 1.02 × the first half (F test p = 0.937).

Partitions

BreaksDatesRSSBICChosen
0 breaks—129.18435.05
1 breakafter 2023-09-1183.976381.37✓
2 breaksafter 2022-08-22, after 2023-09-1180.657390.14
3 breaksafter 2022-08-22, after 2023-08-28, after 2024-02-1278.709401.46
  • Segment 1 (2022-01-03–2023-09-11): intercept 0.9971, xreg 0.4164.
  • Segment 2 (2023-09-18–2025-01-20): intercept 0.9848, xreg 1.532.
  • Shortest segment 24 observations (trimming 0.15); BIC counts k coefficients per segment, the break dates and the variance.
  • Simulated p-values: 999 samples of normal errors with these predictors held fixed (seed 42; identical in Python and R).
  • sup-F, ave-F and exp-F are on the Wald (χ²) scale: k × the textbook F with k = 2 coefficients, as in strucchange. Divide by 2 for the F scale of the Chow test.
  • Rows are taken in time order; every test compares the regression across time, so the order matters.
The exact R script · R R version 4.5.1 (2025-06-13)
# Structural change in a regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.stability 1.0.3 · spec 7c02258906f953d9
# Dataset: s3_shifts (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/s3_shifts.parquet", col_select = c("yreg", "xreg", "week")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("yreg", "xreg", "week")]), , 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("yreg", "xreg", "week"))  # infinite values stop the run (registry/errors.yaml)

# %% Data in time order
OUTCOME <- "yreg"
PREDICTORS <- c("xreg")
TIME <- "week"
TEMPORAL <- TRUE
TEST <- "bai_perron"
BREAK_AT <- NULL
TRIM <- 0.15
H <- 0.2
MAX_BREAKS <- 3
CALIBRATION <- "auto"
REPS <- 999
SEED <- 42
if (is.null(PREDICTORS)) PREDICTORS <- character(0)
s <- cs_ts_ordered(df, OUTCOME, TIME, TEMPORAL)
d <- s$df
cols <- c(OUTCOME, PREDICTORS)
keep <- stats::complete.cases(d[, cols, drop = FALSE])
if (sum(!keep) > 0) warnings <- c(warnings, sprintf("%d rows with missing values were left out.", sum(!keep)))
d <- d[keep, , drop = FALSE]
y <- as.numeric(d[[OUTCOME]])
X <- matrix(1, nrow = nrow(d), ncol = 1)
for (p in PREDICTORS) X <- cbind(X, as.numeric(d[[p]]))
dimnames(X) <- NULL
n <- nrow(X)
k <- ncol(X)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_len(n)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: rows with the same time keep their file order.", s$dups))
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(n, 3 * k + 4, "A stability test")  # each candidate segment needs more rows than coefficients
for (col in cols) cs_check_not_constant(d[[col]], col)  # one value is no variation
if (qr(X)$rank < k) cs_error("CS_E_COLLINEAR")
LABELS <- list(chow = "Chow F", sup_f = "sup-F", ave_f = "ave-F", exp_f = "exp-F", rec_cusum = "Recursive CUSUM", ols_cusum = "OLS-CUSUM",
               ols_mosum = "OLS-MOSUM", rec_mosum = "Recursive MOSUM", nyblom = "Nyblom–Hansen L", bai_perron = "Bai–Perron")
LOOKS <- list(sup_f = "one shift at an unknown date", ave_f = "a shift anywhere", exp_f = "a shift anywhere", rec_cusum = "an early shift in the intercept",
              ols_cusum = "a shift in the intercept", ols_mosum = "a temporary or reversing change", rec_mosum = "a temporary change",
              nyblom = "gradually drifting coefficients")
lab <- function(i) as.character(labels[[i]])
fmt4 <- function(v) formatC(v, digits = 4, format = "g")

# %% Tests
values <- list(n_obs = n, k = k, test = TEST)
rows <- list()
notes <- list()
charts <- list()
kind <- if (TEMPORAL) "temporal" else "numeric"
if (TEST == "chow") {
  point <- if (!is.null(BREAK_AT)) as.integer(BREAK_AT) else n %/% 2
  if (is.null(BREAK_AT)) warnings <- c(warnings, sprintf("No break position was set: tested after observation %d (the middle). A Chow test needs the date chosen before looking at the data.", point))
  r <- cs_stab_chow(y, X, point)
  values <- c(values, list(stat = r$stat, p = r$p, df1 = r$df1, df2 = r$df2, break_at = point, break_label = lab(point)))
  rows[[1]] <- list(test = "Chow F", looks_for = sprintf("a change after %s", lab(point)), statistic = r$stat, p = r$p)
  label <- LABELS[[TEST]]
  summary <- paste0(sprintf("Chow test for a change after %s in the regression of %s: F(%d, %d) = %.3f, %s — ", lab(point), OUTCOME, r$df1, r$df2, r$stat, cs_fmt_p(r$p)),
                    if (r$p < 0.05) "the coefficients differ before and after." else "no evidence that the coefficients changed.")
  charts[[1]] <- cs_chart("series", "series-line", sprintf("%s with the tested break", OUTCOME),
                          list(x = cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind), y = cs_col(OUTCOME, y)), controls = list(marker = point))
} else {
  run <- cs_stab_run(y, X, TRIM, H, CALIBRATION, REPS, SEED)
  st <- run$stats
  pv <- run$p
  crit <- run$crit
  values$reps <- REPS
  values$sup_at <- run$sup_at
  values$sup_at_label <- lab(run$sup_at)
  if (TEST == "battery") {
    tests <- c("sup_f", "rec_cusum", "ols_cusum", "ols_mosum", "nyblom")
    for (t in tests) {
      values[[paste0(t, "_stat")]] <- st[[t]]
      values[[paste0(t, "_p")]] <- pv[[t]]
      rows[[length(rows) + 1]] <- list(test = LABELS[[t]], looks_for = LOOKS[[t]], statistic = st[[t]], p = pv[[t]])
    }
    values$n_reject <- sum(vapply(tests, function(t) pv[[t]] < 0.05, logical(1)))
    values$stat <- st$sup_f
    values$p <- pv$sup_f
    label <- "Stability battery"
    flagged <- unlist(lapply(tests, function(t) if (pv[[t]] < 0.05) LABELS[[t]]))
    summary <- paste0(sprintf("%d of %d stability tests reject at α = .05 for the regression of %s (%d observations)", values$n_reject, length(tests), OUTCOME, n),
                      if (length(flagged)) paste0(": ", paste(flagged, collapse = ", "), sprintf(". The largest Chow F is after %s.", lab(run$sup_at)))
                      else " — no evidence that the coefficients changed.")
  } else if (TEST == "bai_perron") {
    bp <- cs_stab_breakpoints(y, X, TRIM, MAX_BREAKS)
    values$stat <- as.numeric(bp$m)
    values$p <- pv$sup_f
    values$m <- bp$m
    for (i in seq_along(bp$breaks)) values[[paste0("break_", i)]] <- bp$breaks[i]
    for (row in bp$table) {
      values[[paste0("rss_", row$m)]] <- row$rss
      values[[paste0("bic_", row$m)]] <- row$bic
      dates <- if (length(row$breaks)) paste(vapply(row$breaks, function(b) sprintf("after %s", lab(b)), ""), collapse = ", ") else "—"
      rows[[length(rows) + 1]] <- list(test = sprintf("%d break%s", row$m, if (row$m != 1) "s" else ""), looks_for = dates, statistic = row$rss,
                                       p = NULL, bic = row$bic, chosen = if (row$m == bp$m) "✓" else "")
    }
    label <- LABELS[[TEST]]
    fits <- cs_stab_segment_fits(y, X, bp$breaks)
    names <- c("intercept", PREDICTORS)
    summary <- paste0(sprintf("BIC chooses %d break%s in the regression of %s", bp$m, if (bp$m != 1) "s" else "", OUTCOME),
                      if (length(bp$breaks)) paste0(": after ", paste(vapply(bp$breaks, lab, ""), collapse = ", "), ".") else ".",
                      sprintf(" The sup-F test of no break gives %s.", cs_fmt_p(pv$sup_f)))
    for (i in seq_along(fits)) {
      f <- fits[[i]]
      notes <- c(notes, sprintf("Segment %d (%s–%s): %s.", i, lab(f$start), lab(f$end),
                                paste(vapply(seq_along(names), function(j) sprintf("%s %s", names[j], fmt4(f$beta[j])), ""), collapse = ", ")))
    }
    notes <- c(notes, sprintf("Shortest segment %d observations (trimming %s); BIC counts k coefficients per segment, the break dates and the variance.", bp$h, format(TRIM)))
  } else {
    values$stat <- st[[TEST]]
    values$p <- pv[[TEST]]
    values$crit_5 <- crit[[TEST]]
    rows[[1]] <- list(test = LABELS[[TEST]], looks_for = LOOKS[[TEST]], statistic = st[[TEST]], p = pv[[TEST]])
    label <- LABELS[[TEST]]
    summary <- paste0(sprintf("%s for the regression of %s (%d observations): %.3f, %s — ", label, OUTCOME, n, st[[TEST]], cs_fmt_p(pv[[TEST]])),
                      if (pv[[TEST]] < 0.05) "the coefficients changed." else "no evidence that the coefficients changed.")
    if (TEST %in% c("sup_f", "ave_f", "exp_f")) summary <- paste0(summary, sprintf(" The largest Chow F is after %s.", lab(run$sup_at)))
  }
  # Charts
  split_labels <- vapply(run$splits, lab, "")
  if (!TEMPORAL) split_labels <- labels[run$splits]
  proc <- cs_stab_processes(y, X, H)
  if (TEST %in% c("battery", "sup_f", "ave_f", "exp_f", "bai_perron"))
    charts[[length(charts) + 1]] <- cs_chart("fstats", "fstat-sequence", "Chow F at each candidate break",
                                             list(x = cs_col(if (is.null(TIME)) "index" else TIME, split_labels, kind = kind), y = cs_col("F", run$F)),
                                             controls = list(crit = crit$sup_f))
  fl <- switch(TEST, battery = "rec_cusum", rec_cusum = "rec_cusum", ols_cusum = "ols_cusum", ols_mosum = "ols_mosum", rec_mosum = "rec_mosum", NULL)
  if (!is.null(fl)) {
    pos <- switch(fl, rec_cusum = k:n, ols_cusum = 0:n, ols_mosum = proc$ols_window:n, rec_mosum = (k + proc$rec_window):n)
    charts[[length(charts) + 1]] <- cs_chart("process", "fluctuation-process", sprintf("%s process", LABELS[[fl]]),
                                             list(x = cs_col("observations used", pos), y = cs_col(fl, proc[[fl]])),
                                             controls = list(kind = gsub("_", "-", fl), crit = crit[[fl]]))
  }
  if (TEST %in% c("battery", "nyblom")) {
    j <- if (k > 1) 2 else 1
    rc <- cs_stab_recursive_coef(y, X, j)
    nm <- if (k > 1) PREDICTORS[1] else "intercept"
    charts[[length(charts) + 1]] <- cs_chart("recursive", "recursive-coef", sprintf("Coefficient of %s estimated on the first r rows", nm),
                                             list(x = cs_col(if (is.null(TIME)) "index" else TIME, labels[rc$row], kind = kind), y = cs_col(nm, rc$estimate),
                                                  lower = cs_col("lower", rc$low), upper = cs_col("upper", rc$high)))
  }
  if (TEST == "bai_perron")
    charts[[length(charts) + 1]] <- cs_chart("series", "series-line", sprintf("%s with the first estimated break", OUTCOME),
                                             list(x = cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind), y = cs_col(OUTCOME, y)),
                                             controls = list(marker = if (length(bp$breaks)) bp$breaks[1] else 0))
  mc_tests <- Filter(function(t) TEST %in% c(t, "battery", "bai_perron"), c("sup_f", "ave_f", "exp_f", "ols_mosum", "rec_mosum", "nyblom"))
  if (CALIBRATION == "monte_carlo" || length(mc_tests))
    notes <- c(notes, sprintf("Simulated p-values: %d samples of normal errors with these predictors held fixed (seed %d; identical in Python and R).", REPS, SEED))
}
values$test_label <- label
values$reject <- as.integer(values$p < 0.05)

# %% Assumptions
beta <- solve(crossprod(X), crossprod(X, y))
e <- as.numeric(y - X %*% beta)
rho1 <- sum(e[-1] * e[-n]) / sum(e * e)
values$rho1 <- rho1
crit1 <- 1.959963984540054 / sqrt(n)
half <- n %/% 2
v1 <- sum(e[1:half]^2) / half
v2 <- sum(e[(half + 1):n]^2) / (n - half)
fr <- v2 / v1
p_var <- 2 * min(stats::pf(fr, n - half, half), stats::pf(fr, n - half, half, lower.tail = FALSE))
assumptions <- list(
  list(key = "independence", label = "Independent errors", status = if (abs(rho1) <= crit1) "pass" else "warn",
       detail = paste0(sprintf("Lag-1 autocorrelation of the residuals is %.2f", rho1),
                       if (abs(rho1) <= crit1) "." else sprintf(" (> %.2f): autocorrelated errors make these tests reject too often.", crit1))),
  list(key = "homoscedasticity", label = "Constant error variance", status = if (p_var >= 0.01) "pass" else "warn",
       detail = paste0(sprintf("Residual variance in the second half is %.2f × the first half (F test p = %s)", fr, formatC(p_var, digits = 3, format = "g")),
                       if (p_var >= 0.01) "." else " — a change in variance alone can trigger these tests.")))
if (TEST %in% c("battery", "sup_f", "ave_f", "exp_f", "bai_perron")) {
  notes <- c(notes, sprintf("sup-F, ave-F and exp-F are on the Wald (χ²) scale: k × the textbook F with k = %d coefficients, as in strucchange. Divide by %d for the F scale of the Chow test.", k, k))
}
notes <- c(notes, "Rows are taken in time order; every test compares the regression across time, so the order matters.")
apa_rows <- Filter(function(r) !is.null(r$p), rows)
bp_cols <- list(list(key = "test", label = "Breaks", type = "string"), list(key = "looks_for", label = "Dates", type = "string"),
                list(key = "statistic", label = "RSS", type = "number"), list(key = "bic", label = "BIC", type = "number"),
                list(key = "chosen", label = "Chosen", type = "string"))
test_cols <- list(list(key = "test", label = "Test", type = "string"), list(key = "looks_for", label = "Sensitive to", type = "string"),
                  list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue"))
cs_publish(list(
  method = "regression.stability",
  methodVersion = "1.0.3",
  title = "Structural change in a regression",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = paste(vapply(apa_rows, function(r) sprintf("%s = %.2f, %s", r$test, r$statistic, cs_fmt_p(r$p)), ""), collapse = "; "),
  statistics = list(list(key = "stat", label = if (TEST == "bai_perron") "Breaks (BIC)" else LABELS[[if (TEST == "battery") "sup_f" else TEST]], value = values$stat),
                    list(key = "p", label = if (TEST == "bai_perron") "p (sup-F)" else "p", value = values$p)),
  tables = list(list(key = "tests", title = if (TEST == "bai_perron") "Partitions" else "Stability tests",
                     columns = if (TEST == "bai_perron") bp_cols else test_cols, rows = rows)),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values
))
Python

BIC chooses 1 break in the regression of yreg: after 2023-09-11. The sup-F test of no break gives p = .001.

Breaks (BIC)
1
p (sup-F)
0.0010

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

Assumptions

  • Independent errors — Lag-1 autocorrelation of the residuals is -0.00.
  • Constant error variance — Residual variance in the second half is 1.02 × the first half (F test p = 0.937).

Partitions

BreaksDatesRSSBICChosen
0 breaks—129.18435.05
1 breakafter 2023-09-1183.976381.37✓
2 breaksafter 2022-08-22, after 2023-09-1180.657390.14
3 breaksafter 2022-08-22, after 2023-08-28, after 2024-02-1278.709401.46
  • Segment 1 (2022-01-03–2023-09-11): intercept 0.9971, xreg 0.4164.
  • Segment 2 (2023-09-18–2025-01-20): intercept 0.9848, xreg 1.532.
  • Shortest segment 24 observations (trimming 0.15); BIC counts k coefficients per segment, the break dates and the variance.
  • Simulated p-values: 999 samples of normal errors with these predictors held fixed (seed 42; identical in Python and R).
  • sup-F, ave-F and exp-F are on the Wald (χ²) scale: k × the textbook F with k = 2 coefficients, as in strucchange. Divide by 2 for the F scale of the Chow test.
  • Rows are taken in time order; every test compares the regression across time, so the order matters.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Structural change in a regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.stability 1.0.3 · spec 7c02258906f953d9
# Dataset: s3_shifts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
from scipy import stats as sps

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import stability as sb, ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s3_shifts.parquet", columns=["yreg", "xreg", "week"])
n_input = len(df)
df = df.dropna(subset=["yreg", "xreg", "week"])  # listwise deletion over the analysis columns
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, ["yreg", "xreg", "week"])  # infinite values stop the run (registry/errors.yaml)

# %% Data in time order
OUTCOME = "yreg"
PREDICTORS = ["xreg"]
TIME = "week"
TEMPORAL = True
TEST = "bai_perron"
BREAK_AT = None
TRIM = 0.15
H = 0.2
MAX_BREAKS = 3
CALIBRATION = "auto"
REPS = 999
SEED = 42
s = ts.ordered(df, OUTCOME, TIME, TEMPORAL)
d = s["df"].reset_index(drop=True)
cols = [OUTCOME] + list(PREDICTORS)
keep = d[cols].notna().all(axis=1)
if (~keep).sum():
    warnings.append(f"{int((~keep).sum())} rows with missing values were left out.")
d = d[keep].reset_index(drop=True)
y = d[OUTCOME].to_numpy(dtype=float)
X = np.column_stack([np.ones(len(d))] + [d[p].to_numpy(dtype=float) for p in PREDICTORS])
n, k = X.shape
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, n + 1))
if s["dups"]:
    warnings.append(f"{s['dups']} repeated time values: rows with the same time keep their file order.")
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(n, 3 * k + 4, "A stability test")  # each candidate segment needs more rows than coefficients
for col in cols:
    check_not_constant(d[col], col)  # one value is no variation
if np.linalg.matrix_rank(X) < k:
    cs.cs_error("CS_E_COLLINEAR")
LABELS = {"chow": "Chow F", "sup_f": "sup-F", "ave_f": "ave-F", "exp_f": "exp-F", "rec_cusum": "Recursive CUSUM", "ols_cusum": "OLS-CUSUM",
          "ols_mosum": "OLS-MOSUM", "rec_mosum": "Recursive MOSUM", "nyblom": "Nyblom–Hansen L", "bai_perron": "Bai–Perron"}
LOOKS = {"sup_f": "one shift at an unknown date", "ave_f": "a shift anywhere", "exp_f": "a shift anywhere", "rec_cusum": "an early shift in the intercept",
         "ols_cusum": "a shift in the intercept", "ols_mosum": "a temporary or reversing change", "rec_mosum": "a temporary change",
         "nyblom": "gradually drifting coefficients"}
lab = lambda i: str(labels[i - 1])  # 1-based position → time label

# %% Tests
values = {"n_obs": n, "k": k, "test": TEST}
rows = []
notes = []
charts = []
kind = "temporal" if TEMPORAL else "numeric"
if TEST == "chow":
    point = int(BREAK_AT) if BREAK_AT is not None else n // 2
    if BREAK_AT is None:
        warnings.append(f"No break position was set: tested after observation {point} (the middle). A Chow test needs the date chosen before looking at the data.")
    r = sb.chow(y, X, point)
    values.update({"stat": r["stat"], "p": r["p"], "df1": r["df1"], "df2": r["df2"], "break_at": point, "break_label": lab(point)})
    rows.append({"test": "Chow F", "looks_for": f"a change after {lab(point)}", "statistic": r["stat"], "p": r["p"]})
    label = LABELS[TEST]
    summary = (f"Chow test for a change after {lab(point)} in the regression of {OUTCOME}: F({r['df1']}, {r['df2']}) = {r['stat']:.3f}, "
               f"{cs.fmt_p(r['p'])} — " + ("the coefficients differ before and after." if r["p"] < 0.05 else "no evidence that the coefficients changed."))
    charts.append(cs.chart("series", "series-line", f"{OUTCOME} with the tested break", {"x": cs.col(TIME or "index", labels, kind=kind), "y": cs.col(OUTCOME, y)},
                           controls={"marker": point}))
else:
    run = sb.run(y, X, TRIM, H, CALIBRATION, REPS, SEED)
    st, pv, crit = run["stats"], run["p"], run["crit"]
    values["reps"] = REPS
    values["sup_at"] = run["sup_at"]
    values["sup_at_label"] = lab(run["sup_at"])
    if TEST == "battery":
        tests = ["sup_f", "rec_cusum", "ols_cusum", "ols_mosum", "nyblom"]
        for t in tests:
            values[f"{t}_stat"] = st[t]
            values[f"{t}_p"] = pv[t]
            rows.append({"test": LABELS[t], "looks_for": LOOKS[t], "statistic": st[t], "p": pv[t]})
        values["n_reject"] = sum(1 for t in tests if pv[t] < 0.05)
        values.update({"stat": st["sup_f"], "p": pv["sup_f"]})
        label = "Stability battery"
        flagged = [LABELS[t] for t in tests if pv[t] < 0.05]
        summary = (f"{values['n_reject']} of {len(tests)} stability tests reject at α = .05 for the regression of {OUTCOME} ({n} observations)"
                   + (": " + ", ".join(flagged) + f". The largest Chow F is after {lab(run['sup_at'])}." if flagged else " — no evidence that the coefficients changed."))
    elif TEST == "bai_perron":
        bp = sb.breakpoints(y, X, TRIM, MAX_BREAKS)
        values.update({"stat": float(bp["m"]), "p": pv["sup_f"], "m": bp["m"]})
        for i, b in enumerate(bp["breaks"], start=1):
            values[f"break_{i}"] = b
        for row in bp["table"]:
            values[f"rss_{row['m']}"] = row["rss"]
            values[f"bic_{row['m']}"] = row["bic"]
            rows.append({"test": f"{row['m']} break{'s' if row['m'] != 1 else ''}", "looks_for": ", ".join(f"after {lab(b)}" for b in row["breaks"]) or "—",
                         "statistic": row["rss"], "p": None, "bic": row["bic"], "chosen": "✓" if row["m"] == bp["m"] else ""})
        label = LABELS[TEST]
        fits = sb.segment_fits(y, X, bp["breaks"])
        names = ["intercept"] + list(PREDICTORS)
        summary = (f"BIC chooses {bp['m']} break{'s' if bp['m'] != 1 else ''} in the regression of {OUTCOME}"
                   + (": after " + ", ".join(lab(b) for b in bp["breaks"]) + "." if bp["breaks"] else ".")
                   + f" The sup-F test of no break gives {cs.fmt_p(pv['sup_f'])}.")
        for i, f in enumerate(fits, start=1):
            notes.append(f"Segment {i} ({lab(f['start'])}–{lab(f['end'])}): " + ", ".join(f"{nm} {b:.4g}" for nm, b in zip(names, f["beta"])) + ".")
        notes.append(f"Shortest segment {bp['h']} observations (trimming {TRIM}); BIC counts k coefficients per segment, the break dates and the variance.")
    else:
        values.update({"stat": st[TEST], "p": pv[TEST], "crit_5": crit[TEST]})
        rows.append({"test": LABELS[TEST], "looks_for": LOOKS[TEST], "statistic": st[TEST], "p": pv[TEST]})
        label = LABELS[TEST]
        summary = (f"{label} for the regression of {OUTCOME} ({n} observations): {st[TEST]:.3f}, {cs.fmt_p(pv[TEST])} — "
                   + ("the coefficients changed." if pv[TEST] < 0.05 else "no evidence that the coefficients changed."))
        if TEST in ("sup_f", "ave_f", "exp_f"):
            summary += f" The largest Chow F is after {lab(run['sup_at'])}."
    # Charts
    split_labels = [lab(i) for i in run["splits"]]
    proc = sb.processes(y, X, H)
    if TEST in ("battery", "sup_f", "ave_f", "exp_f", "bai_perron"):
        charts.append(cs.chart("fstats", "fstat-sequence", "Chow F at each candidate break",
                               {"x": cs.col(TIME or "index", split_labels, kind=kind), "y": cs.col("F", run["F"])}, controls={"crit": crit["sup_f"]}))
    fl = {"battery": "rec_cusum", "rec_cusum": "rec_cusum", "ols_cusum": "ols_cusum", "ols_mosum": "ols_mosum", "rec_mosum": "rec_mosum"}.get(TEST)
    if fl:
        if fl == "rec_cusum":
            pos = list(range(k, n + 1))
        elif fl == "ols_cusum":
            pos = list(range(0, n + 1))
        elif fl == "ols_mosum":
            pos = list(range(proc["ols_window"], n + 1))
        else:
            pos = list(range(k + proc["rec_window"], n + 1))
        charts.append(cs.chart("process", "fluctuation-process", f"{LABELS[fl]} process",
                               {"x": cs.col("observations used", pos), "y": cs.col(fl, proc[fl])},
                               controls={"kind": fl.replace("_", "-"), "crit": crit[fl]}))
    if TEST in ("battery", "nyblom"):
        j = 1 if k > 1 else 0
        rc = sb.recursive_coef(y, X, j)
        nm = PREDICTORS[0] if k > 1 else "intercept"
        charts.append(cs.chart("recursive", "recursive-coef", f"Coefficient of {nm} estimated on the first r rows",
                               {"x": cs.col(TIME or "index", [labels[r - 1] for r in rc["row"]], kind=kind), "y": cs.col(nm, rc["estimate"]),
                                "lower": cs.col("lower", rc["low"]), "upper": cs.col("upper", rc["high"])}))
    if TEST == "bai_perron":
        charts.append(cs.chart("series", "series-line", f"{OUTCOME} with the first estimated break", {"x": cs.col(TIME or "index", labels, kind=kind), "y": cs.col(OUTCOME, y)},
                               controls={"marker": bp["breaks"][0] if bp["breaks"] else 0}))
    mc_tests = [t for t in ("sup_f", "ave_f", "exp_f", "ols_mosum", "rec_mosum", "nyblom") if TEST in (t, "battery", "bai_perron")]
    if CALIBRATION == "monte_carlo" or mc_tests:
        notes.append(f"Simulated p-values: {REPS} samples of normal errors with these predictors held fixed (seed {SEED}; identical in Python and R).")
values["test_label"] = label
values["reject"] = int(values["p"] < 0.05)

# %% Assumptions
fit = sb.ols(y, X)
e = fit["resid"]
rho1 = float((e[1:] @ e[:-1]) / (e @ e))
values["rho1"] = rho1
crit1 = 1.959963984540054 / math.sqrt(n)
half = n // 2
v1 = float(e[:half] @ e[:half]) / half
v2 = float(e[half:] @ e[half:]) / (n - half)
fr = v2 / v1
p_var = float(2.0 * min(sps.f.cdf(fr, n - half, half), sps.f.sf(fr, n - half, half)))
assumptions = [
    {"key": "independence", "label": "Independent errors", "status": "pass" if abs(rho1) <= crit1 else "warn",
     "detail": f"Lag-1 autocorrelation of the residuals is {rho1:.2f}" + ("." if abs(rho1) <= crit1 else f" (> {crit1:.2f}): autocorrelated errors make these tests reject too often.")},
    {"key": "homoscedasticity", "label": "Constant error variance", "status": "pass" if p_var >= 0.01 else "warn",
     "detail": f"Residual variance in the second half is {fr:.2f} × the first half (F test p = {p_var:.3g})"
     + ("." if p_var >= 0.01 else " — a change in variance alone can trigger these tests.")},
]
if TEST in ("battery", "sup_f", "ave_f", "exp_f", "bai_perron"):
    notes.append(f"sup-F, ave-F and exp-F are on the Wald (χ²) scale: k × the textbook F with k = {k} coefficients, as in strucchange. Divide by {k} for the F scale of the Chow test.")
notes.append("Rows are taken in time order; every test compares the regression across time, so the order matters.")
cs.publish({
    "method": "regression.stability",
    "methodVersion": "1.0.3",
    "title": "Structural change in a regression",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": "; ".join(f"{r['test']} = {r['statistic']:.2f}, {cs.fmt_p(r['p'])}" for r in rows if r.get("p") is not None),
    "statistics": [{"key": "stat", "label": "Breaks (BIC)" if TEST == "bai_perron" else LABELS["sup_f" if TEST == "battery" else TEST], "value": values["stat"]},
                   {"key": "p", "label": "p (sup-F)" if TEST == "bai_perron" else "p", "value": values["p"]}],
    "tables": [{
        "key": "tests", "title": "Partitions" if TEST == "bai_perron" else "Stability tests",
        "columns": ([{"key": "test", "label": "Breaks", "type": "string"}, {"key": "looks_for", "label": "Dates", "type": "string"},
                     {"key": "statistic", "label": "RSS", "type": "number"}, {"key": "bic", "label": "BIC", "type": "number"},
                     {"key": "chosen", "label": "Chosen", "type": "string"}] if TEST == "bai_perron" else
                    [{"key": "test", "label": "Test", "type": "string"}, {"key": "looks_for", "label": "Sensitive to", "type": "string"},
                     {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]),
        "rows": rows,
    }],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
})

Bai–Perron fits every number of breaks, then picks by BIC. No break: 435.1. One break: 381.4. Two: 390.1.

It picks 1 break, on 2023-09-11. Why might a sup-F test come first, even if you end up dating with Bai–Perron?

07

A mean-only model

Reflect

With no predictors, the model is a mean alone. That connects these tests to the last lesson. On the Nile, exp-F = 33.8, p = 0.002, at 1898. That matches the Pettitt date.

Pick a regression you rely on. When was it fit? What has changed since? Which of these tests would show the change you're most worried about?

08

Check your understanding

Checkpoint

Check yourself

A law changed on a known date. You want to see if a regression changed there. Which test should you use?

Show the answer

Answer: a

A date with an outside reason gives Chow more power, since there's no search. Don't use Chow on a date you picked from the same plot.

Check yourself

A regression with an intercept and one slope (k=2k = 2) has n=100n = 100 observations. What are the Chow test's denominator degrees of freedom?

Show the answer

Answer: 96

n−2k=96n - 2k = 96.

Check yourself

CUSUM gives p = 0.80, but sup-F gives p = 0.002. How should you read that?

Show the answer

Answer: b

Knowing what each test detects lets you read their disagreement.

Check yourself

What else can make these tests reject on a stable regression?

Show the answer

Answer: a

The assumption rows on the card check for these. A change in variance alone can trigger these tests.

09

Do it in CodeSplash

In the app

Choose Outcome, Predictors and Time. Test defaults to a battery, and Chow F at a known break uses Break after observation. Bai–Perron sits under Several breaks.

Python
import pandas as pd
import statsmodels.api as sm
from statsmodels.stats.diagnostic import breaks_cusumolsresid

df = pd.read_csv("stability.csv")
fit = sm.OLS(df["y"], sm.add_constant(df[["x"]])).fit()
print(breaks_cusumolsresid(fit.resid, ddof=fit.df_model + 1))  # OLS-CUSUM
R
# install.packages("strucchange")
library(strucchange)
df <- read.csv("stability.csv")
sctest(y ~ x, data = df, type = "Chow", point = 50)
sctest(Fstats(y ~ x, data = df, from = 0.15))
sctest(efp(y ~ x, data = df, type = "Rec-CUSUM"))
breakpoints(y ~ x, data = df, h = 0.15)
10

Recap

Recap
  • Use Chow if the date comes from outside the data, sup-F if it doesn't.
  • CUSUM, MOSUM and Nyblom–Hansen each watch for a different kind of change.
  • When they disagree, ask what each one can see.
  • Bai–Perron dates several breaks, and BIC chooses how many.

Concepts in this lesson