Abstract
Financial markets exhibit alternating periods of rising and falling prices. Stock traders seeking to make profitable investment decisions have to account for those trends, where the goal is to accurately predict switches from bullish to bearish markets and vice versa. Popular tools for modelling financial time series are hidden Markov models, where a latent state process is used to explicitly model switches among different market regimes. In their basic form, however, hidden Markov models are not capable of capturing both short- and long-term trends, which can lead to a misinterpretation of short-term price fluctuations as changes in the long-term trend. In this article, we demonstrate how hierarchical hidden Markov models can be used to draw a comprehensive picture of market behaviour, which can contribute to the development of more sophisticated trading strategies. The feasibility of the suggested approach is illustrated in two real-data applications, where we model data from the Deutscher Aktienindex and the Deutsche Bank stock. The proposed methodology is implemented in the R package fHMM, which is available on CRAN.
Keywords
Introduction
Earning money with stock trading is simple: one only needs to buy and sell stocks at the right moment. In general, stock traders seek to invest at the beginning of upward trends (hereon termed as bullish markets) and repel their stocks just in time before the prices fall again (hereon termed as bearish markets). As stock prices depend on a variety of environmental factors (Humpe and Macmillan 2009; Cohen et al. 2013), chance certainly plays a fundamental role in hitting those exact moments. However, investigating market behaviour can lead to a better understanding of how trends alternate and thereby increases the chance of making profitable investment decisions. In this article, we aim at contributing to those investigations by applying the hierarchical extension of hidden Markov models (HMMs) (Fine et al. 1998) to detect bearish and bullish markets in financial time series.
Over the last decades, various HMM-type models have emerged as popular tools for modelling financial time series that are subject to state-switching over time (Schaller and van Norden 1997; Dias et al. 2009; Ang and Timmermann 2012; De Angelis and Paas 2013). Rydän et al. 1998, Bulla and Bulla 2006, and Nystrup et al. 2015, for example, used HMMs to derive stylized facts of stock returns, while Hassan and Nath 2005 and Nystrup et al. 2017 demonstrated that HMMs can prove useful for economic forecasting. More recently, Lihn 2017 applied HMMs to the Standard and Poor's 500 (S&P 500), where HMMs were used to identify different levels of market volatility, aiming at providing evidence for the conjecture that returns exhibit negative correlation with volatility. Another application to the S&P 500 can be found in Nguyen 2018, where HMMs were used to predict monthly closing prices to derive an optimal trading strategy, which was shown to outperform the conventional buy-and-hold strategy. Further applications, which involve HMM-type models for asset allocation and portfolio optimization, can be found in Ang and Bekaert 2002, Bulla et al. 2011, and Nystrup et al. 2015; Nystrup et al. 2018, to name but a few examples. All these applications demonstrate that HMMs constitute a versatile class of time series models that naturally accounts for the dynamics typically exhibited by financial time series.
However, in their basic form HMMs operate on a single time scale, with observations made, for example, on a quarterly, monthly, or daily basis. As a consequence, conventional HMMs are not capable of capturing both short- and long-term trends. Furthermore, the temporal resolution of the data strongly determines the kind of inference that can be made. This is to be regarded as a major deficit, as short-term price fluctuations can easily be misinterpreted as changes in the long-term trend and hence may draw a distorted picture of market behaviour. While models for mixed frequency modelling exist (see Guerin and Marcellino 2013), or approaches that penalize state-switches to force the model to focus on changes in the long-term trend rather than short-term price fluctuations (see Nystrup et al. 2020), we propose that this issue can to some extent be overcome by adding a hierarchical structure to the basic HMM, which improves the model's capability for distinguishing between short- and long-term trends and allows to interpret market dynamics at multiple time scales.
The hierarchical extension of HMMs originates from supervised machine learning. In Fine et al. 1998, hierarchical HMMs (HHMMs) were first applied to solve handwriting recognition tasks, where hierarchical levels appear as single letters, syllables, and words. More recently, Leos-Barajas et al. 2017 and \cite ada19 used HHMMs for animal movement modelling, where the hierarchical structure was exploited to jointly infer animals’ behavioural modes at fine and coarse scales, respectively. Here, we demonstrate that the same model structure has also strong potential for modelling financial time series, where it is often of major interest to distinguish short-term (e.g., daily) price fluctuations from long-term trends (e.g., bullish and bearish markets lasting several months).
The article is structured as follows: In Section 2, we introduce the methodology, discuss how HHMMs can be fitted via numerical likelihood maximization, and briefly outline related topics such as state decoding and model checking. In Section 3, we illustrate the feasibility of the suggested approach by modelling time series of the DAX and the Deutsche Bank stock, followed by a simulation study and a comparison to the basic HMM. In Section 4, we conclude with a discussion and outline possible avenues for future research. Pseudo-code for the proposed methodology is appended, while an implementation is provided in the R package fHMM (Oelschläger and Adam 2021).
Methodology
In this section, we introduce the model formulation and dependence structure, state a formula for the likelihood, and discuss its numerical maximization to obtain estimates for the model parameters. In addition, we outline the Viterbi algorithm, which allows to decode the hidden states underlying the observations. Model checking based on pseudo-residuals is discussed at the end of the section.
Model formulation and dependence structure
HMMs constitute a versatile class of statistical models for time series, see, for example, Zucchini et al. 2016 for a comprehensive introduction. They predicate that the behaviour of the nature can be divided into a finite number of states, where the state that is active cannot be directly observed. However, at each point in time, a data point is observed, which depends on the current state of the nature and thus yields information on the latter. More formally, this concept can be formulated by introducing two stochastic processes:
At each time point Depending on which state is active at
We make the following assumptions on these processes:
We assume that The process
From a practical point of view, it is reasonable to identify the initial distribution of
In case of financial data, the hidden states can be interpreted as different moods of the market. Even though these moods cannot be observed directly, price changes—which clearly depend on the current mood of the market—can be observed. Thereby, using an underlying Markov process, we can detect which mood is active at any point in time and how the different moods alternate. Depending on the current mood, a price change is generated by a different distribution. These distributions characterize the moods in terms of expected return and volatility.
The HMM can be extended by a hierarchical structure, resulting in the HHMM. Throughout this article, two hierarchies are considered. Assume that we are dealing with two time series observed on two different time scales. For each observation of the time series on the coarser scale, we have several observations of the times series on the finer scale, for example, monthly observations and corresponding daily observations. Following the concept of HMMs, we can model both state-dependent time series jointly. First, we treat the time series on the coarser scale as stemming from an ordinary HMM, which we refer to as the coarse-scale HMM:
At each time point Depending on which state is active at
The processes
Subsequently, we segment the observations of the fine-scale time series into At each time point Depending on which state is active at
The fine-scale processes

