DRegression models · regression.stability
Structural change in a regression
Did the relationship between the outcome and its predictors change over time — at a known date, at an unknown date, or gradually?
Tests whether a linear regression fitted in time order keeps the same coefficients throughout: the Chow F test at a known break, the sup-, average- and exponential-F tests over every candidate break, recursive and OLS CUSUM and MOSUM fluctuation tests, the Nyblom–Hansen test of gradually drifting coefficients, and Bai–Perron dating of several breaks chosen by BIC.
A real result
Example “Chow guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Chow F = 0.05, p = .950
- Chow F
- 0.0516
- p
- 0.9498
Plots
View data
| t | y |
|---|---|
| 1 | 1.193 |
| 2 | 0.7706 |
| 3 | 0.7719 |
| 4 | −1.233 |
| 5 | 0.6758 |
| 6 | 1.678 |
| 7 | −0.2795 |
| 8 | 0.3454 |
| 9 | 0.5854 |
| 10 | 2.101 |
| 11 | −0.5170 |
| 12 | 1.057 |
| 13 | 0.1710 |
| 14 | 0.7193 |
| 15 | −0.8420 |
| 16 | 2.395 |
| 17 | 1.832 |
| 18 | 2.536 |
| 19 | 2.350 |
| 20 | 3.186 |
| 21 | 1.478 |
| 22 | −0.9780 |
| 23 | −0.1679 |
| 24 | 1.226 |
| 25 | 0.2065 |
| 26 | 3.246 |
| 27 | 1.133 |
| 28 | 0.1737 |
| 29 | 1.981 |
| 30 | 2.874 |
| 31 | 0.4785 |
| 32 | 2.287 |
| 33 | 1.548 |
| 34 | 1.473 |
| 35 | 0.6531 |
| 36 | 2.291 |
| 37 | −1.300 |
| 38 | 1.319 |
| 39 | 1.977 |
| 40 | 2.754 |
| 41 | 0.7961 |
| 42 | 1.547 |
| 43 | 1.848 |
| 44 | 1.502 |
| 45 | 0.9261 |
| 46 | 1.415 |
| 47 | 1.595 |
| 48 | −0.0386 |
| 49 | 2.707 |
| 50 | 0.2055 |
| 51 | 0.1261 |
| 52 | 1.686 |
| 53 | 0.4325 |
| 54 | 1.271 |
| 55 | 2.380 |
| 56 | 0.5925 |
| 57 | −0.0573 |
| 58 | 1.835 |
| 59 | 0.7220 |
| 60 | 0.0484 |
First 60 of 100 rows.
Assumptions
- Independent errors — Lag-1 autocorrelation of the residuals is -0.10.
- Constant error variance — Residual variance in the second half is 0.65 × the first half (F test p = 0.129).
Stability tests
| Test | Sensitive to | Statistic | p |
|---|---|---|---|
| Chow F | a change after 50 | 0.0516 | .950 |
- Rows are taken in time order; every test compares the regression across time, so the order matters.
Chow F = 0.05, p = .950
- Chow F
- 0.0516
- p
- 0.9498
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.10.
- Constant error variance — Residual variance in the second half is 0.65 × the first half (F test p = 0.129).
Stability tests
| Test | Sensitive to | Statistic | p |
|---|---|---|---|
| Chow F | a change after 50 | 0.0516 | .950 |
- Rows are taken in time order; every test compares the regression across time, so the order matters.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Chow guides3_stability · outcome: y · predictors: x · time: t
- Supf guides3_stability · outcome: y · predictors: x · time: t
- Rec cusum guides3_stability · outcome: y · predictors: x · time: t
- Ols mosum guides3_stability · outcome: y · predictors: x · time: t
- Nyblom guides3_stability · outcome: y · predictors: x · time: t
- Battery slope changes3_shifts · outcome: yreg · predictors: xreg · time: week
- Bai perron slope changes3_shifts · outcome: yreg · predictors: xreg · time: week
- Mean stability nileml_nile · outcome: flow · time: year
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Regression diagnostics · Statistics Guide · D — Predict an outcome
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Outcomenumeric · 1 column
- The response of the linear model.
- Predictorsnumeric · 0–20 columns
- Numeric predictors (none = test the stability of the mean).
- Timetemporal / numeric · 0–1 column
- Orders the rows (omit to use the row order); breaks are reported at these times.
Choices you make
hypothesis
- Testdefault battery
H₀: the regression coefficients are the same throughout the period.
- Battery (sup-F, recursive and OLS CUSUM, OLS-MOSUM, Nyblom–Hansen)(default) — Each test looks for a different kind of change; read them together.
- Chow F at a known break — When the date of the possible change (a policy, a relocation) was fixed before seeing the data.
- sup-F (Quandt / Andrews) — Largest Chow statistic over all candidate dates, with a p-value that allows for the search. Like strucchange, it is on the Wald scale: k × the Chow F.
- ave-F (Andrews–Ploberger) — Average F over the candidates: more power when a change could be anywhere.
- exp-F (Andrews–Ploberger) — Combines F tests over all candidate dates with exponential weights; good for one break at an unknown date.
- Bai–Perron (date several breaks) — Dynamic programming finds the best m-break partition for every m; BIC chooses m.
- Recursive CUSUM (Brown–Durbin–Evans) — Cumulative sum of one-step-ahead forecast errors: catches a change in the intercept early in the sample.
- OLS-CUSUM (Ploberger–Krämer) — Tracks cumulative OLS residuals; best at spotting a shift in the intercept.
- OLS-MOSUM (moving sums) — Moving sums of residuals over a window: catches a change that later reverses.
- Recursive MOSUM — Tracks a moving sum of recursive residuals; pick it for a change that may reverse mid-sample.
- Nyblom–Hansen (gradual drift) — Locally most powerful against coefficients that drift as a random walk.
- Break after observationdefault —
Position in time order of the last observation before the break (fix it before looking at the data).
options
- Trimmingdefault 0.15
Share of observations excluded at each end as candidate breaks (and the shortest Bai–Perron segment).
- MOSUM windowdefault 0.2
Window as a share of the sample.
- Most breaksdefault 5
Most structural breaks Bai–Perron may place.
- p-valuesdefault auto
How the p-value is computed: a large-sample formula, or by permutation or simulation (slower, fewer assumptions).
- Classic where available, else simulated(default) — Chow from F; the CUSUMs from their Brownian-motion approximations; the rest by Monte Carlo with your predictors held fixed.
- Simulated for every test — Exact for normal errors at this sample size, given the predictors.
- Simulationsdefault 999
Monte-Carlo replicates (normal errors, predictors held fixed).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Independent errors
Autocorrelated errors make the fluctuation and F tests reject too often.
Constant error variance
A change in variance alone can trigger these tests; check the residual plot.
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- stat
- A single number that summarizes how far your data are from what H₀ predicts.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- reject
- A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
Per group, level or term: test, test_label, df1, df2, break_at, break_label, sup_at, sup_at_label, n_reject, reps, m, break_<i>, bic_<m>, rss_<m>, rho1, <test>_stat, <test>_p, crit_5
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Same twin in both engines; Monte-Carlo p-values use the shared Wichmann–Hill stream with the predictors held fixed, so they agree exactly.
- Statistics equal strucchange's (Chow, Fstats sup/ave/exp, efp Rec-/OLS-CUSUM and MOSUM, gefp with meanL2BB, breakpoints RSS and BIC). strucchange's p-values for sup-/ave-/exp-F, MOSUM and meanL2 come from asymptotic tables (Hansen 1997, Chu et al. 1995); ours are finite-sample Monte-Carlo, so they differ somewhat.
The exact script CodeSplash ran for example “Chow guide” · 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 eb2483332b1f4d6d
# Dataset: s3_stability (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_stability.parquet", columns=["y", "x", "t"])
n_input = len(df)
df = df.dropna(subset=["y", "x", "t"]) # 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, ["y", "x", "t"]) # infinite values stop the run (registry/errors.yaml)
# %% Data in time order
OUTCOME = "y"
PREDICTORS = ["x"]
TIME = "t"
TEMPORAL = False
TEST = "chow"
BREAK_AT = 50
TRIM = 0.15
H = 0.2
MAX_BREAKS = 5
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,
})
The exact script CodeSplash ran for example “Chow guide” · 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 eb2483332b1f4d6d
# Dataset: s3_stability (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_stability.parquet", col_select = c("y", "x", "t")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y", "x", "t")]), , 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", "x", "t")) # infinite values stop the run (registry/errors.yaml)
# %% Data in time order
OUTCOME <- "y"
PREDICTORS <- c("x")
TIME <- "t"
TEMPORAL <- FALSE
TEST <- "chow"
BREAK_AT <- 50
TRIM <- 0.15
H <- 0.2
MAX_BREAKS <- 5
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
))
Sources
- Chow, G. C. (1960). Tests of equality between sets of coefficients in two linear regressions. Econometrica, 28, 591–605.
- Andrews, D. W. K. (1993). Tests for parameter instability and structural change with unknown change point. Econometrica, 61, 821–856.
- Andrews, D. W. K., & Ploberger, W. (1994). Optimal tests when a nuisance parameter is present only under the alternative. Econometrica, 62, 1383–1414.
- Brown, R. L., Durbin, J., & Evans, J. M. (1975). Techniques for testing the constancy of regression relationships over time. JRSS B, 37, 149–192.
- Ploberger, W., & Krämer, W. (1992). The CUSUM test with OLS residuals. Econometrica, 60, 271–285.
- Chu, C.-S. J., Hornik, K., & Kuan, C.-M. (1995). MOSUM tests for parameter constancy. Biometrika, 82, 603–617.
- Nyblom, J. (1989). Testing for the constancy of parameters over time. JASA, 84, 223–230.
- Hansen, B. E. (1992). Testing for parameter instability in linear models. J. Policy Modeling, 14, 517–533.
- Bai, J., & Perron, P. (2003). Computation and analysis of multiple structural change models. J. Applied Econometrics, 18, 1–22.
- Zeileis, A., Leisch, F., Hornik, K., & Kleiber, C. (2002). strucchange: An R package for testing for structural change in linear regression models. J. Statistical Software, 7(2).
From the CodeSplash method registry · regression.stability v1.0.3.