svgfluctuation-process
Fluctuation process with boundaries
Does the cumulative (or moving) sum of residuals wander outside what a stable regression allows?
How to read it
- Read the line as cumulative (or moving) residuals from a regression fitted in time order.
- Leaving the boundaries signals a change in the coefficients.
- Note where it first crosses: the change happened before that.
- Callout 1: Crossing the boundary: unstable coefficients.
- Callout 2: The upper 5% boundary.
- Callout 3: A stable regression keeps the process near zero.
Watch out
- The crossing date isn't the break date: use the F sequence or Bai–Perron to date it.
Defaults
- Process
- OLS-CUSUM
- Which fluctuation process to draw: cumulative or moving sums of residuals.
- Also: Recursive CUSUM · OLS-MOSUM · Recursive MOSUM
- 5% critical value (0 = closed form)
- 0
- The analysis sends a simulated value for the MOSUMs; the CUSUMs have closed forms.
- Range 0 to 10, step 0.01
Pinned in the code
- Recursive CUSUM: boundary ±λ(1 + 2t) with λ = 0.948 at 5% (Brown, Durbin & Evans); OLS-CUSUM: ±1.358 (Brownian-bridge supremum).
- MOSUM boundaries have no closed form: the analysis sends a simulated 5% point (normal errors, predictors held fixed); with none, no boundary is drawn.
- t runs from 0 to 1 across the process; processes are scaled as strucchange's efp().
# Fluctuation process with boundaries — Codesplash Chart Lab (recipe "fluctuation-process")
# controls: kind=ols-cusum, crit=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("fluctuation-process-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "observations used"
Y = "OLS-CUSUM"
KIND, CRIT = "ols-cusum", 1.358099 # 5% boundary (recursive CUSUM: ±CRIT·(1 + 2t))
d = ordered(df, X, [Y])
x, v = time_of(d, X).to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
t = (x - x[0]) / (x[-1] - x[0]) # 0 … 1 across the process
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhline(0, color="grey", linewidth=0.8)
if CRIT is not None:
b = CRIT * (1 + 2 * t) if KIND == "rec-cusum" else np.full_like(t, CRIT)
ax.plot(x, b, color="#ce5342", linestyle="--", linewidth=1.2, label="5% boundary")
ax.plot(x, -b, color="#ce5342", linestyle="--", linewidth=1.2)
ax.plot(x, v, color=PALETTE[0], linewidth=1.8, label=KIND)
ax.set_xlabel("observations used")
ax.set_ylabel("empirical fluctuation process")
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads fluctuation-process-demo.csv · app theme from the optional codesplash helper
# Fluctuation process with boundaries — Codesplash Chart Lab (recipe "fluctuation-process")
# controls: kind=ols-cusum, crit=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("fluctuation-process-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "observations used"
Y = "OLS-CUSUM"
KIND, CRIT = "ols-cusum", 1.358099
d = ordered(df, X, [Y])
x, v = time_of(d, X).to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
t = (x - x[0]) / (x[-1] - x[0])
fig = go.Figure(go.Scatter(x=x, y=v, mode="lines", line=dict(color=PALETTE[0], width=1.8), name=KIND))
if CRIT is not None:
b = CRIT * (1 + 2 * t) if KIND == "rec-cusum" else np.full_like(t, CRIT)
for sgn in (1, -1):
fig.add_scatter(x=x, y=sgn * b, mode="lines", line=dict(color="#ce5342", dash="dash"), name="5% boundary", showlegend=sgn == 1)
fig.update_layout(xaxis_title="observations used", yaxis_title="empirical fluctuation process")
fig.show()Needs pandas, numpy, plotly · reads fluctuation-process-demo.csv · app theme from the optional codesplash helper
# Fluctuation process with boundaries — Codesplash Chart Lab (recipe "fluctuation-process")
# controls: kind=ols-cusum, crit=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("fluctuation-process-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "observations used"
y_col <- "OLS-CUSUM"
KIND <- "ols-cusum"
CRIT <- 1.358099 # 5% boundary
d <- ordered(df, x_col, y_col)
pr <- data.frame(x = as.numeric(time_of(d, x_col)), v = d[[y_col]])
tt <- (pr$x - pr$x[1]) / (pr$x[nrow(pr)] - pr$x[1])
if (!is.null(CRIT)) pr$b <- if (KIND == "rec-cusum") CRIT * (1 + 2 * tt) else CRIT
p <- ggplot(pr, aes(x, v)) + geom_hline(yintercept = 0, colour = "grey50") +
{ if (!is.null(CRIT)) list(geom_line(aes(y = b), colour = "#ce5342", linetype = "dashed"), geom_line(aes(y = -b), colour = "#ce5342", linetype = "dashed")) } +
geom_line(colour = cs_cat[1], linewidth = 0.9) + labs(x = "observations used", y = "empirical fluctuation process", title = KIND) + theme_cs
print(p)Needs ggplot2 · reads fluctuation-process-demo.csv · app theme from the optional codesplashr helper