Dependence structure of the HHMM
Conceptually, an HHMM can be treated as an HMM with two conditionally independent observations, the coarse-scale observation on the one hand and the corresponding chunk of fine-scale observations connected to a fine-scale HMM on the other hand. To derive the likelihood of an HHMM, we start by stating the likelihood formula for the fine-scale HMMs.
Assume that we want to fit the
The forward probabilities can be calculated in a recursive way of linear complexity:
The transition from the likelihood function of an HMM to the likelihood function of an HHMM is straightforward: Consider the so-called coarse-scale forward probabilities
The coarse-scale forward probabilities can be calculated similarly by applying the recursive scheme
Maximization of the likelihood function is numerically feasible using the Newton-Raphson method. In practice, we often face the technical issues such as numerical under- or overflow, which can be addressed by maximizing the logarithm of the likelihood and incorporating constants in a conducive way. Instead of computing the forward probabilities directly, we consider the logarithmic transformation
where
where
where
where
Additionally, we have to consider that certain model parameters must satisfy constraints, namely the transition probabilities and potentially parameters of the state-dependent distributions. Using parameter transformations serves the purpose. To ensure that the entries of the t.p.m.s fulfill non-negativity and the unity condition, we use a bijective transformation from the real numbers to the unity interval. Rather than estimating the probabilities
The diagonal entries result from the unity condition
A third source of conflicts arises from the fact that the likelihood is maximized with respect to a relatively large number of parameters, which can lead to local maxima apart from the global maximum. Common Newton-Raphson-type optimization routines are unable to distinguish local maxima from the global one. To avoid the trap of ending up at a local maximum, we recommended to run the maximization routine multiple times from different, possibly randomly selected starting points, and to choose the model that corresponds to the highest likelihood. A reasonable set of starting points can be chosen based on the observed data, for example, using the method of moments estimator. Due to the increasingly complex likelihood surface, the number of optimization runs should increase with the number of parameters.
State decoding
In practice, the primary interest often lies in decoding the hidden states. The term argmax
Obtaining the most-likely state sequence
As for the likelihood function, we need to prevent numerical conflicts. Therefore, we again apply a logarithmic transformation, see Algorithm
State decoding in HHMMs is straightforward by first decoding the coarse-scale state process and then, using this information, to decode the fine-scale state process afterwards (see \cite ada19).
Model checking
Analysing so-called pseudo-residuals enables us to check whether a fitted HMM describes the data sufficiently well. This cannot be done by standard residual analysis since the observations are explained by different distributions, depending on the active state. Therefore, all observations have to be transformed on a common scale, which can be achieved in the following way: If
For HHMMs, we first decode the coarse-scale state process using the Viterbi algorithm (see Section 2.3). Subsequently, we assign each coarse-scale observation its associated distribution function under the fitted model and perform the transformation described above. Using the Viterbi-decoded coarse-scale states, we then treat the fine-scale observations analogously.
Application to stock market data
Stock market indices are computed as weighted averages over the stock prices of several companies in the market, thereby constituting a convenient measure of the overall market behaviour. In this section, HHMMs are applied to the DAX and the Deutsche Bank stock, pursuing the goal of detecting long-term trends along with short-term dynamics. The data were downloaded from
DAX
The DAX averages the stock prices of the 30 largest publicly traded companies in Germany. Formally, its value
where
Instead of modelling the process
which we refer to as the logarithm of the daily returns (log-returns). This transformation yields two important benefits from a modelling point of view: First, conditional independence becomes a reasonable assumption, which is required to preserve the first-order Markov property of the hidden state process. Second, financial theory suggests a distribution for log-returns, namely the
For our first case study, the fine-scale observation process is identified by the daily log-returns corresponding to the years 2000 to 2019. For the coarse-scale observations, we considered the average log-returns over 30 trade days, which appears to be a reasonable time span at which short-term trends can manifest themselves. While this choice is somewhat arbitrary, we found that choosing different fine-scale time horizons between 20 and 40 days had no major impact on the estimation results. For model selection, we considered the BIC, which favoured 3 coarse-scale states and 2 fine-scale states.

