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.

211

> # Fit a Hidden Markov Model with two states

> # to the S&P500 returns stream

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

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’), fill=1:2, bty=’n’)

Figure 14.6: Two-state Hidden Markov Model applied to S&P500 returns data

Notice that within 2004 and 2007 the markets were calmer and hence the Hidden Markov

Model has given high posterior probability to Regime #2 for this period. However between 2007-

2009 the markets were incredibly volatile due to the financial crisis. This has the initial effect of

rapidly changing the posterior probabilities between the two states but being fairly consistently

in Regime #1 during 2008 itself.

The markets became calmer in 2010 but additional volatility occurred in 2011, leading once

again for the HMM to give high posterior probability to Regime #1. Subsequent to 2011 the

markets became calmer once again and the HMM is consistently giving high probability to

Regime #2. In 2015 the markets once again became choppier and this is reflected in the increased

switching between regimes for the HMM.

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

Saved successfully!

Ooh no, something went wrong!