2

I am working with this minimal example that I pared down from this blog and I am wondering how to match up the states properly. The example code simulates two states, state 1 is positive return with low volatility and state 2 is negative return with high volatility. If you run the code multiple times, you will see that sometimes the HMM is 100% accurate and other times it is 0% accurate. I think it is just a matter of classification, which volatility regime is state 1 and which state 2. How do I get the output to be consistent?

  library('depmixS4')
  bull_mean <- 0.2
  bull_var <- 0.05
  bear_mean <- -0.1
  bear_var <- 0.1

  # Create the various bull and bear markets returns
  bull <- rnorm(100, bull_mean, bull_var )
  bear <- rnorm(100, bear_mean, bear_var )

  # Create the list of true regime states and full returns list
  true_regimes <- c(rep(1, 100), rep(2, 100))
  returns <- c(bull, bear)

  # Create and fit the Hidden Markov Model
  hmm <- depmix(returns ~ 1, family = gaussian(), nstates = 2, data=data.frame(returns=returns))
  hmmfit <- fit(hmm, verbose = FALSE)
  post_probs <- posterior(hmmfit)
  output <- data.frame(pred = post_probs$state, true_regimes = true_regimes)
  table(output)
  accuracy = sum(post_probs$state == true_regimes) / nrow(post_probs)
  accuracy

Roger J Bos CFA
  • 474
  • 4
  • 16

0 Answers0