Visualization of the HHMM results for the DAX
The t.p.m. associated with the coarse-scale state process was estimated as
which implies the stationary distribution
implying the stationary distributions
The estimated state-dependent scaled
Figure 2(c) displays the Viterbi-decoded time series, with the decoding performed using the Viterbi algorithm as described in Section 2.3. In the autumn of 2008, the DAX is marked by the global financial crisis, which led to the bankruptcy of the US investment bank Lehman Brothers on 15 September 2008. Noteworthy, the model detects fine-scale state 2 within the bearish market (which represents most lossy periods) and switches to calmer fine-scale states as soon as the log-returns become more moderate. In 2017, we observe a high proportion of light green periods, in which the DAX gained nearly 4 000 points within just a few months. In 2018, this skyrocketing was stopped. However, as the volatility remained low, the model retained coarse-scale state 1.
Figure 2(b) shows that the pseudo-residuals can be considered as independently normal distributed, indicating a reasonable model fit. In case of severe deviations from a normal distribution, more flexible state-dependent distributions such as the normal inverse Gaussian distribution (De Angelis and Viroli 2017) can be considered. When experiencing severe residual correlation, autoregressive terms can be incorporated into the observation process. In that regard, testing for differences in the corresponding coefficients among the coarse-scale states can provide a starting point for investigating the LeBaron effect (LeBaron 1992).
In our second case study, we demonstrate how HHMMs can be used to detect bearish and bullish markets by jointly modelling indices and individual stocks, where the fine-scale observation process is identified by the daily log-returns of the Deutsche Bank stock between 2000 and March 2021. Instead of considering the monthly averages of the daily log-returns for the coarse-scale observation process (as it was done in Section 3.1), we considered the monthly returns of the DAX, and present the model with 2 coarse-scale states and 2 fine-scale states.
The t.p.m. associated with the coarse-scale state process was estimated as
which implies the stationary distribution
implying the stationary distributions
Figure 3 displays the Viterbi-decoded time series. In September 2001, after the 9/11 terrorist attacks, the Deutsche Bank stock faces a short period of substantial losses. In the autumn of 2008, the stock is marked by the global financial crisis in general and the bankruptcy of Lehman Brothers on 15 September in particular. Between 2010 and 2020, the volatility remains moderate, except for two short transitions to coarse-scale state 2. On 27 January the first confirmed COVID-19 case in Germany led to another switch to coarse-scale state 2, which is characterized by a high volatility especially in the coarse-scale observations and lasts until the end of the time series.

