d <- read.csv("data/T10Y3M.csv")
d$T10Y3M <- suppressWarnings(as.numeric(d$T10Y3M)) # FRED marks holidays with "."
d <- na.omit(d); d$month <- substr(d$observation_date, 1, 7)
m <- aggregate(T10Y3M ~ month, data = d, FUN = mean); x <- m$T10Y3M
cands <- list("AR(1)" = c(1, 0, 0), "AR(2)" = c(2, 0, 0), "AR(3)" = c(3, 0, 0),
"ARMA(1,1)" = c(1, 0, 1), "ARMA(2,1)" = c(2, 0, 1))
fits <- lapply(cands, function(o) arima(x, order = o, method = "ML"))
tab <- t(sapply(names(fits), function(k) c(BIC = BIC(fits[[k]]),
LjungBox_p = Box.test(resid(fits[[k]]), lag = 24, type = "Ljung-Box",
fitdf = sum(cands[[k]]))$p.value)))
best <- fits[[which.min(tab[, "BIC"])]]; fc <- predict(best, n.ahead = 24)
f2 <- function(v) paste(sprintf("%5.2f", v), collapse = " ")
cat("ACF, lags 1-4:", f2(acf(x, 4, plot = FALSE)$acf[2:5]),
"\nPACF, lags 1-4:", f2(pacf(x, 4, plot = FALSE)$acf[1:4]), "\n\n",
paste(capture.output(print(round(tab, 3))), collapse = "\n"),
"\n\nbest:", names(fits)[which.min(tab[, "BIC"])], " coef:", f2(coef(best)),
"\nh = 12: forecast", f2(fc$pred[12]), " 95% interval",
f2(fc$pred[12] + c(-1.96, 1.96) * fc$se[12]), "\n")