Original link: http://tecdat.cn/?p=12187
Financial analysts are usually concerned with detecting when the market "changes": the typical behavior of the market can be instantly transformed into very different behavior in a few months or even years. Investors want to discover these changes in time so that they can adjust their strategies accordingly, but doing so can be difficult.
RHmm is no longer available from CRAN , so I want to use the copy function of other software packages to implement the Markov regime switching model to predict the typical market behavior and increase the linear constraint function of the parameters in the model.
library(SIT)
load.packages('quantmod')
# find regimes
load.packages('RHmm', repos ='http://R-Forge.R-project.org')
y=returns
ResFit = HMMFit(y, nStates=2)
VitPath = viterbi(ResFit, y)
DimObs = 1
matplot(fb$Gamma, type='l', main='Smoothed Probabilities', ylab='Probability')
legend(x='topright', c('State1','State2'), fill=1:2, bty='n')
fm2 = fit(mod, verbose = FALSE)
Use logLik to converge at iteration 69: 125.6168
probs = posterior(fm2)
layout(1:2)
plot(probs$state, type='s', main='Implied States', xlab='', ylab='State')
matplot(probs[,-1], type='l', main='Probabilities', ylab='Probability')
legend(x='topright', c('State1','State2'), fill=1:2, bty='n')
#*****************************************************************
# Add some data and see if the model is able to identify the regimes
#******************************************************************
bear2 = rnorm( 100, -0.01, 0.20 )
bull3 = rnorm( 100, 0.10, 0.10 )
bear3 = rnorm( 100, -0.01, 0.25 )
true.states = c(true.states, rep(2,100),rep(1,100),rep(2,100))
y = c( bull1, bear, bull2, bear2, bull3, bear3 )
DimObs = 1
plota(data, type='h', x.highlight=T)
plota.legend('Returns + Detected Regimes')
#*****************************************************************
# Load historical prices
#******************************************************************
data = env()
getSymbols('SPY', src = 'yahoo', from = '1970-01-01', env = data, auto.assign = T)
price = Cl(data$SPY)
open = Op(data$SPY)
ret = diff(log(price))
ret = log(price) - log(open)
atr = ATR(HLC(data$SPY))[,'atr']
fm2 = fit(mod, verbose = FALSE)
Use logLik to converge at iteration 30: 18358.98
probs = posterior(fm2)
print(head(probs))
layout(1:3)
plota(temp, type='l', col='darkred')
plota.legend('Market Regimes', 'darkred')
layout(1:4)