A hidden Markov model (HMM) is a statistical model that assumes the market moves between a few unobservable regimes, such as bullish, neutral and bearish, and that each regime produces returns with its own typical mean and volatility. In hidden Markov model trading, you fit the HMM to observable data like returns or rate of change, infer which regime the market is most likely in, and switch your strategy or exposure based on that regime.
Trading the financial markets can be challenging, especially when price movements are unpredictable. One of the techniques traders use to understand and anticipate market movements is the Hidden Markov Model (HMM). While this might sound like a complex statistical model, it’s actually a powerful tool for identifying hidden market conditions (or regimes) that can help inform your trading decisions. In this blog, we’ll introduce HMM, explain its importance in trading, and guide you through a practical example of implementing a Gaussian HMM strategy with Python.

- An HMM has two layers: hidden states (market regimes) and observations (returns, ROC) that each state generates.
- A Gaussian HMM assumes the observations in each state follow a normal distribution with its own mean and variance.
- hmmlearn numbers states arbitrarily. Rank them by their fitted mean before calling one “bullish”, or your signals can be reversed.
- Fitting and decoding on the full history uses future data. Use walk-forward fitting and the filtered (last-bar) state for honest backtests.
- HMMs work best on daily or weekly data as a regime filter, not as a stand-alone buy and sell signal generator.
What Is a Hidden Markov Model (HMM)?
At its core, an HMM is a model that helps you understand and predict systems that transition between different states, such as financial markets, where the future is uncertain. The “hidden” part of the model refers to the fact that these states are not directly observable, like whether the market is bullish, bearish, or neutral, but they can be inferred through data like price changes.
Think of the market as a state machine that can be in one of several states:
- Bullish (price is likely to go up),
- Bearish (price is likely to go down),
- Neutral (prices are moving sideways).
In HMM, each state generates observable data (e.g., daily stock prices or technical indicators). However, you cannot directly observe the state, whether the market is bullish, bearish, or neutral, you can only see the stock prices or indicators. The goal of the model is to infer the hidden state (market regime) based on observable data and predict how the market is likely to behave next.
The building blocks of an HMM
| Component | What it means in trading | In hmmlearn |
|---|---|---|
| Hidden states | Market regimes you cannot see directly | n_components |
| Start probabilities | How likely each regime is on day one | startprob_ |
| Transition matrix | Probability of moving from one regime to another tomorrow | transmat_ |
| Emission distribution | Mean and variance of returns in each regime | means_, covars_ |
| Fitting (Baum-Welch / EM) | Learns all of the above from data | model.fit() |
| Decoding (Viterbi) | Most likely sequence of regimes | model.predict() |
| Posterior probabilities | Probability of each regime at each bar | model.predict_proba() |
An HMM is defined by how likely the market is to stay in, or leave, each hidden regime. Move the sliders to see the average length of each regime and a simulated year.
Set how “sticky” each regime is: the probability that tomorrow stays in the same regime as today. The rest is split equally between the other two regimes.
The sliders show why the transition matrix matters: a staying probability of 0.98 means a regime lasts about 50 trading days on average (1 divided by 1 minus 0.98). After fitting, print model.transmat_: if the diagonal values are close to 1, the regimes are sticky and the model is useful as a filter; if they are near 0.5, the states are flipping almost daily and the signals will whipsaw.
Gaussian HMM Explained
Now, let’s dive into the Gaussian Hidden Markov Model (Gaussian HMM). In this case, the “Gaussian” part refers to a type of probability distribution that the model assumes for each hidden state. This means that for each market state (bullish, bearish, neutral), the model assumes that the price changes (or another market indicator) follow a normal distribution. This makes the model more suitable for financial time series data, which often exhibits trends and volatility.
How Does HMM Work in Trading?
Here’s how HMM is applied in a trading strategy:
- Data Observation: You collect observable data, such as stock prices or a technical indicator like the Rate of Change (ROC).
- Training the Model: The HMM model is trained on this data to identify hidden patterns, such as the likelihood that the market is in a bullish or bearish state.
- Prediction: The model predicts the hidden states (regimes) based on new data and identifies which regime the market is currently in.
- Decision Making: You can generate trading signals (buy, sell, hold) based on these hidden states. For example, if the model predicts the market is in a bullish state, you might decide to buy; if it predicts a bearish state, you might sell.
Why Should Traders Use Hidden Markov Models?
Identifying Market Regimes
One of the most important reasons to use an HMM is to help identify different market regimes. A market regime refers to the underlying conditions that drive market behavior, such as whether the market is in an uptrend (bullish), downtrend (bearish), or sideways movement (neutral). Since these conditions are often not immediately obvious, HMM helps infer them using historical data, giving traders a clearer sense of where the market might be heading.
Capturing Market Transitions
Markets don’t stay in one state forever. A bullish market may suddenly shift into a bearish one, or a sideways market may break out into a trend. HMM is effective at identifying these transitions and helps traders adjust their strategies accordingly, such as switching from a trend-following strategy to a mean-reversion strategy.
Statistical Approach to Market Noise
In financial markets, price movements are often noisy and random in the short term. HMM helps to cut through this noise by focusing on the hidden underlying states that drive the market, helping traders make more informed decisions rather than getting caught up in short-term price fluctuations.
Algorithmic and Systematic Trading
HMM is also useful for systematic traders who prefer to follow a more rules-based, data-driven approach. The model generates signals (buy/sell/hold) based on quantitative data, making it ideal for traders who are looking to automate their strategies and reduce emotional decision-making.
When Should Traders Use HMM?
Trend Identification
HMM is particularly useful in trend-following strategies. If your trading system relies on identifying when the market is in a strong uptrend or downtrend, HMM can help by identifying when these trends are likely to begin and end.
Volatile or Range-Bound Markets
If the market is highly volatile or moving sideways, HMM can help you avoid false signals by distinguishing between noise and real market movements. This can be particularly valuable for traders who are looking to avoid getting caught in “whipsaws” during choppy market conditions.
Switching Between Strategies
Many traders use different strategies for different market conditions. For instance, you might use a trend-following strategy in a bullish market and a mean-reversion strategy in a neutral or bearish market. HMM allows you to switch between strategies by predicting the underlying market regime.
Medium to Long-Term Trading
HMM works best with medium- to long-term data, such as daily or weekly stock prices. It’s less effective in very short-term or high-frequency trading due to the inherent randomness and noise in intraday price movements.
Practical Example: HMM in Python for Nifty 50 Trading Strategy
Now that we have an understanding of what HMM and Gaussian HMM are, let’s look at how you can apply them to trading with a practical Python example.
In this example, we’ll apply the HMM model to the Nifty 50 index, a major stock market index in India, using historical price data. The goal is to use HMM to predict different market regimes and generate buy/sell signals.
Building the HMM Trading Strategy Step-by-Step Implementation:
To make this practical, let’s walk through the steps of implementing an HMM-based trading strategy using Python. The steps involve fetching stock data, calculating the rate of change, fitting the HMM model to predict market regimes, and generating buy/sell signals.
PIP Install Commands
pip install yfinance pandas numpy hmmlearn plotly
Step 1: Fetching Intraday Data Using Yahoo Finance
We start by fetching historical data for a specific stock or index. Here, we’ll use the Nifty 50 index (^NSEI) and retrieve data for the past 10 years at daily intervals. For this, we use the yfinance library.
import yfinance as yf
from datetime import datetime, timedelta
def fetch_intraday_data(symbol, interval='1D', days=3650):
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
data = yf.download(symbol, start=start_date, end=end_date, interval=interval)
return data
The function fetch_intraday_data downloads the stock data for the given symbol and interval using Yahoo Finance’s API. In this case, we are interested in the Nifty 50 index, but you can easily replace this with any other stock or index symbol.
Step 2: Calculating the Rate of Change (ROC)
The next step is to calculate the Rate of Change (ROC), which measures the percentage change of the stock’s closing price over a given time window. The ROC is used as a feature for our HMM model to infer market regimes.
import pandas as pd
def calculate_roc(data, window=12):
return data['Close'].pct_change(periods=window)
The function calculate_roc calculates the percentage change of the stock’s closing price over the specified window (12 days in this example).
Step 3: Fitting the HMM and Predicting Market Regimes
With the ROC data, we now fit an HMM model to predict hidden states that represent different market regimes. We use the hmmlearn library, which provides tools for implementing HMMs.
from hmmlearn import hmm
import numpy as np
def fit_hmm_predict(data, n_components=3):
model = hmm.GaussianHMM(n_components=n_components, n_iter=20, random_state=42)
model.fit(np.array(data).reshape(-1, 1))
hidden_states = model.predict(np.array(data).reshape(-1, 1))
return pd.Series(hidden_states, index=data.index)
Here, we fit a Gaussian HMM model with three components, representing three possible market regimes (bullish, neutral, and bearish). The model is trained on the ROC data, and the hidden states are predicted. These hidden states help us understand the market conditions over time.
Step 4: Generating Trading Signals
Once we have the hidden states, we can generate trading signals based on these predictions:
- Buy when the regime is bullish.
- Sell when the regime is bearish.
- Do nothing in a neutral market.
def generate_signals(hidden_states):
signals = pd.Series(index=hidden_states.index, data=0)
signals[hidden_states == 2] = 1 # Buy signal for bullish state
signals[hidden_states == 0] = -1 # Sell signal for bearish state
return signals
In this strategy, we assume that state 2 (highest) is bullish, state 0 (lowest) is bearish, and state 1 is neutral. Based on these states, the function generate_signals generates corresponding buy (1) and sell (-1) signals.
Important: hmmlearn does not guarantee that state 2 has the highest mean. The labels 0, 1 and 2 are assigned during fitting and can come out in any order, and they can change if you change random_state or the data. Always check model.means_ and map the state with the highest mean to “bullish” in code. The updated script below does this automatically.
Step 5: Visualizing the Strategy
Visualization is an important part of any trading strategy. Using Plotly, we plot the stock’s closing price and overlay the buy and sell signals to better understand how the strategy performs over time.
import plotly.graph_objects as go
def plot_strategy(result):
fig = go.Figure()
# Add price line
fig.add_trace(go.Scatter(x=result.index, y=result['Close'], mode='lines', name='Nifty Close'))
# Add buy signals
buy_points = result[result['Signal'] == 1]
fig.add_trace(go.Scatter(x=buy_points.index, y=buy_points['Close'], mode='markers',
marker=dict(symbol='triangle-up', size=10, color='green'), name='Buy Signal'))
# Add sell signals
sell_points = result[result['Signal'] == -1]
fig.add_trace(go.Scatter(x=sell_points.index, y=sell_points['Close'], mode='markers',
marker=dict(symbol='triangle-down', size=10, color='red'), name='Sell Signal'))
fig.update_layout(
title='Nifty 50 HMM Strategy',
xaxis_title='Date',
yaxis_title='Price',
template='plotly_dark',
xaxis=dict(type='category')
)
fig.show()
Gaussian HMM Long Only Strategy – Full Python Code
import yfinance as yf
import pandas as pd
import numpy as np
from hmmlearn import hmm
import plotly.graph_objects as go
from datetime import datetime, timedelta
# Function to fetch intraday data
def fetch_intraday_data(symbol, interval='1D', days=3650):
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
data = yf.download(symbol, start=start_date, end=end_date, interval=interval)
return data
# Function to calculate rate of change
def calculate_roc(data, window=12):
return data['Close'].pct_change(periods=window)
# Function to fit HMM and predict regimes
def fit_hmm_predict(data, n_components=3):
model = hmm.GaussianHMM(n_components=n_components, n_iter=20, random_state=42)
model.fit(np.array(data).reshape(-1, 1))
hidden_states = model.predict(np.array(data).reshape(-1, 1))
return pd.Series(hidden_states, index=data.index)
# Function to generate trading signals
def generate_signals(hidden_states):
# Assuming state 2 is bullish, state 1 is neutral, and state 0 is bearish
signals = pd.Series(index=hidden_states.index, data=0)
signals[hidden_states == 2] = 1 # Buy signal for highest state
signals[hidden_states == 0] = -1 # Sell signal for lowest state
return signals
# Main function
def main():
# Fetch data
symbol = "^NSEI" # Nifty 50 index
data = fetch_intraday_data(symbol)
# Calculate ROC
roc = calculate_roc(data)
# Fit HMM and predict regimes
hidden_states = fit_hmm_predict(roc.dropna())
# Generate signals
signals = generate_signals(hidden_states)
# Create DataFrame with all necessary data
result = pd.DataFrame({
'Close': data['Close'],
'ROC': roc,
'Regime': hidden_states,
'Signal': signals
}).dropna()
# Visualize using Plotly
fig = go.Figure()
# Add price line
fig.add_trace(go.Scatter(x=result.index, y=result['Close'], mode='lines', name='Nifty Close'))
# Add buy signals
buy_points = result[result['Signal'] == 1]
fig.add_trace(go.Scatter(x=buy_points.index, y=buy_points['Close'], mode='markers',
marker=dict(symbol='triangle-up', size=10, color='green'), name='Buy Signal'))
# Add sell signals
sell_points = result[result['Signal'] == -1]
fig.add_trace(go.Scatter(x=sell_points.index, y=sell_points['Close'], mode='markers',
marker=dict(symbol='triangle-down', size=10, color='red'), name='Sell Signal'))
# Update layout with the new specifications
fig.update_layout(
title='Nifty 50 HMM Strategy',
xaxis_title='Date',
yaxis_title='Price',
template='plotly_dark',
xaxis=dict(type='category')
)
# Show the plot
fig.show()
# Print some statistics
print(f"Total data points: {len(result)}")
print(f"Buy signals: {len(buy_points)}")
print(f"Sell signals: {len(sell_points)}")
if __name__ == "__main__":
main()
Two problems in the original code (and how to fix them)
When I revisited this tutorial, two issues stood out that affect anyone who copies the code as is:
- Look-ahead bias. The model is fitted on the entire 10 years of ROC and then
predict()runs the Viterbi algorithm over the whole series. Viterbi uses future observations to decide the regime of past days, so the signals on the chart could not have been known at the time. The fix is to fit on past data only (walk-forward) and use the posterior probability of the last bar, which depends only on data up to that bar. Read more in understanding look-ahead bias. - Arbitrary state labels. As explained above, state 2 is not always the bullish state. The fix is to sort states by their fitted mean.
Newer yfinance versions (0.2.5x onwards) also return MultiIndex columns by default, so data['Close'] becomes a one-column DataFrame and the final pd.DataFrame({...}) call can fail. Passing multi_level_index=False to yf.download fixes that, and the daily interval should be written as "1d".
Updated version (2026): walk-forward hidden Markov model trading strategy
This version fits the HMM on an expanding window, refits every 63 trading days (about a quarter), labels states by their mean, takes the long position only on the bar after a bullish regime is detected, and compares the result with buy and hold. I tested it with hmmlearn 0.3.3 and yfinance 1.8 (on simulated data, because Yahoo rate-limits automated downloads).
pip install -U yfinance pandas numpy hmmlearn
import numpy as np
import pandas as pd
import yfinance as yf
from hmmlearn import hmm
def fetch_data(symbol="^NSEI", years=10):
# yfinance 0.2.5x+ returns MultiIndex columns by default; flatten them
data = yf.download(symbol, period=f"{years}y", interval="1d",
auto_adjust=True, multi_level_index=False, progress=False)
return data.dropna()
def fit_hmm(train, n_states=3, seed=42):
model = hmm.GaussianHMM(n_components=n_states, covariance_type="full",
n_iter=200, random_state=seed)
model.fit(train.reshape(-1, 1))
# hmmlearn numbers states arbitrarily, so rank them by their mean ROC:
# 0 = lowest mean (bearish) ... n_states-1 = highest mean (bullish)
order = np.argsort(model.means_.ravel())
rank = np.empty(n_states, dtype=int)
rank[order] = np.arange(n_states)
return model, rank
def walk_forward_regimes(roc, n_states=3, train_bars=750, refit_every=63):
"""Label each bar using only data available up to that bar (no look-ahead)."""
values = roc.values
regimes = pd.Series(np.nan, index=roc.index)
model, rank = None, None
for t in range(train_bars, len(values)):
if model is None or (t - train_bars) % refit_every == 0:
model, rank = fit_hmm(values[:t], n_states)
# filtered state of bar t: posterior of the last bar given data up to t
probs = model.predict_proba(values[: t + 1].reshape(-1, 1))[-1]
regimes.iloc[t] = rank[np.argmax(probs)]
return regimes
def backtest(close, regimes, bull_state):
position = (regimes == bull_state).astype(int)
position = position.shift(1).fillna(0) # act on the next bar, not the same bar
daily_ret = close.pct_change().fillna(0)
strat_ret = position * daily_ret
return pd.DataFrame({
"Close": close,
"Regime": regimes,
"Position": position,
"BuyHold": (1 + daily_ret).cumprod(),
"Strategy": (1 + strat_ret).cumprod(),
})
def main():
n_states = 3
data = fetch_data("^NSEI", years=10)
close = data["Close"]
roc = close.pct_change(12).dropna()
regimes = walk_forward_regimes(roc, n_states=n_states)
result = backtest(close.loc[roc.index], regimes, bull_state=n_states - 1).dropna()
print(result["Regime"].value_counts().sort_index())
print(f"Buy and hold: {result['BuyHold'].iloc[-1] / result['BuyHold'].iloc[0] - 1:.2%}")
print(f"HMM long only: {result['Strategy'].iloc[-1] / result['Strategy'].iloc[0] - 1:.2%}")
print(f"Time in market: {result['Position'].mean():.1%}")
if __name__ == "__main__":
main()
Expect the walk-forward result to look less impressive than the chart from the original code. That is the point: it is the result you could actually have traded. From here you can add features (volatility, volume, ROC over several windows), try two or four states, and compare against a simple moving average filter before trusting the model.
Limitations of hidden Markov model trading
- Regimes are detected late. The model needs a few bars of new behaviour before the posterior shifts, so it confirms regimes rather than predicting turns.
- The Gaussian assumption is a simplification. Equity returns have fat tails; a crash day can create its own short-lived “regime”.
- Results depend on settings. Number of states, feature window, training length and random seed all change the output. Test several and prefer settings that are stable, not the best looking one.
- Labels can drift between refits. Re-rank states by mean after every refit, as in the updated code.
Summary: Why You Should Consider HMM for Trading
Hidden Markov Models offer traders a powerful way to decode hidden market conditions and adapt their strategies accordingly. By identifying different market regimes, traders can improve their decision-making and enhance their overall trading performance.
- Flexibility: HMM can be applied to a wide range of assets, from stocks to commodities, and even cryptocurrencies.
- Adaptability: The model works well in both trending and range-bound markets.
- Quantitative Approach: It provides a data-driven, systematic way to trade, reducing reliance on subjective opinions.
Whether you’re a systematic trader looking for a more quantitative approach or someone seeking to understand market regimes better, HMM can be a valuable addition to your trading toolkit.
Research Reference
Intraday Application of Hidden Markov Models
For other machine learning approaches on marketcalls, see Introduction to Machine Learning for Traders and Kalman filter estimation of the mean in Python, another state-space model that traders use to track hidden values.
Frequently Asked Questions
What is a hidden Markov model trading strategy?
It is a model that treats the market regime (for example bullish, neutral or bearish) as a hidden variable that switches according to fixed probabilities, and treats returns as observations generated by that regime. Traders use it to estimate the current regime and adjust exposure or strategy.
Which Python library is used for hidden Markov models?
hmmlearn is the most common choice and provides GaussianHMM, GMMHMM and other variants with a scikit-learn style fit and predict interface. pomegranate and statsmodels (Markov switching models) are alternatives.
How many states should an HMM have for trading?
Two or three is typical: two for risk-on and risk-off, three to add a neutral state. More states usually overfit. Compare models with the BIC score or by checking whether each state has a clearly different mean and volatility.
Can an HMM predict stock prices?
Not directly. It estimates which regime the market is in and how likely it is to switch. That is useful as a filter for other strategies, but it does not forecast tomorrow’s price.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

