svgvolatility-band
Volatility band
When was the series calm or turbulent, and how wide should the next moves be expected to be?
How to read it
- Read the line as the series and the band as its expected range at each moment.
- A wide band marks a turbulent period; volatility tends to cluster.
- Read the extension at the end as how wide the next moves should be expected to be.
Watch out
- The band models size, not direction: it says nothing about which way the series will move.
Defaults
- Band (σ)
- 2
- How many conditional standard deviations the band spans on each side of the mean.
- Range 0.5 to 4, step 0.5
Pinned in the code
- The band is mean ± k σ_t with σ_t the model's conditional standard deviation; the forecast part continues it with the variance forecasts.
- With k = 2 about 95% of normally distributed moves fall inside; fat-tailed returns breach it more often.
Use with care
A wider band says larger moves are likely, in either direction; it says nothing about which way the series will go.
# Volatility band — Codesplash Chart Lab (recipe "volatility-band")
# controls: k=2
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("volatility-band-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"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["fit", "forecast"])
_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")
X = "day"
SIGMA = "volatility"
V = "return"
M = "mean"
KIND = "kind"
K = 2 # band = mean ± K·sigma
d = df.dropna(subset=[SIGMA])
d = d.sort_values(X, kind="stable") if X else d
t = d[X] if X else np.arange(1, len(d) + 1)
mid = d[M] if M else 0.0
ahead = (d[KIND].astype(str) == "forecast").to_numpy() if KIND else np.zeros(len(d), dtype=bool)
fig, ax = plt.subplots(figsize=(8, 4))
ax.fill_between(t, mid - K * d[SIGMA], mid + K * d[SIGMA], where=~ahead, color=PALETTE[0], alpha=0.22, linewidth=0, label=f"Fitted ±{K} σ")
if ahead.any():
ax.fill_between(t, mid - K * d[SIGMA], mid + K * d[SIGMA], where=ahead, color=PALETTE[1], alpha=0.3, linewidth=0, label=f"Forecast ±{K} σ")
if V:
ax.plot(t, d[V], color=GREY, linewidth=0.8, label=V)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads volatility-band-demo.csv · app theme from the optional codesplash helper
# Volatility band — Codesplash Chart Lab (recipe "volatility-band")
# controls: k=2
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("volatility-band-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"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["fit", "forecast"])
_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")
X = "day"
SIGMA = "volatility"
V = "return"
M = "mean"
K = 2
d = df.dropna(subset=[SIGMA])
d = d.sort_values(X, kind="stable") if X else d
t = list(d[X]) if X else list(range(1, len(d) + 1))
mid = d[M] if M else 0.0
up, lo = mid + K * d[SIGMA], mid - K * d[SIGMA]
fig = go.Figure(go.Scatter(x=t + t[::-1], y=list(up) + list(lo)[::-1], fill="toself", fillcolor="rgba(70,110,200,0.22)", line=dict(width=0), name=f"±{K} σ"))
if V:
fig.add_trace(go.Scatter(x=t, y=d[V], mode="lines", line=dict(color=GREY, width=1), name=V))
fig.show()Needs pandas, numpy, plotly · reads volatility-band-demo.csv · app theme from the optional codesplash helper
# Volatility band — Codesplash Chart Lab (recipe "volatility-band")
# controls: k=2
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("volatility-band-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")
df[["kind"]] <- factor(df[["kind"]], levels = c("fit", "forecast"))
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
X <- "day"
SIGMA <- "volatility"
V <- "return"
M <- "mean"
KIND <- "kind"
K <- 2 # band = mean ± K·sigma
d <- df[!is.na(df[[SIGMA]]), , drop = FALSE]
d$.t <- if (!is.null(X)) d[[X]] else seq_len(nrow(d))
d <- d[order(d$.t), , drop = FALSE]
d$.mid <- if (!is.null(M)) d[[M]] else 0
d$.part <- if (!is.null(KIND)) as.character(d[[KIND]]) else "fit"
d$.s <- d[[SIGMA]]
p <- ggplot(d, aes(.t)) +
geom_ribbon(aes(ymin = .mid - K * .s, ymax = .mid + K * .s, fill = .part), alpha = 0.3) +
scale_fill_manual(values = c(fit = cs_cat[1], forecast = cs_cat[2]), name = NULL) +
labs(x = if (!is.null(X)) X else "observation", y = if (!is.null(V)) V else SIGMA)
if (!is.null(V)) { d$.v <- d[[V]]; p <- p + geom_line(data = d[!is.na(d$.v), ], aes(y = .v), colour = "grey55", linewidth = 0.3) }
print(p)Needs ggplot2 · reads volatility-band-demo.csv · app theme from the optional codesplashr helper