library(KFAS)
#Example of multivariate local level model
#Two temperature datas from David S. Stoffer's webpage
y1<-scan("http://www.stat.pitt.edu/stoffer/tsa2/data/HL.dat")
y2<-scan("http://www.stat.pitt.edu/stoffer/tsa2/data/folland.dat")
yt<-rbind(y1,y2)
#Estimating the variance parameters
likfn<-function(par, yt, a1, P1, P1inf) #Function to optim
{
L<-matrix(c(par[1],par[2],0,par[3]),ncol=2)
H<-L%*%t(L)
q11<-exp(par[4])
lik<-kf(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1,
Ht=H, Qt=q11, a1 = a1, P1=P1, P1inf=P1inf, optcal=c(FALSE,FALSE,FALSE,FALSE))
lik$lik
}
est<-optim(par=c(.1,0,.1,.1), likfn, method="BFGS", control=list(fnscale=-1),
hessian=TRUE, yt=yt, a1=0, P1=0, P1inf=1) #Diffuse initialisation
pars<-est$par
L<-matrix(c(pars[1],pars[2],0,pars[3]),ncol=2)
H<-L%*%t(L)
q11<-exp(pars[4])
kfd<-kf(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1,
Ht=H, Qt=q11, a1 = 0, P1=0, P1inf=1)
ksd<-ks(kfd)
alpha<-simsmoother(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1,
Ht=H, Qt=q11, a1 = 0, P1=0, P1inf=1, nsim=1000)
ahat<-NULL
for(i in 1:108) ahat[i]<-mean(alpha[1,i,])
ts.plot(ts(ahat),ts(ksd$ahat[1,]),col=c(1,2))
Run the code above in your browser using DataLab