g <- read.csv("data/GDPC1.csv"); g$date <- as.Date(g$observation_date)
x_all <- 100 * diff(log(g$GDPC1)); d_all <- g$date[-1]
use <- d_all >= as.Date("1951-10-01") & d_all <= as.Date("1984-10-01") # first obs is a lag
x <- x_all[use]; d <- d_all[use]
start <- c(1, -0.5, 0.3, 0.3, log(0.8), qlogis(0.9), qlogis(0.7))
fit <- optim(start, hamilton, x = x, method = "BFGS", hessian = TRUE)
th <- fit$par
se <- sqrt(diag(solve(fit$hessian)))
est <- c(mu1 = th[1], mu2 = th[2], rho1 = th[3], rho2 = th[4], sigma = exp(th[5]),
p = plogis(th[6]), q = plogis(th[7]))
use19 <- d_all >= as.Date("1951-10-01") # same model, to 2019Q4
fit19 <- optim(start, hamilton, x = x_all[use19], method = "BFGS")
list(estimates_1952_1984 = round(rbind(estimate = est, se = c(se[1:4], NA, NA, NA)), 3),
mean_duration_qtrs = round(c(expansion = 1 / (1 - est[["p"]]),
recession = 1 / (1 - est[["q"]])), 2),
p_q_if_sample_ends_2019 = round(c(p = plogis(fit19$par[6]), q = plogis(fit19$par[7])), 3))