Knowing how different market conditions affect the performance of your strategy can have a huge impact on your returns.

Certain strategies will perform well in highly volatile, choppy markets while others need a strong, smooth trend or they risk long periods of drawdown. Figuring out when you should start or stop trading a strategy, adjusting your risk and money management techniques, and even setting the parameters of your entry and exit conditions are all dependent on the market “regime”, or current conditions.

Being able to identify different market regimes and altering your strategy accordingly can mean the difference between success and failure in the markets. In this article we will explore how to identify different market regimes by using a powerful class of machine-learning algorithms known as “Hidden Markov Models.

Hidden Markov Models

Markov Models are a probabilistic process that look at the current state to predict the next state. A simple example involves looking at the weather. Let’s say we have three weather conditions (also known as “states” or “regimes”): rainy, cloudy, and sunny. If today is raining, a Markov Model looks for the probability of each different weather condition occurring. For example, there might be a higher probability that it will continue to rain tomorrow, a slightly lower probability that it will be cloudy, and a small probability that it will become sunny.

Today’s Weather Tomorrow’s Weather Probability of Change Rainy Rainy 65% Rainy Cloudy 25% Rainy Sunny 10% Cloudy Rainy 55% Cloudy Cloudy 20% Cloudy Sunny 25% Sunny Rainy 10% Sunny Cloudy 30% Sunny Sunny 60%

This seems like a very straightforward process but the complexity lies in not knowing the probability of each regime shift and how to account for these probabilities changing over time. This is where a Hidden Markov Model (HMM) comes into play. They are able to estimate the transition probabilities for each regime and then, based on current conditions, output the most probable regime.

The applications to trading are very clear. Instead of weather conditions, we could define the regimes as being bullish, bearish, or sideways markets, or high or low volatility, or some combination of factors that we know will have a large effect on the performance of our strategy.

Building a Model in R over Real Data

We are looking to find different market regimes based on these factors that we can then use to optimize our trading strategy. To do this, we’ll use the depmixS4 R library as well as EUR/USD day charts dating back to 2012 build the model.

First, let’s install the libraries and build our data set in R.

install.packages(‘depmixS4’) library(‘depmixS4’) #the HMM library we’ll use

install.packages(‘quantmod’) library(‘quantmod’) #a great library for technical analysis and working with time series

Load out data set (you can download it here), then turn it into a time series object.