Visualization of the HHMM results for DAX and Deutsche Bank
Estimated parameters of the state-dependent distributions and corresponding 95% CIs
The estimated parameters, as well as 95% confidence intervals (CIs), which were computed based on
To assess the properties of HHMMs, we conducted the following simulation study: In each of 100 simulation runs, we first simulated 256 realizations from a 2-state Markov chain (coarse-scale state process). For each of these realizations, we then simulated, on average, 22.2 realizations from another 2-state Markov chain (fine-scale state process). Conditional on the simulated coarse- and fine-scale states, the observations were then drawn from scaled

Estimated state-dependent distributions for the coarse-scale observations (left panel) and the fine-scale observations within coarse-scale state 1 (middle panel) and 2 (right panel) obtained in 100 simulation runs. True state-dependent distributions are indicated by dashed lines
To assess the differences between the true and the estimated parameters, we considered the sample mean absolute bias, which was computed as
where
The estimated state-dependent distributions obtained in 100 simulations runs are visualized in Figure 4. As the estimated distributions are very close to the true ones, there is no indication for substantial biases in the estimated parameters, indicating that the suggested approach is capable of adequately capturing the true state-dependent distributions.
The sample mean estimates and the sample mean absolute biases are reported in Table 2. The mean estimates are very close to the true values (see Table 1). Due to the much smaller sample size, the biases are, in general, larger for the estimated parameters of the coarse-scale state-dependent distributions than for the fine-scale state-dependent distributions. When the true degrees of freedom are relatively large, then the corresponding estimates are substantially biased, which is due to the fact that the degrees of freedom do not affect the shape of the state-dependent distributions anymore when
Sample mean estimates and sample mean absolute biases obtained in 100 simulation runs
As demonstrated in Sections 3.1, 3.2 and 3.3, HHMMs are, by definition, capable of jointly modelling short-term price fluctuations and long-term trends. In contrast, basic HMMs are limited to modelling state-switching dynamics at only one temporal resolution. This can lead to characteristics that are difficult to interpret, which is to be regarded as a major deficit of basic HMMs (see also Lihn 2017 and Nguyen 2018). To demonstrate this issue, we compared the HHMM presented in Section 3.2 to a basic HMM. As the model presented in Section 3.2 has effectively 4 states to model the fine-scale observation process, we considered a 4-state HMM for comparison.

