The Viterbi algorithm solves the decoding problem for Hidden Markov Models (HMMs) by recursively finding the maximum a posteriori estimate of the state sequence. It avoids the computational explosion of enumerating all possible state paths by using a trellis structure, where the probability of the most probable path ending in each state at time t is calculated from the maximum over all previous states, multiplied by the transition probability and the emission probability of the current observation.
Glossary
Viterbi Algorithm

What is Viterbi Algorithm?
The Viterbi algorithm is a dynamic programming algorithm that computes the most likely sequence of hidden states—such as market regimes—given a sequence of observed events and a fitted Hidden Markov Model.
In quantitative finance, the algorithm is applied to fitted regime-switching models to identify historical periods of bull, bear, or sideways markets from return data. The resulting Viterbi path provides a hard classification of each time step into a specific regime, enabling analysts to backtest state-conditional trading strategies, attribute performance to specific market environments, and compute regime-conditional risk metrics.
Key Properties of the Viterbi Algorithm
The Viterbi algorithm is a recursive dynamic programming method that efficiently finds the single most likely sequence of hidden states (the Viterbi path) given a sequence of observations and a fitted Hidden Markov Model. It is the standard decoding workhorse for regime-switching models in quantitative finance.
Global Optimality Guarantee
Unlike greedy approaches that make locally optimal state assignments at each time step, the Viterbi algorithm computes the globally optimal sequence of regimes. It uses a trellis structure to recursively compute the maximum probability of ending in each state at time t, storing backpointers to reconstruct the full path. This ensures the decoded regime sequence is the single most probable explanation of the observed market data under the model.
Computational Efficiency via Dynamic Programming
A naive brute-force evaluation of all possible state sequences would require O(N^T) operations, where N is the number of regimes and T is the sequence length—computationally intractable for any realistic financial time series. The Viterbi algorithm exploits the Markov property and optimal substructure to reduce this to O(N²T). This quadratic scaling in the number of states makes it feasible to decode regimes on tick-level or daily data spanning decades.
Recursive Trellis Computation
The algorithm operates on a trellis diagram with time steps as columns and hidden states as rows. At each time step t, it computes:
- Maximum path probability to each state j:
δ_t(j) = max_i [δ_{t-1}(i) · a_{ij}] · b_j(o_t) - Backpointer to the preceding state:
ψ_t(j) = argmax_i [δ_{t-1}(i) · a_{ij}]where a_{ij} is the transition probability from state i to j, and b_j(o_t) is the emission probability of observation o_t given state j. After reaching the final time step, the algorithm traces back through the stored pointers to reconstruct the optimal path.
Log-Space Implementation for Numerical Stability
In practice, multiplying many probabilities smaller than 1 leads to arithmetic underflow in floating-point arithmetic. The standard implementation operates entirely in the log domain, converting products into sums:
log δ_t(j) = max_i [log δ_{t-1}(i) + log a_{ij}] + log b_j(o_t)This transformation preserves the ordering of path probabilities while ensuring numerical stability for sequences with thousands of observations, which is essential for high-frequency financial applications.
Hard vs. Soft Decoding Distinction
The Viterbi algorithm performs hard decoding—it returns a single deterministic state sequence. This contrasts with the Forward-Backward algorithm, which performs soft decoding by computing the posterior probability of being in each state at each time step. In regime-switching trading models, hard decoding is preferred when the strategy requires a definitive regime classification to trigger specific allocation rules. Soft decoding is used when uncertainty quantification is needed for risk management.
Frequently Asked Questions
Clear, technically precise answers to the most common questions about how the Viterbi algorithm decodes hidden market regimes from observed financial time series.
The Viterbi algorithm is a dynamic programming algorithm that computes the single most likely sequence of hidden states (regimes) given a sequence of observed data and a fully parameterized Hidden Markov Model (HMM). It works by recursively computing the maximum probability path to each state at each time step, storing backpointers to reconstruct the optimal state sequence. Unlike the forward-backward algorithm which computes posterior state probabilities, Viterbi produces a deterministic, globally optimal state path. The algorithm operates in O(T × N²) time, where T is the sequence length and N is the number of hidden states. In quantitative finance, this translates to decoding whether the market was in a bull regime, bear regime, or sideways regime at each point in time based on observed return and volatility data.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Viterbi Algorithm vs. Alternative Decoding Methods
Comparison of the Viterbi algorithm against alternative methods for inferring the most likely sequence of hidden regimes from observed market data in Hidden Markov Models.
| Feature | Viterbi Algorithm | Forward-Backward Algorithm | Particle Filter |
|---|---|---|---|
Output Type | Single most likely state sequence (MAP path) | Posterior probability of each state at each time | Approximate posterior distribution of states |
Optimization Criterion | Maximizes joint probability of entire sequence | Maximizes marginal probability at each time step | Approximates full posterior via sequential Monte Carlo |
Handles Non-Gaussian Noise | |||
Handles Nonlinear Dynamics | |||
Computational Complexity | O(T × N²) | O(T × N²) | O(T × N × K) where K is particle count |
Memory Requirement | O(T × N) for backpointer storage | O(N) for forward pass only | O(K) for particle storage |
Online/Real-Time Capable | |||
Typical Use Case in Finance | Regime classification for backtesting and historical analysis | Real-time regime probability smoothing and parameter estimation | Stochastic volatility and jump diffusion state estimation |
Related Terms
The Viterbi algorithm is the computational engine that decodes the most probable sequence of hidden market regimes from observable price data. Explore the foundational concepts that make this dynamic programming technique indispensable for quantitative finance.
Hidden Markov Model (HMM)
The statistical framework that the Viterbi algorithm operates upon. An HMM assumes the market is governed by unobservable (hidden) states—such as bull, bear, or sideways regimes—that emit observable returns. The Viterbi algorithm solves the decoding problem: given a fitted HMM and a sequence of price data, what is the single most likely path of hidden states that generated it?
Dynamic Programming Core
The Viterbi algorithm is a classic example of dynamic programming applied to a trellis structure. It avoids the exponential complexity of enumerating all possible state sequences by recursively computing the maximum probability path to each state at each time step. Key steps include:
- Initialization: Set the probability of starting in each state.
- Recursion: At each time step, for each state, select the predecessor that maximizes the joint probability.
- Backtracking: Reconstruct the optimal path using stored pointers.
Transition Probability Matrix
A critical input to the Viterbi algorithm that governs the switching dynamics between regimes. This stochastic matrix defines the probability of transitioning from one hidden state to another. For example, a high self-transition probability (e.g., 0.95) implies regime persistence, meaning the algorithm will heavily penalize frequent state switches unless strongly supported by the observed data.
Baum-Welch vs. Viterbi
These two algorithms serve distinct purposes in the HMM lifecycle:
- Baum-Welch Algorithm: An Expectation-Maximization (EM) procedure used for training—estimating the HMM's parameters (transition and emission probabilities) from data when the state sequence is unknown.
- Viterbi Algorithm: Used for inference—decoding the most likely state sequence given an already-trained model and a new observation sequence. Viterbi provides a hard assignment of states, while Baum-Welch computes soft posterior probabilities.
Regime Detection in Practice
The Viterbi algorithm transforms raw price data into a discrete sequence of regime labels. A quantitative strategist uses this decoded path to:
- Segment historical data into distinct volatility or trend clusters for backtesting.
- Identify the current regime in real-time to switch between trading strategies (e.g., trend-following in bull markets vs. mean-reversion in range-bound markets).
- Calculate regime-conditional metrics like the Regime-Conditional Value-at-Risk (Regime-CVaR).
Computational Complexity
The Viterbi algorithm runs in O(T × N²) time, where T is the length of the observation sequence and N is the number of hidden states. This linear scaling with time makes it highly efficient for processing long financial time series. The space complexity is O(T × N) to store the backpointers required for the final backtracking step, making it feasible for high-frequency decoding on streaming data.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us