# Replication of residual plot of Section 8.2 of Durbin and Koopman (2012)
model <- SSModel(log(drivers) ~ SSMtrend(1, Q = list(NA))+
SSMseasonal(period = 12, sea.type = "trigonometric", Q = NA),
data = Seatbelts, H = NA)
updatefn <- function(pars, model){
model$H[] <- exp(pars[1])
diag(model$Q[, , 1]) <- exp(c(pars[2], rep(pars[3], 11)))
model
}
fit <- fitSSM(model = model,
inits = log(c(var(log(Seatbelts[, "drivers"])), 0.001, 0.0001)),
updatefn = updatefn)
# tiny differences due to different optimization algorithms
setNames(c(diag(fit$model$Q[,,1])[1:2], fit$model$H[1]),
c("level", "seasonal", "irregular"))
out <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
plot(cbind(
recursive = rstandard(out),
irregular = rstandard(out, "pearson"),
state = rstandard(out, "state")[,1]),
main = "recursive and state residuals", type = "h")
# Figure 2.8 in DK2012
model_Nile <- SSModel(Nile ~
SSMtrend(1, Q = list(matrix(NA))), H = matrix(NA))
model_Nile <- fitSSM(model_Nile, c(log(var(Nile)), log(var(Nile))),
method = "BFGS")$model
out_Nile <- KFS(model_Nile, smoothing = c("state", "mean", "disturbance"))
par(mfrow = c(2, 2))
res_p <- rstandard(out_Nile, "pearson")
ts.plot(res_p)
abline(a = 0, b= 0, lty = 2)
hist(res_p, freq = FALSE)
lines(density(res_p))
res_s <- rstandard(out_Nile, "state")
ts.plot(res_s)
abline(a = 0, b= 0, lty = 2)
hist(res_s, freq = FALSE)
lines(density(res_s))
Run the code above in your browser using DataLab