Skip to content
svgbrushablerolling

Rolling statistics

Is the level or volatility of a series shifting, and which points break from recent behaviour?

Demo data · seed 20261101 · 365 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the darker line as the local level.
  2. Read the band as recent variability: a wider band means a more volatile period.
  3. Check the flagged points: they break from recent behaviour.
  1. Callout 1: The rolling mean: the local level.
  2. Callout 2: Band: a wider band means higher recent variability.
  3. 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