OPEN-SOURCE SCRIPT
Probability Horizon - Bayesian SVJD Model

# Probability Horizon — Bayesian SVJD Model
## What it does
Probability Horizon is a forward-looking probability projection tool. It does **not** generate buy or sell signals, does **not** act as a strategy, and does **not** place orders. Its single purpose is to display, at each bar, where price **may** be over a user-set horizon, drawn as a forward cone with three percentile lines (25%, 50%, 75%) plus an 8-row diagnostic dashboard.
The cone is the visual answer to two questions the indicator computes every bar:
1. **How wide should the distribution of forward outcomes be?** — set by expected total variance over the horizon.
2. **Should the distribution tilt up or down?** — set by a Bayesian-averaged probability of an up-move.
The wider the cone, the more uncertain the model is. The more the cone tilts, the more directionally confident the model is. A flat, narrow cone means "I expect range-bound, low-vol conditions." A wide, steeply tilted cone means "I expect a directional move under elevated variance."
## Why these components are combined (justification for the mashup)
This script combines several quantitative methods — KAMA, z-score, Haar wavelet, Kalman filter, Hamilton regime-switching, Hawkes process, Heston stochastic volatility, Merton jump-diffusion, Bayesian model averaging, and a calibration tracker. To a reviewer this can look like a collection of indicators bolted together, but it is not. It is **one** statistical model — a Stochastic Volatility Jump-Diffusion (SVJD) framework — whose pieces are mathematically required to produce a forward probability distribution.
Each component has a specific structural role:
- **Forward variance estimation.** A probability cone needs a forward-variance number. The naive choice is realized volatility × √horizon (pure Brownian motion), but this ignores two well-documented facts about financial returns: variance is mean-reverting (Heston, 1993) and returns have fat tails from discrete jumps (Merton, 1976). The Heston + jump-diffusion combination addresses both. The script uses the Heston integrated-variance closed form for the mean-reverting diffusion component, adds a Merton jump-variance contribution, and optionally adds a vol-of-vol uncertainty term. The result is a horizon-dependent variance estimate that dynamically narrows when volatility is elevated (expected to decay back to mean) and widens when volatility is depressed (expected to rise).
- **Directional probability.** To tilt the cone, a probability of direction is required. A single signal is unreliable, so five orthogonal sub-models each output their own P(up):
- A short-term KAMA-trend model
- A z-score mean-reversion model
- A Haar wavelet decomposition model (price denoised into trend + cycle + noise; signal fires only on the trend band)
- A Kalman-adaptive smoothing model (smoothing factor adapts to noise level in real time)
- A Hamilton 3-state regime model with Gaussian observation likelihoods (Bull / Bear / Range)
- **Sub-model combination.** The five P(up) values are combined via Bayesian model averaging with online weight updates. Each bar, after a fixed evaluation horizon, every sub-model is scored by log-loss against the actual outcome. Weights update via exponential decay: a model that predicted correctly gains weight; a model that failed loses weight. A minimum weight floor prevents any model from being silenced completely, so it can recover if its regime returns. Weights are renormalised to sum to 1.
- **Crisis dampening.** A Hawkes self-exciting point process monitors volatility clustering. Each large absolute return is treated as an event that boosts the process's intensity by α and decays exponentially at rate β. When intensity rises above a threshold multiple of its baseline, the final Bayesian probability is shrunk toward 0.5 — the higher the intensity, the stronger the shrinkage. This is how the model says "I have no idea — treat this as a coin flip" during regime breaks.
- **Self-correcting calibration.** A calibration tracker logs every prediction and checks the realized outcome after a fixed horizon. Predictions are binned by predicted probability (50–60%, 60–70%, etc.). If a bin's actual historical hit rate is below its predicted midpoint, future predictions in that bin are shrunk further toward 0.5. This is the model's honesty mechanism: it learns from its own miscalibration and tones itself down where it has been overconfident.
Each component answers a specific structural question. Remove any one and a specific capability disappears: no Heston → cone width does not adapt to vol regime; no calibration → no self-correction; no Hawkes → no crisis dampening; no Bayesian averaging → one model dominates and the system becomes brittle.
## How the components interact (data flow)
Every confirmed bar, the script executes the following pipeline:
1. **Measure** five raw market dimensions: KAMA slope, z-score vs trend, realized-vol percentile, OBV/price divergence, higher-TF trend.
2. **Each sub-model** maps its directional bias and strength to a probability in [0.40, 0.60]. The maximum single-model probability is capped at 0.60 because empirical calibration on multiple markets showed that anything higher is overconfident.
3. **Bayesian model averaging** combines the five sub-model probabilities into a single raw P(up), weighted by each sub-model's recent log-loss accuracy.
4. **Hawkes modifier** is applied: if intensity is above its warning threshold, the raw P(up) is pulled toward 0.5 in proportion to how far above threshold the intensity is.
5. **Calibration shrinkage** is applied: the post-Hawkes probability is checked against its calibration bin's historical hit rate, and shrunk further toward 0.5 if that bin has been overconfident.
6. **Forward variance** is computed separately: Heston integrated variance + Merton jump variance + optional vol-of-vol uncertainty, all over the projection horizon.
7. **The cone is drawn** with width set by the square root of forward variance and tilt set by the final shrunk probability. Three percentile lines (P25, P50, P75) are plotted from the current bar to the horizon endpoint.
Direction (sub-model probabilities → Bayesian average → Hawkes modifier → calibration shrinkage) is one half of the pipeline. Variance (Heston + jumps + vol-of-vol) is the other half. They meet at the cone, where one determines tilt and the other determines width.
## How to use it
**On the chart.** The cone shows the model's current view of the forward distribution. The P50 line is the median expected level given the implied drift. The P25 and P75 lines bracket the interquartile range. If P25 and P75 are roughly equidistant from current price, the model has no strong directional view; if the cone tilts noticeably up or down, the Bayesian probability favours that direction. A wider cone means more uncertainty; a narrower cone means tighter forward variance.
**The optional Monte Carlo cloud** (off by default) overlays bootstrap-resampled forward paths drawn from the asset's actual recent returns. Unlike the cone, it makes no Gaussian assumption — it shows the empirical distribution of forward outcomes given the asset's own recent return history.
**The 8-row dashboard** (top-right) is where the model exposes its full state:
- **Row 1 — Verdict.** Current direction (Bull / Bear / Neutral) and final P(up) percentage.
- **Row 2 — Direction.** A 10-character probability bar plus the size of the calibration shrinkage applied in percentage points.
- **Row 3 — 5 Models.** Up/down icons for each sub-model and the agreement count (e.g., "4/5 agree"). Trust the verdict more when 4 or 5 of 5 agree; trust it less when only 3 of 5 agree.
- **Row 4 — Regime.** Combined market regime (Quiet Bull / Quiet Bear / Volatile-Range / Crisis) plus the Hamilton dominant state.
- **Row 5 — Vol.** Volatility state vs long-run mean: HIGH (above mean, cone narrowing as vol decays), LOW (below mean, cone widening as vol rises), or AT MEAN. Includes the current sigma.
- **Row 6 — Risk.** Hawkes status: ✓ calm or ⚠ CRISIS. When CRISIS fires, the probability has been shrunk toward 0.5.
- **Row 7 — Honesty.** This is the most important diagnostic. It shows the actual historical hit rate for predictions in the 50–60% probability bin, with a Wilson confidence interval. If the system has predicted 55% many times and the actual rate is 53–58%, it is well-calibrated. If actual is below 50%, the system is currently overconfident and shrinkage is active.
- **Row 8 — Samples.** Total confirmed predictions and a trust level (low / warm-up / OK). Trust the cone less when total samples are below 50; trust it most when samples exceed 200.
## Suitable timeframes
The script auto-scales internal lookbacks to the chart timeframe relative to a 15-minute reference, so the same defaults work across 15-minute, 1-hour, 4-hour, and daily charts without manual tuning. Below 15 minutes the Hamilton 3-state model is automatically disabled because sample sizes become too small for reliable likelihood estimation; the other four sub-models continue to operate.
## What is original
Combining KAMA, wavelets, Kalman, Hamilton, Heston, Merton jumps, and a Hawkes process is not by itself new — these are all published methods. The original aspects of this script are:
- The **specific combination**: a five-model Bayesian ensemble for direction, with Hawkes-process crisis dampening and a self-correcting calibration tracker, all wrapped around a Heston + jump-diffusion variance estimate. I am not aware of a public Pine Script that combines all of these into a single probability cone with this data flow.
- The **calibration shrinkage mechanism**: the model logs every prediction, scores it after a fixed horizon, and applies bin-specific shrinkage to future predictions in bins where it has been overconfident. This is a self-correcting honesty layer that runs entirely on-chart, with Wilson confidence intervals and optional regime-specific calibration tables (Bull / Bear / Range).
- The **transparent diagnostic dashboard**: rather than hiding the model behind a single line, the dashboard exposes the verdict, model agreement, regime, vol state, crisis indicator, calibration quality, and sample size in eight rows. Users can see at a glance not only what the model thinks, but how much to trust it.
## Limitations (please read)
- **Pine Script cannot perform true maximum-likelihood estimation.** Heston and jump-diffusion parameters are estimated using approximation methods (AR(1) regression on log-variance, exponential moving averages for jump moments, rolling averages for long-term variance). The directional behaviour is correct — when vol is high, the cone narrows; when jumps are frequent, the cone widens — but exact parameter values are not equivalent to those a quantitative research desk would produce with MLE on tick data.
- **OHLCV data only.** No order-book data, no alternative-data feed, no options input, no fundamental input.
- **Calibration needs sample accumulation.** The Honesty row shows "warming up" until at least ~30 confirmed predictions have matured. Pine has no cross-session persistence, so calibration is rebuilt from chart history each time the indicator loads on a new chart.
- **Monte Carlo is deterministic.** Paths use a Linear Congruential Generator seeded by bar_index for reproducibility within a session. The same chart at the same moment produces the same cloud. This is intentional.
- **This is a probability indicator, not a strategy.** There are no backtest results, no equity curve, no position management. The script cannot tell you what to do; it only tells you what its model currently thinks the distribution of forward outcomes is.
- **Past calibration does not guarantee future calibration.** Market regimes change, parameters drift, and the cone should be treated as a visualisation aid rather than a prediction.
## Inputs of note
The defaults work without modification on most liquid instruments at most timeframes. Inputs worth knowing:
- **Auto-scale lookbacks** (on by default) — keeps the same defaults usable across timeframes.
- **Bayesian learning rate η** (default 0.15) — how fast sub-model weights adapt. Higher = faster but noisier.
- **Min Bayesian Probability** (default 0.62) — the threshold the dashboard uses to call a bar "Bull" or "Bear" rather than "Neutral".
- **Heston κ floor / ceiling** — bounds the mean-reversion-speed estimate. Defaults (0.02 to 0.30) handle most markets.
- **Hawkes warning threshold** (default 2.0× baseline) — when crisis dampening kicks in.
- **Monte Carlo Cloud** (off by default) — overlays bootstrap paths. Turn on if you want an empirical (non-Gaussian) view of forward outcomes alongside the cone.
## Disclaimer
This script is published for educational and analytical purposes only. It does not constitute financial advice, investment advice, a recommendation to buy or sell any financial instrument, or a solicitation of any transaction. The author is not a registered investment adviser and nothing in this script should be construed as personalised investment guidance.
Past performance does not guarantee future results. The probability projections shown by this indicator are model outputs, not forecasts of what will actually happen. Trading and investing involve substantial risk of loss and are not suitable for every investor. Users are solely responsible for their own trading decisions and for verifying that any approach is appropriate for their personal financial situation, risk tolerance, and applicable regulations.
The author and Market_Logic_India accept no liability for any losses, damages, or trading outcomes resulting from the use, misuse, or interpretation of this script. Use at your own risk.
## What it does
Probability Horizon is a forward-looking probability projection tool. It does **not** generate buy or sell signals, does **not** act as a strategy, and does **not** place orders. Its single purpose is to display, at each bar, where price **may** be over a user-set horizon, drawn as a forward cone with three percentile lines (25%, 50%, 75%) plus an 8-row diagnostic dashboard.
The cone is the visual answer to two questions the indicator computes every bar:
1. **How wide should the distribution of forward outcomes be?** — set by expected total variance over the horizon.
2. **Should the distribution tilt up or down?** — set by a Bayesian-averaged probability of an up-move.
The wider the cone, the more uncertain the model is. The more the cone tilts, the more directionally confident the model is. A flat, narrow cone means "I expect range-bound, low-vol conditions." A wide, steeply tilted cone means "I expect a directional move under elevated variance."
## Why these components are combined (justification for the mashup)
This script combines several quantitative methods — KAMA, z-score, Haar wavelet, Kalman filter, Hamilton regime-switching, Hawkes process, Heston stochastic volatility, Merton jump-diffusion, Bayesian model averaging, and a calibration tracker. To a reviewer this can look like a collection of indicators bolted together, but it is not. It is **one** statistical model — a Stochastic Volatility Jump-Diffusion (SVJD) framework — whose pieces are mathematically required to produce a forward probability distribution.
Each component has a specific structural role:
- **Forward variance estimation.** A probability cone needs a forward-variance number. The naive choice is realized volatility × √horizon (pure Brownian motion), but this ignores two well-documented facts about financial returns: variance is mean-reverting (Heston, 1993) and returns have fat tails from discrete jumps (Merton, 1976). The Heston + jump-diffusion combination addresses both. The script uses the Heston integrated-variance closed form for the mean-reverting diffusion component, adds a Merton jump-variance contribution, and optionally adds a vol-of-vol uncertainty term. The result is a horizon-dependent variance estimate that dynamically narrows when volatility is elevated (expected to decay back to mean) and widens when volatility is depressed (expected to rise).
- **Directional probability.** To tilt the cone, a probability of direction is required. A single signal is unreliable, so five orthogonal sub-models each output their own P(up):
- A short-term KAMA-trend model
- A z-score mean-reversion model
- A Haar wavelet decomposition model (price denoised into trend + cycle + noise; signal fires only on the trend band)
- A Kalman-adaptive smoothing model (smoothing factor adapts to noise level in real time)
- A Hamilton 3-state regime model with Gaussian observation likelihoods (Bull / Bear / Range)
- **Sub-model combination.** The five P(up) values are combined via Bayesian model averaging with online weight updates. Each bar, after a fixed evaluation horizon, every sub-model is scored by log-loss against the actual outcome. Weights update via exponential decay: a model that predicted correctly gains weight; a model that failed loses weight. A minimum weight floor prevents any model from being silenced completely, so it can recover if its regime returns. Weights are renormalised to sum to 1.
- **Crisis dampening.** A Hawkes self-exciting point process monitors volatility clustering. Each large absolute return is treated as an event that boosts the process's intensity by α and decays exponentially at rate β. When intensity rises above a threshold multiple of its baseline, the final Bayesian probability is shrunk toward 0.5 — the higher the intensity, the stronger the shrinkage. This is how the model says "I have no idea — treat this as a coin flip" during regime breaks.
- **Self-correcting calibration.** A calibration tracker logs every prediction and checks the realized outcome after a fixed horizon. Predictions are binned by predicted probability (50–60%, 60–70%, etc.). If a bin's actual historical hit rate is below its predicted midpoint, future predictions in that bin are shrunk further toward 0.5. This is the model's honesty mechanism: it learns from its own miscalibration and tones itself down where it has been overconfident.
Each component answers a specific structural question. Remove any one and a specific capability disappears: no Heston → cone width does not adapt to vol regime; no calibration → no self-correction; no Hawkes → no crisis dampening; no Bayesian averaging → one model dominates and the system becomes brittle.
## How the components interact (data flow)
Every confirmed bar, the script executes the following pipeline:
1. **Measure** five raw market dimensions: KAMA slope, z-score vs trend, realized-vol percentile, OBV/price divergence, higher-TF trend.
2. **Each sub-model** maps its directional bias and strength to a probability in [0.40, 0.60]. The maximum single-model probability is capped at 0.60 because empirical calibration on multiple markets showed that anything higher is overconfident.
3. **Bayesian model averaging** combines the five sub-model probabilities into a single raw P(up), weighted by each sub-model's recent log-loss accuracy.
4. **Hawkes modifier** is applied: if intensity is above its warning threshold, the raw P(up) is pulled toward 0.5 in proportion to how far above threshold the intensity is.
5. **Calibration shrinkage** is applied: the post-Hawkes probability is checked against its calibration bin's historical hit rate, and shrunk further toward 0.5 if that bin has been overconfident.
6. **Forward variance** is computed separately: Heston integrated variance + Merton jump variance + optional vol-of-vol uncertainty, all over the projection horizon.
7. **The cone is drawn** with width set by the square root of forward variance and tilt set by the final shrunk probability. Three percentile lines (P25, P50, P75) are plotted from the current bar to the horizon endpoint.
Direction (sub-model probabilities → Bayesian average → Hawkes modifier → calibration shrinkage) is one half of the pipeline. Variance (Heston + jumps + vol-of-vol) is the other half. They meet at the cone, where one determines tilt and the other determines width.
## How to use it
**On the chart.** The cone shows the model's current view of the forward distribution. The P50 line is the median expected level given the implied drift. The P25 and P75 lines bracket the interquartile range. If P25 and P75 are roughly equidistant from current price, the model has no strong directional view; if the cone tilts noticeably up or down, the Bayesian probability favours that direction. A wider cone means more uncertainty; a narrower cone means tighter forward variance.
**The optional Monte Carlo cloud** (off by default) overlays bootstrap-resampled forward paths drawn from the asset's actual recent returns. Unlike the cone, it makes no Gaussian assumption — it shows the empirical distribution of forward outcomes given the asset's own recent return history.
**The 8-row dashboard** (top-right) is where the model exposes its full state:
- **Row 1 — Verdict.** Current direction (Bull / Bear / Neutral) and final P(up) percentage.
- **Row 2 — Direction.** A 10-character probability bar plus the size of the calibration shrinkage applied in percentage points.
- **Row 3 — 5 Models.** Up/down icons for each sub-model and the agreement count (e.g., "4/5 agree"). Trust the verdict more when 4 or 5 of 5 agree; trust it less when only 3 of 5 agree.
- **Row 4 — Regime.** Combined market regime (Quiet Bull / Quiet Bear / Volatile-Range / Crisis) plus the Hamilton dominant state.
- **Row 5 — Vol.** Volatility state vs long-run mean: HIGH (above mean, cone narrowing as vol decays), LOW (below mean, cone widening as vol rises), or AT MEAN. Includes the current sigma.
- **Row 6 — Risk.** Hawkes status: ✓ calm or ⚠ CRISIS. When CRISIS fires, the probability has been shrunk toward 0.5.
- **Row 7 — Honesty.** This is the most important diagnostic. It shows the actual historical hit rate for predictions in the 50–60% probability bin, with a Wilson confidence interval. If the system has predicted 55% many times and the actual rate is 53–58%, it is well-calibrated. If actual is below 50%, the system is currently overconfident and shrinkage is active.
- **Row 8 — Samples.** Total confirmed predictions and a trust level (low / warm-up / OK). Trust the cone less when total samples are below 50; trust it most when samples exceed 200.
## Suitable timeframes
The script auto-scales internal lookbacks to the chart timeframe relative to a 15-minute reference, so the same defaults work across 15-minute, 1-hour, 4-hour, and daily charts without manual tuning. Below 15 minutes the Hamilton 3-state model is automatically disabled because sample sizes become too small for reliable likelihood estimation; the other four sub-models continue to operate.
## What is original
Combining KAMA, wavelets, Kalman, Hamilton, Heston, Merton jumps, and a Hawkes process is not by itself new — these are all published methods. The original aspects of this script are:
- The **specific combination**: a five-model Bayesian ensemble for direction, with Hawkes-process crisis dampening and a self-correcting calibration tracker, all wrapped around a Heston + jump-diffusion variance estimate. I am not aware of a public Pine Script that combines all of these into a single probability cone with this data flow.
- The **calibration shrinkage mechanism**: the model logs every prediction, scores it after a fixed horizon, and applies bin-specific shrinkage to future predictions in bins where it has been overconfident. This is a self-correcting honesty layer that runs entirely on-chart, with Wilson confidence intervals and optional regime-specific calibration tables (Bull / Bear / Range).
- The **transparent diagnostic dashboard**: rather than hiding the model behind a single line, the dashboard exposes the verdict, model agreement, regime, vol state, crisis indicator, calibration quality, and sample size in eight rows. Users can see at a glance not only what the model thinks, but how much to trust it.
## Limitations (please read)
- **Pine Script cannot perform true maximum-likelihood estimation.** Heston and jump-diffusion parameters are estimated using approximation methods (AR(1) regression on log-variance, exponential moving averages for jump moments, rolling averages for long-term variance). The directional behaviour is correct — when vol is high, the cone narrows; when jumps are frequent, the cone widens — but exact parameter values are not equivalent to those a quantitative research desk would produce with MLE on tick data.
- **OHLCV data only.** No order-book data, no alternative-data feed, no options input, no fundamental input.
- **Calibration needs sample accumulation.** The Honesty row shows "warming up" until at least ~30 confirmed predictions have matured. Pine has no cross-session persistence, so calibration is rebuilt from chart history each time the indicator loads on a new chart.
- **Monte Carlo is deterministic.** Paths use a Linear Congruential Generator seeded by bar_index for reproducibility within a session. The same chart at the same moment produces the same cloud. This is intentional.
- **This is a probability indicator, not a strategy.** There are no backtest results, no equity curve, no position management. The script cannot tell you what to do; it only tells you what its model currently thinks the distribution of forward outcomes is.
- **Past calibration does not guarantee future calibration.** Market regimes change, parameters drift, and the cone should be treated as a visualisation aid rather than a prediction.
## Inputs of note
The defaults work without modification on most liquid instruments at most timeframes. Inputs worth knowing:
- **Auto-scale lookbacks** (on by default) — keeps the same defaults usable across timeframes.
- **Bayesian learning rate η** (default 0.15) — how fast sub-model weights adapt. Higher = faster but noisier.
- **Min Bayesian Probability** (default 0.62) — the threshold the dashboard uses to call a bar "Bull" or "Bear" rather than "Neutral".
- **Heston κ floor / ceiling** — bounds the mean-reversion-speed estimate. Defaults (0.02 to 0.30) handle most markets.
- **Hawkes warning threshold** (default 2.0× baseline) — when crisis dampening kicks in.
- **Monte Carlo Cloud** (off by default) — overlays bootstrap paths. Turn on if you want an empirical (non-Gaussian) view of forward outcomes alongside the cone.
## Disclaimer
This script is published for educational and analytical purposes only. It does not constitute financial advice, investment advice, a recommendation to buy or sell any financial instrument, or a solicitation of any transaction. The author is not a registered investment adviser and nothing in this script should be construed as personalised investment guidance.
Past performance does not guarantee future results. The probability projections shown by this indicator are model outputs, not forecasts of what will actually happen. Trading and investing involve substantial risk of loss and are not suitable for every investor. Users are solely responsible for their own trading decisions and for verifying that any approach is appropriate for their personal financial situation, risk tolerance, and applicable regulations.
The author and Market_Logic_India accept no liability for any losses, damages, or trading outcomes resulting from the use, misuse, or interpretation of this script. Use at your own risk.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.