# Hidden Markov Models & Regime Change: DARWINs vs. S&P500

24 April 2017

In this post, we will employ a statistical time series approach using Hidden Markov Models (HMM), to firstly obtain visual evidence of regime change in the S&P500. We will then compare the index’ performance to a DARWIN Portfolio, between June 2014 and March 2017.

Detecting significant, unforeseen changes in underlying market conditions (termed “market regimes“) is one of the greatest challenges faced by algorithmic traders today. It is therefore critical that traders account for shifts in these market regimes during trading strategy development.

## Why use Hidden Markov Models? Hidden Markov Models for Detecting Market Regime Change (Source: Wikipedia)

Hidden Markov Models infer “hidden states” in data by using observations (in our case, returns) correlated to these states (in our case, bullish, bearish, or unknown).

They are hence a suitable technique for detecting regime change, enabling algorithmic traders to optimize entries/exits and risk management accordingly.

We will make use of the depmixS4 package in R to analyse regime change in the S&P500 Index, and subsequently compare its performance during those states to a DARWIN Portfolio over the same time period. Hidden Markov Model – State Space Model (Source: StackExchange)

With any state-space modelling effort in quantitative finance, there are usually three main types of problems to address:

1. Prediction – forecasting future states of the market
2. Filtering – estimating the present state of the market
3. Smoothing – estimating the past states of the market

We will be using the Filtering approach.

Additionally, we will assume that since DARWIN Portfolio or S&P500 returns are continuous, the probability of seeing a particular return R in time t, with market regime M being in state m, where the model used has parameter-set P, is described by a multivariate normal distribution with mean μ and standard deviation σ .

Mathematically, this can be expressed as:

$$p(R_t | M_t = m, P) = N(R_t | μ_m, σ_m)$$

As noted earlier, we will utilize the Dependent Mixture Models package in R (depmixS4) for the purposes of:

1. Fitting a Hidden Markov Model to S&P500 returns data.
2. Determining posterior probabilities of being in one of three market states (bullish, bearish or unknown), at any given time.

We will then use the plotly R graphing library to plot both the S&P500 returns, and the market states the index was estimated to have been in over time.

Once these steps are complete, we’ll compare the risk adjusted performance of the S&P500 to that of a DARWIN Portfolio over the same time period.

You may replicate the following R source code to conduct this analysis on the S&P500.

#### Step 1: Load required R libraries

library(quantmod) library(plotly) library(depmixS4)

#### Step 2: Get S&P500 data from June 2014 to March 2017

getSymbols("^GSPC", from="2014-06-01", to="2017-03-31")

#### Step 3: Calculate differenced logarithmic returns using S&P500 EOD Close prices.

sp500_temp = diff(log(Cl(GSPC))) sp500_returns = as.numeric(sp500_temp)

#### Step 4: Plot returns from (3) above on plot_ly scatter plot.

plot_ly(x = index(GSPC), y = sp500_returns, type="scatter", mode="lines") %>%

layout(xaxis = list(title="Date/Time (June 2014 to March 2017)"), yaxis = list(title="S&P500 Differenced Logarithmic Returns"))

## S&P500 Differenced Logarithmic Returns (June 2014 to March 2017)

#### Step 5: Fit Hidden Markov Model to S&P500 returns, with three “states”

hidden_markov_model <- depmix(sp500_returns ~ 1, family = gaussian(), nstates = 3, data = data.frame(sp500_returns=sp500_returns))

model_fit <- fit(hidden_markov_model)

#### Step 6: Calculate posterior probabilities for each of the market states

posterior_probabilities <- posterior(model_fit)

#### Step 7: Overlay calculated probabilities on S&P500 cumulative returns

sp500_gret = 1 + sp500_returns
sp500_gret <- sp500_gret[-1]
sp500_cret = cumprod(sp500_gret)

plot_ly(name="Unknown", x = index(GSPC), y = posterior_probabilities$S1, type="scatter", mode="lines", line=list(color="grey")) %>% add_trace(name="Bullish", y = posterior_probabilities$S2, line=list(color="blue")) %>%

add_trace(name="Bearish", y = posterior_probabilities\$S3, line=list(color="red")) %>%

add_trace(name="S&P500", y = c(rep(NA,1), sp500_cret-1), line=list(color="black"))

## S&P500 Market Regime Probabilities (June 2014 to March 2017)

Interpretation: In any one “market regime”, the corresponding line/curve will “cluster” towards the top of the y-axis (i.e. near a probability of 100%).

For example, during a brief bullish run starting on 01 June 2014, the blue line/curve clustered near y-axis value 1.0. This correlates as you can see, with movement in the S&P500 (black line/curve). The same applies to bearish and “unknown” market states.

An interesting insight one can draw from this graphic, is how the Hidden Markov Model successfully reveals high volatility in the market between June 2014 and March 2015 (constantly changing states between bullish, bearish and unknown).

With all our analysis work complete, we can now compare risk adjusted returns’ performance of the S&P500 and a DARWIN Portfolio over the same time period (June 2014 to March 2017).

## Conclusion

A DARWIN Portfolio, carefully constructed using Darwinex’ proprietary Analytical Toolkit, consistently outperformed the S&P500 regardless of shifting market regimes as unearthed by the Hidden Markov Model employed.

It also visibly demonstrated more stable risk adjusted returns than the S&P500, confirmed separately by conducting the necessary calculations on the underlying data.

References:

 Murphy, K.P. (2012) Machine Learning – A Probabilistic Perspective, MIT Press.
https://www.cs.ubc.ca/~murphyk/MLbook/

Influences:

The honourable Mr. Michael Halls-Moore. QuantStart.com
http://www.quantstart.com/
{"ft_lang_label":"__label__en","ft_lang_prob":0.84403735,"math_prob":0.90290034,"size":5862,"snap":"2020-10-2020-16","text_gpt3_token_len":1423,"char_repetition_ratio":0.115056336,"word_repetition_ratio":0.022673031,"special_character_ratio":0.25469124,"punctuation_ratio":0.11804878,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9772001,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-02-21T21:55:12Z\",\"WARC-Record-ID\":\"<urn:uuid:3ef48e3f-3d65-499a-9111-c42649d7ea7e>\",\"Content-Length\":\"56028\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:fc68f7bc-a865-4531-94e9-d3fefc5cecb0>\",\"WARC-Concurrent-To\":\"<urn:uuid:62229ee4-1edb-46e9-b4cf-29d5981f176d>\",\"WARC-IP-Address\":\"52.212.101.17\",\"WARC-Target-URI\":\"https://blog.darwinex.com/hidden-markov-models-darwins-sp500/?lang=fr\",\"WARC-Payload-Digest\":\"sha1:7ZPRS5VJQAEOICPE3YEVCK5PEFQLS2CO\",\"WARC-Block-Digest\":\"sha1:6F4UGH7CSJ542BC6LMCBWJ3C36SKPAEQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-10/CC-MAIN-2020-10_segments_1581875145538.32_warc_CC-MAIN-20200221203000-20200221233000-00059.warc.gz\"}"}