Conformal Prediction Intervals for Equity Return Forecasts in Python

A return forecast without an error budget is a number you cannot size. Treat the interval, not the point, as the deliverable here: a 90% band can hold at the nominal rate overall while badly under-covering the volatile tercile, and the failure arrives exactly when the band is load-bearing. Conformal prediction is the cheapest defensible way to attach such a band to a model you already have — and the fastest way to discover that your band was never conditional in the first place.
About this article. It is built from the published conformal-prediction literature — the Angelopoulos & Bates tutorial, Romano et al. on conformalized quantile regression, Barber et al. on jackknife+, Xu & Xie on EnbPI, Zaffran et al. on adaptive conformal inference — plus the MAPIE and scikit-learn documentation and a self-contained numpy demonstration on synthetic data. This article is based on the published conformal-prediction literature, library documentation and self-contained synthetic demonstrations; we did not run a live market backtest.
Why a point forecast is not a risk forecast
A point forecast collapses a conditional distribution into its centre and discards the dispersion that determines position size. Equity returns are strongly heteroscedastic: the conditional standard deviation moves with the volatility regime, so a single error bar calibrated across all days is systematically too wide in calm markets and too narrow in stressed ones.
You already know this from the residuals. Fit a ridge or gradient-boosted model to next-day returns, plot |residual| against a realised-volatility proxy, and the fan opens by a factor of several. A constant ± band therefore encodes an assumption — homoscedastic errors — that the data rejects. That matters downstream: position sizing, stop placement and VaR all consume the interval, not the mean. A model with a mediocre point forecast but a well-calibrated interval is more tradeable than a sharp model with a fabricated one.
What conformal prediction actually guarantees — and what it does not
Conformal prediction turns any pre-trained point model into an interval with a finite-sample, distribution-free guarantee: the interval contains the true value with at least the requested probability, on average over new draws. It requires only exchangeability between calibration and test points — no Gaussian errors, no correctly specified model.
The construction is embarrassingly simple. Hold out a calibration set of size n, compute a nonconformity score for each calibration point (for a regression interval, the absolute residual), and take the ⌈(n+1)(1−α)⌉-th smallest calibration score as the interval half-width. Note the ceiling and the +1: it is that order statistic, not a plain (1−α) empirical quantile, and the distinction is what buys the finite-sample correction. The Angelopoulos & Bates tutorial is the standard reference and covers structured outputs, distribution shift, time series, outliers and abstaining models, with Python notebooks; the accompanying repository is MIT-licensed (arXiv:2107.07511, github.com/aangelopoulos/conformal-prediction).
What it does not give you is equally important. The guarantee is marginal: at a 90% level the truth is covered for at least 90% of future observations on average over new observations, not per subgroup and not per individual observation (MAPIE documentation). There is no conditional coverage claim hiding in the theorem. Any statement of the form “this particular day has a 90% chance of being inside the band” is not what conformal prediction delivers.
A self-contained numpy demo: split conformal and CQR on synthetic returns
The script below builds synthetic next-day returns whose volatility depends on an observable feature, fits a least-squares mean model, and wraps it in both a split-conformal constant-width interval and a CQR interval. It prints marginal coverage, coverage by volatility tercile and mean width for both, using only numpy and a fixed seed.
Everything printed is illustrative and computed inside the script — no market data is touched. The three blocks are one program, run top to bottom.
import numpy as np
RNG = np.random.default_rng(20261102)
ALPHA = 0.10 # target 90% marginal coverage
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def make_returns(n):
"""Synthetic next-day returns with input-dependent volatility."""
x = RNG.standard_normal((n, 3))
vol = 0.004 + 0.012 * sigmoid(1.5 * x[:, 0]) # input-dependent scale
mean = 0.0003 * x[:, 1] # deliberately tiny signal
y = mean + vol * RNG.standard_normal(n)
return x, y
X, y = make_returns(8000)
X = np.column_stack([np.ones(len(X)), X]) # design matrix with intercept
n_train, n_cal = 3000, 1500
Xtr, ytr = X[:n_train], y[:n_train]
Xca, yca = X[n_train:n_train + n_cal], y[n_train:n_train + n_cal]
Xte, yte = X[n_train + n_cal:], y[n_train + n_cal:]
# --- (a) least-squares mean model + split conformal, constant half-width
w = np.linalg.lstsq(Xtr, ytr, rcond=None)[0]
cal_scores = np.abs(yca - Xca @ w)
k = int(np.ceil((n_cal + 1) * (1 - ALPHA))) # the ceil((n+1)(1-alpha)) rule
q_hat = np.sort(cal_scores)[k - 1]
pred_te = Xte @ w
lo_sc, hi_sc = pred_te - q_hat, pred_te + q_hat
# --- (b) linear quantile regression by pinball-loss fixed-point iteration
def fit_quantile(Xd, yd, tau, iters=300):
"""Solve the pinball subgradient equations:
sum_i w_i x_i (y_i - x_i'b) = 0, w_i = tau if y_i > x_i'b else 1 - tau."""
beta = np.linalg.lstsq(Xd, yd, rcond=None)[0]
ridge = 1e-8 * np.eye(Xd.shape[1])
for _ in range(iters):
wts = np.where(yd > Xd @ beta, tau, 1.0 - tau)
beta = np.linalg.solve(Xd.T @ (wts[:, None] * Xd) + ridge,
Xd.T @ (wts * yd))
return beta
beta_lo = fit_quantile(Xtr, ytr, ALPHA / 2)
beta_hi = fit_quantile(Xtr, ytr, 1 - ALPHA / 2)
# CQR score and the same conformal adjustment on top of it
cqr_scores = np.maximum(Xca @ beta_lo - yca, yca - Xca @ beta_hi)
Q = np.sort(cqr_scores)[int(np.ceil((n_cal + 1) * (1 - ALPHA))) - 1]
lo_cq = Xte @ beta_lo - Q
hi_cq = Xte @ beta_hi + Q
# --- (c) coverage overall, by volatility tercile, and mean width
def report(name, lo, hi):
cov = (yte >= lo) & (yte <= hi)
width = hi - lo
print(f"{name:>16s} overall={cov.mean():.3f} mean width={width.mean():.4f}")
edges = np.quantile(Xte[:, 1], [1 / 3, 2 / 3]) # bin by the vol driver
bins = np.digitize(Xte[:, 1], edges)
for b, tag in enumerate(["low-vol", "mid-vol", "high-vol"]):
m = bins == b
print(f"{tag:>20s} n={m.sum():4d} coverage={cov[m].mean():.3f} "
f"mean width={width[m].mean():.4f}")
print("# ILLUSTRATIVE OUTPUT on synthetic data — not a real backtest or market result")
report("split conformal", lo_sc, hi_sc)
report("CQR", lo_cq, hi_cq)
Here is that script’s output on this machine, verbatim:
# ILLUSTRATIVE OUTPUT on synthetic data — not a real backtest or market result
split conformal overall=0.902 mean width=0.0352
low-vol n=1167 coverage=0.992 mean width=0.0352
mid-vol n=1166 coverage=0.919 mean width=0.0352
high-vol n=1167 coverage=0.794 mean width=0.0352
CQR overall=0.901 mean width=0.0326
low-vol n=1167 coverage=0.955 mean width=0.0248
mid-vol n=1166 coverage=0.900 mean width=0.0325
high-vol n=1167 coverage=0.847 mean width=0.0404
Read the output as two diagnostics, not one. The overall line tests the marginal guarantee; the three tercile lines test whether that marginal number is hiding a conditional failure. On this design the constant-width interval is calibrated in aggregate but its tercile coverages spread widely, because one half-width has to serve both the calm and the volatile part of the sample. The CQR row moves the terciles back toward the nominal level while cutting mean width, since the quantile models already know which days are wide.
Constant width is the wrong shape: conformalized quantile regression
Split conformal produces one half-width for every input, so on heteroscedastic returns it is too wide in calm regimes and too narrow in volatile ones. Conformalized quantile regression fixes the shape: it calibrates a correction on top of fitted lower and upper conditional quantiles, giving intervals whose width varies with the inputs while keeping the coverage guarantee.
The mechanics are a two-line change to the split-conformal recipe. Fit a lower quantile model at α/2 and an upper at 1−α/2 on the proper-training split. On the calibration set, score each point by how far outside its own quantile band the truth fell:
E_i = max( q̂_lo(x_i) − y_i , y_i − q̂_hi(x_i) )
Then take Q as the ⌈(n+1)(1−α)⌉-th smallest of those E_i — the same order statistic as before — and return [q̂_lo(x) − Q, q̂_hi(x) + Q]. Q may be negative, in which case the band is legitimately narrowed rather than widened. Romano, Patterson and Candès introduced this precisely because standard conformal methods can be unnecessarily conservative, forming intervals of constant or weakly varying length across the input space; CQR is fully adaptive to heteroscedasticity with a coverage guarantee, and in their experiments it tends to produce shorter intervals than other conformal methods (arXiv:1905.03222).
The quantile models themselves are commodity. scikit-learn’s QuantileRegressor fits a linear model to the pinball loss with L1 regularisation, is robust to outliers, and defaults to alpha=1.0 with the highs solver since version 1.4 (docs). The demo above replaces it with a fixed-point iteration on the pinball subgradient equations purely to stay inside numpy.
One related fix is worth knowing. Split conformal wastes data and ignores variability in the fitted regression function. Jackknife+ uses leave-one-out predictions at the test point and, with exchangeable training samples, gives rigorous coverage for any algorithm that treats training points symmetrically; the original jackknife has no such guarantee and the paper gives examples where its coverage can vanish. The same guarantees extend to K-fold cross-validation (CV+) (arXiv:1905.02928). Jackknife+ addresses model instability, not heteroscedasticity — it is complementary to CQR, not a substitute.
The marginal–conditional gap: what the 90% actually averages over
The guarantee is an average over future observations, not a promise inside every subgroup or for every individual day. A procedure can hit the nominal rate overall while covering far more than that in calm days and far fewer in volatile ones — the demo’s tercile table measures exactly that gap. Our practical view is that the tercile number, not the overall one, is what a risk system consumes.
This is the single most common misreading of conformal prediction, and it is not a bug in any particular implementation. The theorem controls the expected miscoverage over the joint distribution of (X, Y); it says nothing about miscoverage conditional on X = x. Treat the tercile figures as descriptive statistics of this demo, not as additional guarantees.
For production work the sane path is to stop hand-rolling this. MAPIE, the scikit-learn-contrib Model Agnostic Prediction Interval Estimator, returns an interval for regression and a set for classification for any scikit-learn-compatible estimator. Version 1 shipped in 2025 with a new API, and 2026 additions include risk control for LLM-as-judge and image segmentation, exchangeability tests to check whether MAPIE can legitimately be applied to your data, and adaptive conformal methods (mapie.readthedocs.io). Those exchangeability tests are the practically important part: they turn a silent assumption into a diagnostic you can run.
When exchangeability fails: regimes, drift and the fixes that survive
Split conformal assumes calibration and test points are exchangeable, which equity returns violate through volatility clustering, regime shifts and drift. Weighted conformal handles known or estimable covariate shift, EnbPI drops the exchangeability requirement via bootstrap ensembles, and adaptive conformal methods update the miscoverage level online as the stream arrives.
Covariate shift. When test and training covariate distributions differ but the likelihood ratio is known or estimable from a large set of unlabeled data, a weighted version of conformal prediction restores distribution-free intervals. It rests on weighted exchangeability, not plain exchangeability (arXiv:1904.06019). In equity terms: if you can estimate how the feature distribution has moved — a density-ratio model on recent unlabeled features — you can reweight the calibration scores instead of pretending nothing changed.
No exchangeability at all. EnbPI wraps any bootstrap ensemble estimator to build sequential intervals and does not require data exchangeability. It attains finite-sample approximately valid marginal coverage for broad regression classes with strongly mixing errors, needs no data splitting, and requires no retraining of multiple ensembles — it aggregates already-trained bootstrap estimators (Xu & Xie, ICML 2021). For a walk-forward equity setup where you already maintain a bagged model, this is the lowest-friction option.
Online adaptation. Adaptive Conformal Inference (Gibbs & Candès, 2021) was developed for distribution-shift time series and suits general time-series dependency. Zaffran et al. analyse the learning-rate effect in both exchangeable and autoregressive cases and propose AgACI, a parameter-free online-expert aggregation over candidate learning rates (ICML 2022). Be careful with the evidence here: their real-data case study is electricity price forecasting, not equities. The method transfers; the empirical claim does not.
Multi-horizon. If you forecast a path rather than one day, Stankeviciute, Alaa and van der Schaar extend inductive conformal prediction to the multi-horizon forecasting setup, giving uncertainty estimates with theoretical guarantees for any multi-horizon forecast predictor under minimal exchangeability assumptions (NeurIPS 2021). Calibrating each horizon independently is the naive alternative and it ignores the dependence across horizons.
A practical checklist before you ship an interval
Treat the marginal guarantee as a floor to be verified, not a result to be assumed. Split your calibration data by regime, report coverage per regime next to the headline number, and decide in advance which of the two your downstream consumer actually needs. If they differ badly, the interval is mis-shaped, not mis-calibrated.
- State the coverage level and the word marginal in the same sentence, every time you report it.
- Use ⌈(n+1)(1−α)⌉, not a plain empirical quantile; the difference is small but it is the difference between a guarantee and an approximation.
- Always print coverage by volatility bucket alongside overall coverage. A single number hides the failure mode you care about.
- Prefer CQR when residual scale varies with features; prefer jackknife+/CV+ when the fitted model itself is unstable across folds.
- Test exchangeability before trusting the band — MAPIE ships tests for this.
- If you cannot assume exchangeability, move to weighted conformal, EnbPI or an adaptive method, and accept that the guarantee weakens to “approximately valid” in the sequential case.
- Never quote a coverage number from synthetic data as evidence about a market.
FAQ
Does a 90% conformal interval mean each individual day has a 90% chance of being covered?
No. The guarantee is marginal: coverage holds at or above 90% on average over future observations, not per observation and not per subgroup. Individual days in a high-volatility regime can be covered well below the nominal rate while the overall average still holds, which is why per-regime reporting matters (MAPIE docs).
Can I apply conformal prediction to a model I have already trained and deployed?
Yes — that is the point. Conformal prediction wraps any pre-trained model to produce sets containing the ground truth at a user-specified probability, without distributional or model assumptions, and the tutorial covers structured outputs, distribution shift, time series and abstaining models (arXiv:2107.07511). You only need a held-out calibration set that is exchangeable with the data you will see at inference time.
Is CQR always better than split conformal?
No, but it is better shaped when the noise is heteroscedastic. CQR is fully adaptive to heteroscedasticity with a coverage guarantee, and in the original experiments it tends to produce shorter intervals than other conformal methods, because constant-width intervals are unnecessarily conservative on calm inputs (arXiv:1905.03222). If your residuals are genuinely homoscedastic, the extra quantile models buy you nothing but variance.
← Back to all posts

