OPEN-SOURCE SCRIPT
Mis à jour

AI Regime Detection

471
AI Regime Detection
Markov Regime Switching · 4-State Hidden Markov Model · Online Learning · Pine Script v6
This indicator uses a genuine machine learning model — a 4-state Hidden Markov Model with online learning — to classify the market into one of four regimes in real time: Bull Trend, Bear Trend, Ranging, and High Volatility. Instead of a binary “trend/no-trend” signal, it outputs a full probability distribution over all four regimes every bar, together with a confidence score, a live statistics dashboard, and the learned transition matrix.
Knowing the current regime is arguably the most important context in trading: trend-following systems bleed in ranging markets, mean-reversion systems get destroyed in strong trends, and position sizing should shrink when volatility explodes. This tool answers the question “what kind of market am I in right now — and how sure can I be?” using a probabilistic framework rather than fixed thresholds.
snapshot
How It Works
The engine is a Markov Regime Switching model processed with Bayesian forward filtering (Hamilton filter) on every bar:
Four bounded, scale-free features are extracted each bar: trend correlation (price vs. time, −1 to +1), RSI-based momentum, volatility percentile rank, and Sharpe-normalized drift. Because all features are bounded and scale-free, the model behaves consistently across any symbol and timeframe — no re-tuning needed between a large-cap stock and a crypto pair.
Each regime is defined by an emission template describing what its features typically look like (e.g. Bull Trend expects positive trend correlation and positive drift; High Volatility expects a top-decile volatility percentile).
Every bar, the model computes the likelihood of the observed features under each regime using a Lorentzian kernel (fat-tailed, robust to outliers — the same distance philosophy popularized by Lorentzian Classification) or a Gaussian kernel, then updates the posterior probabilities through the Markov transition matrix.
Online learning (approximate online EM): the transition matrix and the emission means are continuously updated from the data itself, with a learning-rate control. The model adapts to the statistical personality of each symbol instead of staying frozen at its priors. Regularization (diagonal cap, off-diagonal floor, template anchoring) prevents the two classic HMM failure modes: regime lock-in and label switching.
The regime with the highest posterior probability becomes the detected regime; its probability is the confidence score. The filtering is strictly causal — only past and current bars are used, and regime-change labels are drawn on confirmed bars only, so the tool does not repaint.
The model was validated on Monte Carlo simulations with known ground-truth regimes (drift processes for trends, mean-reverting Ornstein–Uhlenbeck processes for ranges and volatility shocks) before release.
Features
Real-time regime classification: Bull Trend ▲, Bear Trend ▼, Ranging ◆, High Volatility ⚡
Full posterior probability for all four regimes every bar, not just a single label
Confidence score (0–100%) with visual probability bars
Chart background tinted by regime, opacity scaled by confidence
Non-repainting regime-change labels printed on the price chart
Confidence & probability oscillator pane with reference levels (uniform prior 25%, high-confidence 80%)
Statistics dashboard: current volatility & its percentile, trend correlation, regime age, average regime duration, average return per bar inside the current regime, total regime switches, time distribution across regimes
Live learned transition matrix (4×4) — see the actual switching probabilities the model has learned for your symbol
Next likely regime — the most probable transition out of the current regime
Long-run π — the stationary distribution: the share of time each regime is expected to occupy in the long run
Choice of Lorentzian (robust) or Gaussian emission kernel
5 built-in alerts: any regime change + one per specific regime
Settings
Model — Markov Regime Switching
Regime persistence (prior): initial probability of staying in the same regime bar-to-bar. Higher = smoother, fewer switches; lower = more reactive.
Learning rate — transition matrix: how fast the switching probabilities adapt to the symbol. 0 disables adaptation.
Learning rate — emission: how fast regime feature profiles adapt. 0 disables adaptation.
Online learning (adaptive): master switch for all learning; off = fixed prior model.
Emission kernel: Lorentzian (robust, default) or Gaussian.
Features
Trend correlation length: window for the price-vs-time correlation trend measure.
RSI momentum length: period of the momentum feature.
Realized volatility length: window for realized volatility.
Volatility percentile window: lookback used to rank current volatility (also the warm-up length).
Drift smoothing length: smoothing window for the normalized drift feature.
Appearance
Toggles for background coloring, dashboard, regime-change labels, and transition matrix rows.
Dashboard position & text size.
Custom colors for each of the four regimes.
Usage
snapshot
When the model detects a Bull Trend regime with high confidence, the background turns green and a label marks the transition bar. This is the environment where trend-following entries, pyramiding, and letting winners run have a statistical tailwind. The confidence reading matters: an 85% Bull reading and a 45% Bull reading are very different market states — the dashboard’s probability bars show how much weight the competing regimes still hold.
snapshot
In a Ranging regime, the probability pane typically shows the blue Ranging line dominating while trend probabilities stay suppressed. This is where breakout trades fail most often and mean-reversion (fading moves back toward the middle of the range) performs best. A falling confidence during a mature trend regime often precedes the transition into Ranging — watch the oscillator pane for the crossover of probability lines.
snapshot
The High Volatility regime fires when volatility jumps into its top percentiles regardless of direction. This regime is a risk filter first and foremost: reduce position size, widen stops, or stand aside. High Vol regimes frequently appear at capitulation lows and blow-off tops, so their resolution (which regime follows) is informative — the “NEXT LIKELY” row of the dashboard shows the model’s learned expectation.
snapshot
The dashboard is the statistical summary of everything the model knows. The transition matrix rows read left-to-right as “from the row’s regime, probability of moving to ▲ ▼ ◆ ⚡”. A learned matrix with strong diagonals means the symbol has persistent, tradable regimes; weak diagonals mean choppy regime behavior — itself useful information for strategy selection. LONG-RUN π tells you the personality of the instrument (e.g. an index that spends 60% of its time trending vs. a pair that ranges 70% of the time). Ø RET/BAR shows the realized average return per bar inside the current regime on this chart — a quick sanity check that the regime labels align with actual profitability.
snapshot
The lower pane plots confidence as a colored area (colored by the ruling regime) plus all four probability lines. Regime transitions appear as probability crossovers, and the 80% dotted line marks the high-confidence zone. Time spent below ~45% confidence indicates a contested, transitional market — a reasonable filter for standing aside.
Details for the Curious
The Hamilton filter recursion is αₜ(j) ∝ bⱼ(oₜ) · Σᵢ αₜ₋₁(i) · A[j], normalized each bar, where bⱼ is the emission likelihood and A the transition matrix.
Transition-matrix learning uses an exponentially weighted update toward the per-bar posterior transition distribution, weighted by the previous state probability — an O(1) approximation of online Baum–Welch.
Emission means are updated toward observed features weighted by the state posterior, with an anchor term pulling back toward the initial templates to keep regime identities stable.
The warm-up period equals the volatility percentile window (default 300 bars). On symbols with short history, reduce this input.
Limitations & Honest Notes
Per-bar classification of noisy financial data has an information-theoretic ceiling; expect occasional flicker near regime boundaries and during genuinely ambiguous markets. The persistence prior and confidence threshold are the tools to manage this.
Probabilities are model outputs, not guarantees. A regime model describes the statistical character of recent price action; it does not predict news, gaps, or structural breaks.
This is a context / filter tool, not a standalone entry-exit system. It is designed to tell you which strategy the current market rewards, not to replace one.
Conclusion
AI Regime Detection brings a real, transparent machine learning pipeline — Hidden Markov Model, Bayesian filtering, Lorentzian likelihoods, and online EM adaptation — natively into Pine Script, with every internal state (probabilities, transition matrix, stationary distribution) exposed on the chart instead of hidden behind a black box. Use it to align your strategy with the market’s current regime and to size risk with the model’s own confidence.

Notes de version
v1.1 — Rebuilt the emission engine in log-space (fixes the Gaussian kernel producing empty output on low-timeframe charts) and added jump-penalty decoding with likelihood tempering (τ) for more persistent regimes and better-calibrated confidence. The statistics dashboard now anchors to the top-right of the main chart, and the bottom confidence pane can be fully toggled on/off in Settings.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.