# NOT RUN {
set.seed(332213)
data(finance)
x <- data.matrix(finance)
#log return
y <- x[-1,-51]
for(i in 2:nrow(x)){
y[i-1,] <- log(x[i,-51]) - log(x[i-1,-51])
}
#annualize the log return
y <- y * 252
#first, fit a Gaussian HMM without autoregressive structure
m <- 2
#initialize the list of means
mu <- list(apply(y,2,mean), apply(y,2,mean))
#initialize the list of covariance matrices
sigma <- list(cov(y)*1.2,cov(y)*0.8)
#initialize the prior probability
delta <- c(0.5,0.5)
#initialize the transition probabilities
gamma <- matrix(c(0,1,1,0),2,2,byrow=TRUE)
#initialize the state duration probabilities
d <- list(rep(0.1,10),rep(0.1,10))
mod1 <- list(m=m,mu=mu,sigma=sigma,delta=delta,gamma=gamma,d=d)
#will not run without a shrinkage on the covariance matrices because the
#series is not long enough to reliably estimate the covariance structure
fit1 <- em.semi(y=y,mod=mod1,cov.shrink=0.0001)
st1 <- viterbi.semi(y=y,mod=fit1)
sp1 <- smooth.semi(y=y,mod=fit1)
#second, fit a Gaussian HSMM with 1st order autoregressive structure
auto <- list(matrix(rep(0,2500),50,50,byrow=TRUE),
matrix(rep(0,2500),50,50,byrow=TRUE))
mod2 <- list(m=m,mu=mu,sigma=sigma,delta=delta,gamma=gamma,auto=auto,
d=d,arp=1)
#increase auto.lambda to enforce stronger regularization for model to run
fit2 <- em.semi(y=y,mod=mod2,cov.shrink=0.001,arp=1,
auto.alpha=0.8,auto.lambda=10)
sum(fit2$auto[[1]]==0)
sum(fit2$auto[[2]]==0)
st2 <- viterbi.semi(y=y,mod=fit2)
sp2 <- smooth.semi(y=y,mod=fit2)
#third, fit a Gaussian HSMM with 2nd order autoregressive structure
auto <- list(matrix(rep(0,5000),50,100,byrow=TRUE),
matrix(rep(0,5000),50,100,byrow=TRUE))
mod3 <- list(m=m,mu=mu,sigma=sigma,delta=delta,gamma=gamma,auto=auto,
d=d,arp=2)
#increase auto.lambda to enforce stronger regularization for model to run
fit3 <- em.semi(y=y,mod=mod3,ntimes=NULL,cov.shrink=0.0001,arp=2,
auto.alpha=0.8,auto.lambda=30)
sum(fit3$auto[[1]]==0)
sum(fit3$auto[[2]]==0)
st3 <- viterbi.semi(y=y,mod=fit3)
sp3 <- smooth.semi(y=y,mod=fit3)
# }
Run the code above in your browser using DataLab