Viterbi-decoded time series of daily closing prices of the Deutsche Bank stock under the fitted 4-state HMM
Figure 5 visualizes the Viterbi-decoded time series of daily closing prices. Compared to the Viterbi-decoded time series under the fitted HHMM displayed in Figure 3, the fitted HMM is characterized by more state switches. Noteworthy, the expected state dwell times under the fitted HMM for states 2, 3 and 4 lie between 1.6 and 4.7 days, which also indicates a high state transition frequency. Many of these state transitions clearly relate to short-term price fluctuations instead of actual regime switches and, as a consequence, overfit market behaviour, which, as demonstrated in Section 3.2, can be overcome using HHMMs.
In this article, we proposed HHMMs as a versatile extension of basic HMMs for detecting bearish and bullish markets in financial time series. By adding a hierarchical structure to the basic HMM, we paved the way for jointly inferring long-term trends and short-term dynamics from multi-scale time series data. In two real-data applications, we demonstrated that HHMMs can help to improve our understanding of how trends alternate, which in turn can help to make profitable investment decisions. In this last section, we discuss some limitations of the suggested approach and outline possible directions for future research.
First, the dependence assumptions of the proposed model are to be questioned. Recall that we assumed conditional independence across observations and that the fine-scale HMMs are independent of the coarse-scale observations. While the former assumption is usually justified in the specific case of log-returns, the latter one can be regarded as more critical, as we used averages over the fine-scale observations (Section 3.1) and returns of a stock index that contains the stock modelled at the fine scale (Section 3.2) as coarse-scale observations. However, although inducing some dependence, we argue that the coarse-scale observation indicate changes in the long-term trend, which only depend on the current coarse-scale state and not on short-term price fluctuations. Furthermore, the dependence structure can be extended by incorporating semi-Markov chains into the state process, see Bulla and Bulla 2006 and Maruotti 2019 for details.
Second, one can put into question whether market behaviour can be classified into a finite number of states. For animal movement data, for example discrete states explaining resting, foraging, or travelling behaviour seem natural (Leos-Barajas et al. 2017). While the prospect of having similar proxies for financial data certainly is desirable, allowing for gradual changes may bring us closer to reality. In that regard, having discrete states on the coarse scale and a state-space model with an infinite number of states on the fine scale would be interesting to explore. Since we should expect the interpretation of the states to become more complicated, such an extension can help us to overcome the deficit that discrete states are often prone to over-interpretation.
While we focused on understanding past market behaviour, it would be interesting to investigate the performance of trading strategies that are based on our model. A naive strategy could be to buy stocks whenever a switch to a bullish market is predicted, and repel them whenever a switch to a bearish market is predicted. Similar strategies for basic HMMs can be found in Lihn 2017 and Nguyen 2018, and it would be interesting to compare the performance of HHMMs to these approaches.
On a final note, we would like to highlight that, analogous to handwriting recognition, any desired number of hierarchies would be theoretically feasible. However, HHMMs with more than two hierarchies would certainly not be as straightforward to implement and to handle, and the problems outlined in Section 2.2 would likely be exacerbated due to the much larger number of parameters. Nonetheless, investigating whether additional hierarchies, capturing, for example, medium-term or intra-day patterns, can help to draw a more complete picture of market dynamics seems intriguing and is therefore to be regarded as a promising avenue for future research.
Footnotes
Supplementary materials
We implemented the proposed methodology in the R package fHMM, which is available from
Acknowledgements
The authors wish to thank Roland Langrock for valuable discussions and helpful advice that considerably improved the article.
Declaration of conflicting interests
The authors declared no potential conflicts of interest with respect to the research, authorship and/or publication of this article.
Funding
The authors received no financial support for the research, authorship and/or publication of this article.
Appendix
1: Procedure
2: for
3:
4: end for
5: for
6:
7: for
8:
9: end for
10: end for
11:
12: Return
13 end Procedure
1:
2: for
3:
4: end for
5 Procedure
6: for
7:
8: end for
9: for
10:
11: for
12:
13: end for
14 end for
15:
16:
17: end Procedure
1:
2: Procedure Viterbi
3 for
4
5: end for
6: for
7: for
8:
9: end for
10: end for
11:
12: for
13:
14: end for
15: Return
16: end Procedure
