svgbrushablerolling
Rolling statistics
Is the level or volatility of a series shifting, and which points break from recent behaviour?
How to read it
- Read the darker line as the local level.
- Read the band as recent variability: a wider band means a more volatile period.
- Check the flagged points: they break from recent behaviour.
- Callout 1: The rolling mean: the local level.
- Callout 2: Band: a wider band means higher recent variability.
- Callout 3: A flagged point: unusual given the recent window.
Watch out
- The rolling mean lags behind turning points, and window length changes what gets flagged.
Defaults
- Window (observations)
- 30
- How many recent observations go into each rolling value: larger is smoother but slower to react.
- Range 2 to 365, step 1
- Band ± k·SD
- 2
- How many rolling standard deviations the band spans around the rolling mean.
- Range 1 to 4, step 0.5
- Flag points outside the band
- On
- Mark points that break from their recent behaviour.
Pinned in the code
- Trailing (right-aligned) windows of w observations including the current one: pandas `rolling(w).mean()/.std()`, zoo `rollapply(align = "right")`. The first w − 1 points have no value.
- SD uses n − 1 within the window. The window counts observations, not calendar time; resample irregular series first.
- Flagged points lie more than k rolling SDs from the rolling mean that includes them (a screening aid, not a test).
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")
# controls: window=30, k=2, outliers=true
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("rolling-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
_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")
d = df.dropna(subset=["day", "p95_ms"]).sort_values("day", kind="stable") # lags count observations, not calendar time
v = d["p95_ms"].to_numpy(dtype=float)
w, k = max(2, min(30, len(v))), 2
s = pd.Series(v)
mean, sd = s.rolling(w).mean(), s.rolling(w).std() # trailing windows of w observations, SD on n − 1
t = d["day"].to_numpy()
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, v, color=GREY, linewidth=1, label="p95_ms")
ax.fill_between(t, mean - k * sd, mean + k * sd, color=PALETTE[0], alpha=0.15, linewidth=0, label=f"± {k}·SD")
ax.plot(t, mean, color=PALETTE[0], linewidth=1.8, label=f"rolling mean ({w})")
out = (np.abs(v - mean) > k * sd).to_numpy() # outside the band that includes the point
ax.scatter(t[out], v[out], color=PALETTE[3], s=16, zorder=3, label="outside band")
ax.set_ylabel("p95_ms")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads rolling-demo.csv · app theme from the optional codesplash helper
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")
# controls: window=30, k=2, outliers=true
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("rolling-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
_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")
d = df.dropna(subset=["day", "p95_ms"]).sort_values("day", kind="stable") # lags count observations, not calendar time
v = d["p95_ms"].to_numpy(dtype=float)
w, k = max(2, min(30, len(v))), 2
s = pd.Series(v)
mean, sd = s.rolling(w).mean(), s.rolling(w).std() # trailing, SD on n − 1
t = d["day"].to_numpy()
fig = go.Figure()
fig.add_scatter(x=t, y=mean - k * sd, mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=t, y=mean + k * sd, mode="lines", line_width=0, fill="tonexty", fillcolor="rgba(41,113,198,0.15)", name=f"± {k}·SD")
fig.add_scatter(x=t, y=v, mode="lines", line=dict(color=GREY, width=1), name="p95_ms")
fig.add_scatter(x=t, y=mean, mode="lines", line=dict(color=PALETTE[0], width=2), name=f"rolling mean ({w})")
out = (np.abs(v - mean) > k * sd).to_numpy()
fig.add_scatter(x=t[out], y=v[out], mode="markers", marker=dict(color=PALETTE[3], size=7), name="outside band")
fig.show()Needs pandas, numpy, plotly · reads rolling-demo.csv · app theme from the optional codesplash helper
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")
# controls: window=30, k=2, outliers=true
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("rolling-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["day"]] <- as.POSIXct(df[["day"]], tz = "UTC")
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
d <- df[!is.na(df[["day"]]) & !is.na(df[["p95_ms"]]), , drop = FALSE]
d <- d[order(d[["day"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["p95_ms"]]
w <- max(2, min(30, length(v))); k <- 2
roll <- function(v, w, f) vapply(seq_along(v), function(i) if (i < w) NA_real_ else f(v[(i - w + 1):i]), numeric(1))
r <- data.frame(t = d[["day"]], v = v, mean = roll(v, w, mean), sd = roll(v, w, stats::sd)) # trailing windows, SD on n - 1
r$out <- !is.na(r$mean) & abs(r$v - r$mean) > k * r$sd
p <- ggplot(r, aes(t)) +
geom_ribbon(aes(ymin = mean - k * sd, ymax = mean + k * sd), fill = cs_cat[1], alpha = 0.15, na.rm = TRUE) +
geom_line(aes(y = v), colour = grey_col) +
geom_line(aes(y = mean), colour = cs_cat[1], linewidth = 0.9, na.rm = TRUE) +
geom_point(data = function(d) d[d$out, ], aes(y = v), colour = cs_cat[4], size = 1.6) +
labs(x = "day", y = "p95_ms", subtitle = sprintf("rolling mean and ±%s·SD over %d observations", k, w)) +
theme_cs
print(p)Needs ggplot2 · reads rolling-demo.csv · app theme from the optional codesplashr helper
-- Rolling statistics — Codesplash Chart Lab (recipe "rolling")
-- controls: window=30, k=2, outliers=true
-- trailing window of 30 observations (complete windows only), SD on n − 1, band ± 2·SD
WITH s AS (
SELECT "day" AS t, "p95_ms" AS v,
count(*) OVER w AS n_w, avg("p95_ms") OVER w AS mean, stddev_samp("p95_ms") OVER w AS sd
FROM read_csv('rolling-demo.csv')
WHERE "p95_ms" IS NOT NULL AND "day" IS NOT NULL
WINDOW w AS (ORDER BY "day" ROWS BETWEEN 29 PRECEDING AND CURRENT ROW)
)
SELECT t, v,
CASE WHEN n_w = 30 THEN mean END AS rolling_mean,
CASE WHEN n_w = 30 THEN sd END AS rolling_sd,
n_w = 30 AND abs(v - mean) > 2 * sd AS outside_band
FROM s;Needs duckdb · reads rolling-demo.csv