OPEN-SOURCE SCRIPT
Advanced HMM - 3 States Complete

Hidden Markov Model
Aconsistent challenge for quantitative traders is the frequent behaviour modification of financial
markets, often abruptly, due to changing periods of government policy, regulatory environment
and other macroeconomic effects. Such periods are known as market regimes. Detecting such
changes is a common, albeit difficult, process undertaken by quantitative market participants.
These various regimes lead to adjustments of asset returns via shifts in their means, variances,
autocorrelation and covariances. This impacts the effectiveness of time series methods that rely
on stationarity. In particular it can lead to dynamically-varying correlation, excess kurtosis ("fat
tails"), heteroskedasticity (volatility clustering) and skewed returns.
There is a clear need to effectively detect these regimes. This aids optimal deployment of
quantitative trading strategies and tuning the parameters within them. The modeling task then
becomes an attempt to identify when a new regime has occurred adjusting strategy deployment,
risk management and position sizing criteria accordingly.
A principal method for carrying out regime detection is to use a statistical time series tech
nique known as a Hidden Markov Model[5]. These models are well-suited to the task since they
involve inference on "hidden" generative processes via "noisy" indirect observations correlated
to these processes. In this instance the hidden, or latent, process is the underlying regime state,
while the asset returns are the indirect noisy observations that are influenced by these states.
MAIN FEATURES OF THE INDICATOR
The "Advanced HMM - 3 States Complete" indicator is an advanced technical analysis tool that uses Hidden Markov Model (HMM) to identify three main market regimes: BULL, BEAR, and SIDEWAYS.
🎯 KEY FEATURES:
1. HMM-based Trend Detection
3 market states: Bull (0), Bear (1), Sideways (2)
Dynamic probabilities: Calculates probability for each state based on price data
Transition matrix: Models state transitions between regimes
2. Analytical Features
Price volatility: Log returns and standard deviation
Momentum: Rate of Change (ROC)
Volume: Volume ratio vs moving average
Data normalization: Standardizes features to common scale
3. Visual Trading Signals
text
📍 BUY Signals:
- Green upward triangle below bars
- "LONG" label in green
📍 SELL Signals:
- Red downward triangle above bars
- "SHORT" label in red
📍 EXIT Signals:
- Orange X marks when transitioning to sideways
4. Information Display
Probability table (top-right): Shows percentage for each state
State label: Current regime with probability percentages
Chart background color: Reflects dominant market state
5. Automated Alerts
Alerts when new Bull/Bear market detected
Alerts when market transitions to sideways
Configurable TradingView notifications
6. Customizable Parameters
pinescript
length: 100 // Lookback period
smoothing_period: 20 // Probability smoothing
volatility_threshold: 0.5 // Volatility threshold
💡 PRACTICAL APPLICATIONS:
Identify primary trends with quantified probabilities
Entry/exit signals based on state transitions
Risk management during sideways markets
Trend confirmation when combined with other indicators
This indicator is particularly useful for market regime analysis and identifying trend transition points using advanced statistical probability methods.
🔧 TECHNICAL IMPLEMENTATION:
Composite observation: Weighted combination of returns (40%), momentum (30%), and volatility (30%)
Gaussian emission probabilities: Different distributions for each state
Manual HMM updates: Avoids matrix computation limitations in Pine Script
Real-time smoothing: EMA applied to state probabilities
The indicator provides institutional-grade regime detection in a visually intuitive package suitable for both discretionary and systematic traders.
Aconsistent challenge for quantitative traders is the frequent behaviour modification of financial
markets, often abruptly, due to changing periods of government policy, regulatory environment
and other macroeconomic effects. Such periods are known as market regimes. Detecting such
changes is a common, albeit difficult, process undertaken by quantitative market participants.
These various regimes lead to adjustments of asset returns via shifts in their means, variances,
autocorrelation and covariances. This impacts the effectiveness of time series methods that rely
on stationarity. In particular it can lead to dynamically-varying correlation, excess kurtosis ("fat
tails"), heteroskedasticity (volatility clustering) and skewed returns.
There is a clear need to effectively detect these regimes. This aids optimal deployment of
quantitative trading strategies and tuning the parameters within them. The modeling task then
becomes an attempt to identify when a new regime has occurred adjusting strategy deployment,
risk management and position sizing criteria accordingly.
A principal method for carrying out regime detection is to use a statistical time series tech
nique known as a Hidden Markov Model[5]. These models are well-suited to the task since they
involve inference on "hidden" generative processes via "noisy" indirect observations correlated
to these processes. In this instance the hidden, or latent, process is the underlying regime state,
while the asset returns are the indirect noisy observations that are influenced by these states.
MAIN FEATURES OF THE INDICATOR
The "Advanced HMM - 3 States Complete" indicator is an advanced technical analysis tool that uses Hidden Markov Model (HMM) to identify three main market regimes: BULL, BEAR, and SIDEWAYS.
🎯 KEY FEATURES:
1. HMM-based Trend Detection
3 market states: Bull (0), Bear (1), Sideways (2)
Dynamic probabilities: Calculates probability for each state based on price data
Transition matrix: Models state transitions between regimes
2. Analytical Features
Price volatility: Log returns and standard deviation
Momentum: Rate of Change (ROC)
Volume: Volume ratio vs moving average
Data normalization: Standardizes features to common scale
3. Visual Trading Signals
text
📍 BUY Signals:
- Green upward triangle below bars
- "LONG" label in green
📍 SELL Signals:
- Red downward triangle above bars
- "SHORT" label in red
📍 EXIT Signals:
- Orange X marks when transitioning to sideways
4. Information Display
Probability table (top-right): Shows percentage for each state
State label: Current regime with probability percentages
Chart background color: Reflects dominant market state
5. Automated Alerts
Alerts when new Bull/Bear market detected
Alerts when market transitions to sideways
Configurable TradingView notifications
6. Customizable Parameters
pinescript
length: 100 // Lookback period
smoothing_period: 20 // Probability smoothing
volatility_threshold: 0.5 // Volatility threshold
💡 PRACTICAL APPLICATIONS:
Identify primary trends with quantified probabilities
Entry/exit signals based on state transitions
Risk management during sideways markets
Trend confirmation when combined with other indicators
This indicator is particularly useful for market regime analysis and identifying trend transition points using advanced statistical probability methods.
🔧 TECHNICAL IMPLEMENTATION:
Composite observation: Weighted combination of returns (40%), momentum (30%), and volatility (30%)
Gaussian emission probabilities: Different distributions for each state
Manual HMM updates: Avoids matrix computation limitations in Pine Script
Real-time smoothing: EMA applied to state probabilities
The indicator provides institutional-grade regime detection in a visually intuitive package suitable for both discretionary and systematic traders.
开源脚本
本着TradingView的真正精神,此脚本的创建者将其开源,以便交易者可以查看和验证其功能。向作者致敬!虽然您可以免费使用它,但请记住,重新发布代码必须遵守我们的网站规则。
免责声明
这些信息和出版物并不意味着也不构成TradingView提供或认可的金融、投资、交易或其它类型的建议或背书。请在使用条款阅读更多信息。
开源脚本
本着TradingView的真正精神,此脚本的创建者将其开源,以便交易者可以查看和验证其功能。向作者致敬!虽然您可以免费使用它,但请记住,重新发布代码必须遵守我们的网站规则。
免责声明
这些信息和出版物并不意味着也不构成TradingView提供或认可的金融、投资、交易或其它类型的建议或背书。请在使用条款阅读更多信息。