13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

212

The same process will now be carried out for a three-state HMM. There is little to modify

between the two, with the exception of modifying nstates = 3 and adjusting the plotting legend.

See Figure 14.7.

> # Fit a Hidden Markov Model with three states

> # to the S&P500 returns stream

> hmm <- depmix(returns ~ 1, family = gaussian(), nstates = 3,

data=data.frame(returns=returns))

> hmmfit <- fit(hmm, verbose = FALSE)

> post_probs <- posterior(hmmfit)

>

> # Plot the returns stream and the posterior

> # probabilities of the separate regimes

> layout(1:2)

> plot(returns, type=’l’, main=’Regime Detection’,

xlab=’’, ylab=’Returns’)

> matplot(post_probs[,-1], type=’l’,

main=’Regime Posterior Probabilities’,

ylab=’Probability’)

> legend(x=’bottomleft’, c(’Regime #1’,’Regime #2’, ’Regime #3’),

fill=1:3, bty=’n’)

Figure 14.7: Three-state Hidden Markov Model applied to S&P500 returns data

The length of data makes the posterior probabilities chart somewhat trickier to interpret.

Since the model is forced to consider three separate regimes it leads to a switching behaviour

between Regime #2 and Regime #3 in the calmer period of 2004-2007. However in the volatile

periods of 2008, 2010 and 2011, Regime #1 dominates the posterior probability indicating a

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!