N P FINANCIALS • MARKET CONTEXT BEFORE TRADE ENTRY
Same Setup. Different Market. Learn to Read the Regime.
Hidden Markov Models for Trading: The NPF Market-Regime Framework
A valid chart pattern can behave differently when volatility, direction and liquidity change. Learn how to investigate those changes without mistaking a model probability for a promise.
A Hidden Markov Model (HMM) estimates probabilities for unobserved statistical states from observed data. In trading research, those states can help describe changing market conditions. An HMM does not know the true regime, guarantee earlier turning-point detection or tell you the probability that your next trade will win.
Prepared for: N P Financials.
Trading education lead: Partha Banerjee, CFTe — Founder, Director and Head Trader, N P Financials Pty Ltd.
General education only, not personal financial advice. Trading involves financial risk. Models, indicators, back-testing and demo practice do not guarantee profitability.
Why Detect Market Regime Shifts?
A market regime is a useful description of how selected market characteristics behave over a period. It is a modelling concept, not a label printed on the chart.
You might investigate regimes to understand why a breakout method produces repeated reversals, why the same stop distance now represents a different amount of price noise, or why execution costs have become a larger part of the planned risk. You might also discover that several positions are exposed to the same market stress.
Detecting a possible change gives you a reason to review your assumptions. It does not, by itself, give you an entry, exit or permission to increase exposure. A sensible outcome can be to continue observing or take no trade.
NPF’s Interpretation: Context First, Setup Second, Risk Always
Apply NPF’s professional trader-development process—Learn → Practise → Back-Test → Demo Trade → Consider Live Trading—to the model as well as the chart.
For this educational framework, treat HMM output as a context estimate. Ask whether the environment resembles conditions in which your written setup has been studied, whether uncertainty is too high, and whether all non-model requirements are satisfied.
A reading of “70% probability of State B” describes membership of a fitted statistical state under that model. It does not mean 70% chance of a profitable trade, 70% certainty about market direction or evidence that leverage should rise.
This is an educational application of NPF’s learning process, not a claim that NPF operates a validated live HMM system, sells an HMM indicator or has achieved the performance statistics quoted in the original draft.
What We Look for When Reviewing the Process
In the beginner-journal observations supplied by NPF, recurring issues include entering before confirmation, trading outside the planned session, moving stops after entry and sizing that does not match the written risk limit. An impressive model does not correct those execution mistakes.
Bring the original chart, written trading plan and time-stamped model output to a review. Separate three questions: Was the setup valid? Was the model being used as specified? Did the trader follow the plan? A compliant loss and an impulsive win require different lessons.
These teaching observations are qualitative. No percentage of NPF students following or breaking rules is asserted here.
How an HMM Works—Without the Black Box
An HMM combines a starting state distribution, a transition matrix and observation distributions. The transition matrix describes modelled movement between states; the observation distributions describe which data are more or less consistent with each state. See hmmlearn’s model overview and Rabiner’s HMM tutorial.
Suppose a research model has two states with different return variances. Both can have near-zero mean returns. It may distinguish relatively quieter from more variable conditions without identifying a “bull” or “bear” market. State numbers are arbitrary; State 0 does not automatically mean favourable.
Begin with a clearly defined research question. Returns, trailing volatility or other features must be available at the decision time. Returns and volatility derived from those returns are not automatically independent. More features and states increase estimation demands; neither three states nor a five-year training window is universally best.
Filtering Is Not the Same as Seeing the Future
| Output | Information used | Trading-research implication |
|---|---|---|
| Filtered probability | Observations available through the current time | Suitable for a historical decision simulation only if parameters and preprocessing were also available then. |
| Smoothed probability | Later observations as well as the past | Useful for retrospective analysis; not an input for earlier simulated entries. |
| Decoded state path | The sequence supplied to the decoding algorithm | A full-history path must not be treated as a live signal history. |
Fitting on the whole dataset and then filtering its early rows still leaks later information through the fitted parameters. A causal recursion alone is not enough. In hmmlearn, full-sequence posterior output is also not automatically a causal series for every historical row; examine the forward/backward implementation.
Moving averages and HMMs both use historical observations. An HMM can react late, switch repeatedly or misclassify conditions. Whether it detects a particular change sooner than a moving-average rule is an empirical question requiring a defined, fair comparison.
When an HMM Result Should Make You Pause
A fitted HMM can be mathematically valid without producing a stable or economically useful description of the market. The question is not only whether the model converges, but whether its states remain interpretable when the assumptions, training sample or fitting process are challenged.
Instead of treating instability as something to hide, use it as part of the research result. A regime layer should earn its place by remaining useful under reasonable checks.
| Warning sign | What it may mean | What to check | NPF research response |
|---|---|---|---|
| Different initialisations produce materially different states | The fitting process may be sensitive to local solutions or starting values. | Repeat reasonable fits and compare state characteristics, transition behaviour and likelihoods. | Do not select the run with the most attractive trading result. Treat inconsistent structure as a stability warning. |
| State labels change after retraining | State numbers are arbitrary and can switch between fitted models. | Use a repeatable training-only rule to map states by characteristics such as relative volatility or another predefined feature. | Never assume that “State 0” keeps the same economic meaning after a refit. |
| One state appears only rarely | The model may be identifying an unusual condition, or it may be unnecessarily complex or poorly estimated. | Review state occupancy, duration and whether enough observations exist to support a useful interpretation. | Investigate before allowing the rare state to control a trading gate. |
| The model switches regimes constantly | The specification may be describing short-lived noise rather than persistent market context. | Review the transition matrix, state duration and the frequency of classification changes. | Compare the HMM with a simpler filter rather than assuming more responsive classification is better. |
| Small feature changes redefine the regimes | The result may be sensitive to feature choice, lookback windows, transformations or sampling frequency. | Compare justified feature sets using training and validation data only. | Record feature sensitivity as a finding instead of choosing the version that produces the best backtest. |
| A previously clear state weakens or disappears after retraining | The underlying relationships may have changed, or the original regime structure may not be persistent. | Review rolling stability, fitted distributions, transition behaviour and whether the economic interpretation still holds. | Pause or simplify the model rather than forcing an old state definition onto new data. |
Distribution assumptions deserve the same scrutiny. A Gaussian HMM can return precise-looking probabilities even when financial observations contain skewness, heavy tails or extreme events that are not well represented by the assumed state distributions. A high posterior probability does not prove that the model itself is well specified.
More complexity is not automatically an improvement. Extra states, features or alternative distributions should be retained only when they provide stable and interpretable information under the research process. If reasonable changes in initialisation, features or retraining windows produce fundamentally different conclusions, that instability is itself evidence.
A useful model should survive attempts to challenge it. If it does not, using a simpler filter—or no regime filter at all—can be the more defensible research outcome.
The NPF One Market, One Setup, One Regime Question Framework
| Stage | Research task | Evidence to bring to review |
|---|---|---|
| Learn | Define the market, timeframe, setup and meaning of each proposed regime. | A written question, feature list and data-availability timeline. |
| Practise | Label chart observations without changing the entry rules. | Annotated examples, including failed setups and no-trade decisions. |
| Back-Test | Compare the base strategy with the same strategy plus a frozen regime rule. | Chronological test windows, all trials, costs, exposure, drawdown and results. |
| Demo Trade | Record model outputs before decisions and follow the rule sheet. | Time-stamped outputs, model versions, fills and adherence records. |
| Consider Live Trading | Assess implementation, evidence and personal suitability separately. | A documented review; no requirement to leave demo. |
Setup Examples: Same Price Level, Different Decisions
All prices, probabilities, thresholds, records and risk amounts below are hypothetical teaching examples. They are not live trade ideas, fitted market forecasts or NPF/student performance records. Thresholds illustrate a rule and are not recommended universal settings.
EXAMPLE A • RULES SATISFIED
A setup eligible for demo review
The EUR/USD rule sheet requires a completed close above 1.1000 followed by a qualifying retest. The demo entry reference is 1.1010, planned stop 1.0990 and exit reference 1.1050.
The frozen model assigns 72% to the pre-identified research state. The prewritten demo gate requires at least 70% for two completed bars; both bars qualify. The session, event and cost checks also pass.
Decision: the setup is eligible under this example’s rules. That does not predict a favourable outcome.
EXAMPLE B • WAIT
A model reading is not an entry
The same state probability is now 52%, below the written gate. Alternatively, the gate passes but price spikes before the required candle close and retest.
The trader feels tempted to enter because the last breakout rose sharply. Neither a familiar pattern nor an attractive model reading overrides missing confirmation.
Decision: record the reason and skip the entry. Do not change the threshold after seeing what price does next.
Check the planned risk separately
The entry-to-stop distance in Example A is 20 pips and the target distance is 40 pips: a gross planned reward-to-risk ratio of 2:1. For an illustrative USD account with a USD $20 risk budget before costs, the permitted pip exposure is $20 ÷ 20 = USD $1 per pip. On EUR/USD, 10,000 base-currency units have that pip value.
Reserve an allowance for costs, verify the contract specification and account-currency conversion, and apply the same predefined risk management rules regardless of model confidence. Use actual execution data in the journal. Do not increase the risk budget because the model appears confident.
The $20 figure explains the arithmetic; it is not a recommended risk amount. Ordinary stop-loss orders do not guarantee the execution price. Slippage and gaps can make losses larger than planned.
A Sample Regime-Aware Rule Sheet
| Rule | Write it before testing |
|---|---|
| Market and setup | One instrument, one timeframe, one observable entry setup and defined invalidation. |
| Data timing | Completed-bar features only; use the actual publication timestamp for external data. |
| Model and labels | Training cutoff, feature transforms, model version, state definition and a repeatable training-only label rule. |
| Regime gate | The tested threshold and persistence rule. Treat ambiguous or unavailable output as “no new entry” in this teaching design. |
| Execution | Act after all signal inputs are available, at an executable subsequent price; account for spread and slippage. |
| Risk and exits | Predefined budget, position size, stop, exit and session loss limit; existing positions follow the written management plan. |
| Pause conditions | Stale data, invalid likelihood, unexplained label changes, excessive switching or a breached risk limit. |
| Review | Log model output before action, reasons for skipped entries, fills, costs, screenshots and adherence. |
Trade Rule-Adherence Example: A Win Can Still Be a Mistake
Recreated educational journal only. The following decisions and results are hypothetical, not client case histories.
| Decision | What happened | Outcome | Review lesson |
|---|---|---|---|
| A | Setup, regime gate, session and sizing rules followed. | Loss | Keep as a compliant trade; examine the strategy without inventing an execution breach. |
| B | Entry taken before confirmation despite a qualifying regime reading. | Win | Mark the breach. A favourable result does not validate the decision. |
| C | Gate did not qualify; trader stayed out. | No trade | Record as a compliant no-trade decision, separately from trade win-rate statistics. |
In a separate hypothetical sample, 24 of 30 executed trades follow every rule: 80% trade adherence. The other six trades could contain two early entries, two gate breaches, one session breach and one oversizing error. That tells you what to correct; it does not establish profitability. Twenty to thirty trades can help reveal execution mistakes but cannot certify a strategy’s edge.
Win rate needs context too. If 60% of trades win an average 0.5R and 40% lose an average 1R, gross expectancy is (0.60 × 0.5R) − (0.40 × 1R) = −0.10R per trade, before costs. Here 1R means the original planned monetary risk. Use the NPF trade-journal guide and template to review process and outcomes separately.
How to Test Whether the Regime Layer Adds Value
Specify the base strategy first. Keep its instruments, entry/exit rules, cost assumptions and test dates fixed when comparing with the filtered version. Record changes in market exposure, trade count, turnover and time out of the market; lower drawdown can simply reflect less exposure. Consider a simpler volatility filter as another benchmark, rather than assuming complexity is useful.
Fit preprocessing and the HMM on past training data only. Use an inner training/validation process to select features, state count, retraining schedule and thresholds; keep a final chronological test period untouched. In each walk-forward step, carry the new model through the available training observations to initialise its final filtered distribution, then process the next observations one at a time. Refit and remap labels using training information alone.
Choosing the Number of States Without Choosing the Best Backtest
There is no universally correct number of hidden states for a trading HMM. Two states may separate relatively quiet and more variable conditions; three may identify an additional intermediate environment; four or more may create finer statistical distinctions. None is automatically better because it produces a higher in-sample likelihood or a more attractive historical equity curve.
Treat the number of states as a model-selection decision made inside the training and validation process. Information criteria such as AIC and BIC can help compare fit against complexity, but they are evidence rather than an oracle. A model with more states usually has greater flexibility, so an improvement in historical fit does not by itself justify the extra parameters.
| Check | Question to ask | Why it matters |
|---|---|---|
| Information criteria | Does the improvement in fit justify the additional complexity? | AIC, BIC or related criteria can help compare candidate models fitted to the same training data without treating raw likelihood as the only objective. |
| State occupancy | Does each state contain enough observations to support a meaningful interpretation? | A rarely occupied state may represent a genuine unusual condition, or it may be poorly estimated or unnecessarily complex. |
| Stability across initialisations | Do repeated fits produce reasonably similar state characteristics? | A state structure that changes materially between seeds may be too sensitive to the fitting process. |
| Stability after retraining | Do comparable regime characteristics persist as new training windows are introduced? | A model intended for walk-forward use should remain interpretable after refitting, even when state numbers need to be remapped. |
| Persistence | Are the states sufficiently persistent for the research question? | Very frequent switching can create statistical classifications that add little practical market context. |
| Economic distinction | Are the states meaningfully different in the variables relevant to the research question? | Statistically separate states do not automatically create useful trading regimes. |
| Out-of-sample behaviour | Does the frozen specification remain useful on genuinely unseen observations? | The final test should evaluate the decision already made, not become another opportunity to choose the state count. |
Published financial-market HMM research has used information criteria to compare different state counts before subsequent evaluation. That does not mean the state count selected for one market, sample or model should be copied into another. The relevant lesson is to make the choice systematically and before inspecting the final test outcome.
State occupancy and persistence deserve particular attention. If a four-state model assigns almost no observations to one state, or switches so frequently that the classification has little practical meaning, the extra state may not be earning its complexity. Likewise, two statistically distinguishable states may still be economically redundant for the question being investigated.
Repeat reasonable fits across different initialisations and examine whether comparable state characteristics emerge. Then repeat the question after retraining through successive historical windows. State numbers may change and should be remapped using training information only, but a regime framework that changes its economic meaning every time it is refitted deserves caution.
Once the candidate state count, features, preprocessing, mapping rules and retraining process have been selected, freeze them before the final chronological test. Do not return repeatedly to unseen data to try two states, then three, then four until one produces the preferred result. Once the supposedly unseen period is used for model selection, it is no longer a clean final test.
Prefer the simplest model that adequately answers the research question. If two states provide comparable, stable information to four, the simpler specification may be easier to understand, monitor and challenge. If no candidate HMM demonstrates useful stability or value beyond a simpler benchmark, “do not use the HMM” is a valid research result.
Use a gap where overlapping outcome labels or holding periods would contaminate validation. Preserve real release dates for macroeconomic inputs. The scikit-learn leakage guidance and TimeSeriesSplit documentation explain the underlying separation principles; a splitter alone does not resolve every trading-data leak.
Review net expectancy, average wins and losses, drawdown, exposure, turnover and state stability. Report uncertainty and unsuccessful configurations too. Sharpe, Sortino and Calmar ratios can provide additional perspectives, but an improved historical ratio is not a promise. This article makes no claim that HMMs consistently beat moving averages or reduce drawdowns.
Readiness Checklist Before Considering Live Use
- I can explain what each model state represents and why its label is not a trading outcome.
- Every input, transform, parameter and decision respects the historical information cutoff.
- I have tested unfiltered, HMM-filtered and simpler alternatives without selecting on the final test period.
- Costs, exposure, drawdown, failed configurations and periods of ambiguous classification are documented.
- I have a reviewable demo record of adherence, errors, skipped entries and model versions.
- Missing data, invalid calculations and label instability trigger a written pause procedure.
- Risk controls and position sizing remain independent of an uncalibrated regime probability.
- I have separately considered product suitability and whether I can afford losses.
Remain in research or demo when any item is unresolved. Detecting a regime change is not the same as knowing what to trade. An HMM can be a useful question-generating tool even when it never becomes part of a live strategy.
Frequently Asked Questions
Can Hidden Markov Models predict a market crash?
Not reliably on demand. They estimate states under selected assumptions. A model can miss a shock, react after losses have occurred or report a false change.
Are three states always better than two?
No. Treat state count as a model-selection decision. Compare justified candidates using training and validation data, information criteria, state occupancy, stability across initialisations and retraining, persistence, economic interpretability and genuinely unseen evaluation. More states can improve historical fit without producing more useful regimes.
Does a high regime probability justify a larger trade?
Not by itself. A model’s state probability is not a calibrated trade-success probability. Any exposure rule requires separate testing and predefined risk limits.
Do I need an HMM before learning to trade?
No. Start with market structure, a written plan, risk calculations and a journal. Explore NPF’s trader-training pathways and trading psychology support to develop the process around the analysis.
Build the Process Before Adding the Model
Bring your chart, rule sheet and journal to a free NPF strategy session. Discuss your learning needs and the next practical skill to develop, from market analysis and back-testing to disciplined trade review.
Important risk and general advice disclosure. This article is general education and does not consider your objectives, financial situation or needs. Forex, CFDs and leveraged trading can cause financial loss. Historical examples, models, education and mentoring do not guarantee future results. An AFSL is not course accreditation or an ASIC endorsement. N P Financials Pty Ltd holds AFSL 488567; review the Financial Services Guide for service scope and disclosures. Consider product suitability and seek independent licensed advice where appropriate. ASIC Moneysmart’s forex guidance explains relevant risks and costs.
Sources and Source-Check Method
Sources were checked for HMM definitions, forward/backward inference, implementation behaviour, time-series validation, data leakage, model-selection principles and financial-risk terminology on 21 October 2026. They support those explanations, not a claim of profitable HMM trading. No untraceable performance comparison from the original draft has been retained.
- Rabiner (1989), A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition — HMM inference foundations, not a trading study.
- hmmlearn tutorial and API reference — model specification and implementation terminology.
- hmmlearn source: base.py — posterior computation and sequence handling.
- scikit-learn common pitfalls and TimeSeriesSplit — leakage prevention and chronological evaluation.
- SciPy logsumexp — numerical normalisation.
- Nguyen (2018), Hidden Markov Model for Stock Trading — an example of comparing candidate HMM state counts with multiple information criteria in a financial-market application; not evidence that any particular number of states is universally optimal.
- ASIC Moneysmart: forex trading — volatility, prediction difficulty and costs.
Technical appendix: a complete, illustrative forward filter
This example isolates filtering with fixed synthetic parameters; it does not fit an HMM, validate a strategy or issue trades. It uses the start distribution directly on the first observation, transitions only on subsequent observations, normalises in log space, and raises an error for invalid inputs instead of silently inventing equal state probabilities.
For fitted models, parameters and transforms must be learned from the training period only. A fresh filter can be run through that training sequence before processing the next unseen bar. Alternatively, supply previous only when it is the last filtered distribution under the same parameters, feature transformation and state ordering. Do not carry an old model’s state vector unchanged into a newly fitted model.
Per-step normalisation already avoids accumulation of raw sequence probabilities; long stream length alone does not make a correctly normalised probability-space filter fail. Log calculations additionally help when individual likelihoods become extremely small.
"""Educational Gaussian HMM filter. No fitting, trade signals or broker orders.
Dependencies: numpy, scipy. Demo parameters and observations are synthetic.
"""
import numpy as np
from scipy.special import logsumexp
from scipy.stats import multivariate_normal
class GaussianRegimeFilter:
def __init__(self, startprob, transmat, means, covars, previous=None):
pi = np.asarray(startprob, dtype=float)
a = np.asarray(transmat, dtype=float)
self.means = np.asarray(means, dtype=float)
self.covars = np.asarray(covars, dtype=float)
k = len(pi)
if pi.shape != (k,) or a.shape != (k, k):
raise ValueError("Invalid probability dimensions")
if self.means.ndim != 2 or len(self.means) != k:
raise ValueError("means must have shape (states, features)")
d = self.means.shape[1]
if self.covars.shape != (k, d, d):
raise ValueError("covars must have shape (states, features, features)")
for p in (pi, a):
if not np.isfinite(p).all() or (p < 0).any():
raise ValueError("Invalid probabilities")
if not np.isclose(pi.sum(), 1) or not np.allclose(a.sum(axis=1), 1):
raise ValueError("Probabilities must sum to one")
if not np.isfinite(self.means).all() or not np.isfinite(self.covars).all():
raise ValueError("Parameters must be finite")
for cov in self.covars:
if not np.allclose(cov, cov.T):
raise ValueError("Covariance must be symmetric")
np.linalg.cholesky(cov) # Reject singular/non-positive covariance.
with np.errstate(divide="ignore"):
self.log_pi, self.log_a = np.log(pi), np.log(a)
self.log_alpha = None
if previous is not None:
p = np.asarray(previous, dtype=float)
if (
p.shape != pi.shape
or not np.isfinite(p).all()
or (p < 0).any()
or not np.isclose(p.sum(), 1)
):
raise ValueError("Invalid previous filtered distribution")
with np.errstate(divide="ignore"):
self.log_alpha = np.log(p)
def update(self, observation):
x = np.asarray(observation, dtype=float)
if x.shape != self.means.shape[1:] or not np.isfinite(x).all():
raise ValueError("Observation must be a finite feature vector")
# First observation: start probability already describes its state.
# Later observations: propagate the previous filtered state through A.
prior = (
self.log_pi
if self.log_alpha is None
else logsumexp(self.log_alpha[:, None] + self.log_a, axis=0)
)
emission = np.array([
multivariate_normal.logpdf(x, mean=m, cov=c)
for m, c in zip(self.means, self.covars)
])
joint = prior + emission
z = logsumexp(joint)
if not np.isfinite(z):
raise FloatingPointError("Invalid likelihood: stop and investigate")
self.log_alpha = joint - z
return np.exp(self.log_alpha).copy()
if __name__ == "__main__":
# Illustrative two-state model, not parameters fitted to a market.
f = GaussianRegimeFilter(
startprob=[0.8, 0.2],
transmat=[[0.95, 0.05], [0.10, 0.90]],
means=[[0.0], [0.0]],
covars=[[[0.0001]], [[0.0009]]],
)
for r in [0.002, -0.001, -0.03, 0.005]:
print(np.round(f.update([r]), 4))
Educational code only. Mathematical checks on synthetic data are not independent quantitative sign-off, market-data validation, execution testing or evidence of profitable trading.