[R] time-varying parameters kalman filter estimation problem using FKF package

napps22 n.j.apps22 at gmail.com
Sat Dec 17 15:21:13 CET 2011


Dear R users,

I am trying to carry out MLE of the time-varying CAPM using the FKF package.
My approach so far has been to try and adapt the example given in the help
file found using ?fkf which demonstrates the MLE of an ARMA(2,1) model.

When I attempt to run my R code (given below) I get the following error:

Error in fkf(a0 = sp$a0, P0 = sp$P0, dt = sp$dt, ct = sp$ct, Tt = sp$Tt,  : 
  Some of dim(dt)[2], dim(ct)[2], dim(Tt)[3],
dim(Zt)[3], dim(HHt)[3], dim(GGt)[3] or
dim(yt)[2] is/are neither equal to 1 nor equal to 'n'!

Here is the R code that generated this error


# Fitting time-varying parameter CAPM to BP stock
# let rt denote adjusted daily returns on a stock
# let rmt denote daily returns on the appropriate benchmark e.g. SP500
# rt = alphat + betat * rmt + et
# alphat = alphat_1 + n1t
# betat = betat_1 + n2t
# where et ~ N(0,H)
# (n1t,n2t) ~ N(0,Q)

#load required packages

library(tseries)
library(FKF)

# load data

FTSE100 <- get.hist.quote(instrument = "^FTSE", start = "2007-01-01", quote
= "Close", retclass = "zoo", quiet = TRUE)

BP <- get.hist.quote(instrument = "BP", start = "2007-01-01", quote =
"AdjClose", retclass = "zoo", quiet = TRUE)

# calulate continuously compounded daily returns

FTSE100.ret <- lag(log(FTSE100), k = -1) - log(FTSE100)
BP.ret <- lag(log(BP), k = -1) - log(BP)

# collect data
data <- merge(BP.ret,FTSE100.ret, all = FALSE)
index <- index(data)

# create data matrix

Z <- cbind(1, as.vector(data[,2]))
y <- as.matrix(data[,1],nrow = 1, ncol = length(y))

# format Z into an array

Zt <- array(NA,c(1,2,nrow(Z)))
for(i in 1:nrow(Z)) {
	Zt[,,i] <- Z[i,]
	}

# specify state-space form of the time-varying capm

capm.ss <- function(alpha,beta,sigma_e,sigma_n1,sigma_n2) {

	Tt <- diag(1,2)
	Zt <- Zt
	ct <- matrix(0)
	dt <- matrix(0,nrow = 2, ncol = 1)
	GGt <- matrix(sigma_e^2)
	HHt <- diag(c(sigma_n1^2,sigma_n2^2),2)
	a0 <- c(0,0)
	P0 <- diag(10^6,2)
	
	return(list(a0 = a0, P0 = P0, ct = ct, dt = dt, Zt = Zt, Tt = Tt, GGt =
GGt, HHt = HHt))
	
	}
	
# now define the loss function

loss.fn <- function(theta,yt) {
	
	sp <- capm.ss(theta["alpha"], theta["beta"],
theta["sigma_e"],theta["sigma_n1"], theta["sigma_n2"])
	
	ans <- fkf(a0 = sp$a0, P0 = sp$P0, dt = sp$dt, ct = sp$ct, Tt = sp$Tt, Zt =
sp$Zt, HHt = sp$HHt, GGt = sp$GGt, yt = yt)
	
	return(-ans$logLik)
	
	} 

start_val <- runif(5)
fit <- optim(start_val, loss.fn, hessian = TRUE, yt = y)


--
View this message in context: http://r.789695.n4.nabble.com/time-varying-parameters-kalman-filter-estimation-problem-using-FKF-package-tp4208364p4208364.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list