analogue-risk

How does analogue-risk work?

Forecasting market risk by finding the moments in the past that looked like now.

Weather forecasters had a trick before computers could simulate the atmosphere: look through old charts for a day that looked like today, and forecast whatever happened next. It's called the method of analogues. analogue-risk applies it to markets. It doesn't try to guess where the price goes next. It asks how much the price is likely to move.

It's a Rust core with a Python interface, and it was tested with a pre-registered study on 15 assets it had never seen. This page walks through how it works and what that study found.

The idea

A volatility shape

At every bar, the model describes the recent past as a short shape: the log variance of returns in each of the last m segments (four by default), measured relative to the asset's long-run level. A shape like quiet, quiet, busier, spike is the kind of thing it looks for.

Then it searches the whole history for the shapes closest to today's, and averages what came next. In the chart below, the blue line is the shape at one moment on Bitcoin's hourly chart. The grey lines are the ten nearest past shapes, and the dashed line is the forecast they produce.

Line chart: the current volatility shape over four segments, ten grey historical analogues that follow a similar path, the dashed analogue forecast for the next 24 hours and the realised value.
One forecast, explained by its analogues. From results/figures.

In nearest-neighbour mode, every forecast comes with the analogues behind it, so you can see which past moments produced any prediction.

Picking analogues

Picking "the nearest past shapes" has two traps, and the engine guards against both.

The first is peeking. A past moment is only useful once you know what happened after it. If the horizon is h bars, the most recent h bars (today included) don't have a complete outcome yet, so they can't be used.

The second is near-duplicates. Neighbouring bars look almost identical, so a naive search returns ten copies of the same week. The engine requires analogues to be at least h bars apart, so their outcome windows never overlap.

Try it below, and drop the exclusion to 1 to watch the picks bunch together. Each box is a past bar, and the bar inside it shows how close its shape is to today's (taller is closer).

model.neighbours(k=3, exclusion=3)
oldesttoday →
analogue too close to one outcome not known yet today
The similarity scores here are made up for the illustration. The rule is the real one: closest first, skip anything within the exclusion zone, never touch an anchor whose outcome isn't in yet (src/analog.rs).

Calm and stormy regimes

Markets switch between calm and stormy stretches. The engine labels each bar as one or the other (is the 14-bar ATR above its long moving average?) and picks k analogues from each regime. A two-state Markov chain, fitted on recent transitions, estimates how likely the next h bars are to be stormy. The two groups are blended with those odds.

A smoother variant drops the hard top-k cut and weights every past moment by a Gaussian kernel of its distance. In the study, that variant beat the plain nearest-neighbour search (H4 below), so it's the recommended setting for new work.

Why risk, not direction

This project started as a TradingView strategy: a one-dimensional nearest-neighbour match on 20-bar returns, a Markov volatility regime, a Poisson "crash gate" and Kelly sizing, all used to predict whether price would go up or down.

Version 2 kept that architecture, ported the original strategy line by line to Rust (src/legacy.rs), and evaluated both versions out of sample. Direction didn't hold up: across 15 new assets the mean information coefficient was +0.003 (p = 0.60). Volatility, on the other hand, clusters. A quiet market tends to stay quiet and a violent one stays violent, which gives analogues something real to find. So the project moved from forecasting direction to forecasting risk.

Testing it honestly

Pre-registration

The model was designed on 9 development assets. Then the eight hypotheses, the models, a list of 15 new assets and the analysis code were committed and tagged prereg-v1 before any data for those assets was downloaded. The confirmatory run used that code unchanged (deviations: none). The tag is archived on Zenodo (doi:10.5281/zenodo.24795156).

Every forecast is walk-forward: the first 30% of each series is for calibration, and the rest is split into five folds. Each fold only uses parameters fitted on data before it. Benchmarks are the standard ones: EWMA, GARCH(1,1), HAR, gradient-boosted trees, Hawkes processes and filtered historical simulation.

What held up

Results on the 15 confirmatory assets (25 series once each daily asset's two horizons are counted). Holm-adjusted p-values are in results/confirmatory/hypotheses.md.

QuestionAnswer
H1Do analogues predict price direction?No. Mean IC +0.003, p = 0.60
H2Analogue+HAR vs HAR for volatilityNo significant difference. Median QLIKE ratio 1.001
H3Analogue alone vs HARWorse. Ratio 1.087, Holm p < 0.001
H4Gaussian kernel vs nearest neighboursBetter. Ratio 0.953, Holm p < 10⁻⁶
H5Gradient-boosted trees vs HARWorse. Ratio 1.42
H6Hawkes vs the original Poisson crash gateBetter. Log-loss ratio 0.85
H7Analogue/FHS blend vs FHS for VaR/ESNo significant difference
H8Volatility targeting vs buy & holdLower drawdown on 15/15 assets
Three dot plots of per-series log QLIKE ratios for development and confirmatory series: Analogue+HAR vs HAR centred on zero, Analogue vs HAR above zero, and kernel vs kNN below zero.
Each dot is one series. Left of the dotted line means the first model had lower loss. From results/figures.

On its own, the analogue model is a decent volatility forecaster but not better than HAR, the standard benchmark. Averaged with HAR it matches HAR. The parts that clearly hold up are the kernel variant, the Hawkes tail gate, and volatility targeting for drawdowns. For targeting, the median drawdown fell by 5.6 percentage points while the Sharpe ratio fell slightly (median −0.015) (e5_overlay).

The robustness checks in the README (dividend-adjusted prices, automatic bootstrap block lengths, rolling HAR, 5-minute realised variance for crypto) don't change any headline result.

Using it

To see it run without installing anything, try the demo: pick any day of S&P 500 history since 1932 and the page finds its analogues, on the paper's data, in your browser.

Install

It isn't on PyPI yet, so install from source. You'll need a Rust toolchain.

pip install git+https://github.com/ManasDasri/analogue-risk

A volatility forecast from hourly Bitcoin bars:

from analogue_risk import Analogue, volatility_forecast
from analogue_risk.data import binance

# open/high/low/close DataFrame, then next-day variance
prices = binance("BTCUSDT", "1h")
vf = volatility_forecast(prices, horizon=24)
print(vf.tail())

# the general engine: any causal features, any targets
model = Analogue(horizon=5, k=20)
F = model.forecast(embedding, targets, state=regime)
# the analogues behind each forecast
idx, w = model.neighbours(embedding, targets, state=regime)

The core is parallel Rust. With the history capped at 5,000 bars it runs at about 30,000 bars a second on 10 cores. A full search over 200,000 bars takes about 90 seconds (e7_speed). The API reference and three executed tutorial notebooks cover the rest.

Reproduce the paper

Every series in the paper is pinned by its last bar, row count and a SHA-256 of the cleaned data, so a fresh download either reproduces the published numbers or warns you that the source has changed.

git clone https://github.com/ManasDasri/analogue-risk
cd analogue-risk
uv venv --python 3.12
uv pip install maturin numpy pandas scipy matplotlib \
  scikit-learn tabulate pytest
.venv/bin/maturin develop --release
.venv/bin/python -m pytest tests
# development tables -> results/ (about 35 min on an M4)
.venv/bin/python -m analogue_risk.experiments
.venv/bin/python -m analogue_risk.hypotheses results/confirmatory

Limitations

Papers and citation

Two manuscripts are in preparation: a research paper and a software paper for SoftwareX. Read them here, or download them.

100% Download Open

The paper loads when you scroll here.

If you use the code, cite it with CITATION.cff (GitHub's "Cite this repository" button reads it).