########## ## Data ## ########## ## obtain weekly NASDAQ-100 series library("tseries") ndx <- get.hist.quote("^NDX", start = "1995-01-01", end = "2006-12-31", compression = "w", quote = "Close")[,1] plot(ndx) plot(log(ndx)) ## log-returns rndx <- 100 * diff(log(ndx)) plot(rndx) ## lattice plot library("lattice") xyplot(cbind(rndx, log(ndx), ndx)) ######################## ## Returns up to 1998 ## ######################## rndx90 <- window(rndx, end = as.Date("1998-01-31")) ## ACF/PACF (acf(coredata(rndx90), main = "")) (pacf(coredata(rndx90), main = "")) ## AR(1) regression (for returns) library("dynlm") fm <- dynlm(rndx90 ~ L(rndx90)) summary(fm) ## just use intercept fm1 <- dynlm(rndx90 ~ 1) summary(fm1) ############################## ## Out-of-sample prediction ## ############################## ## visualize prediction periods plot(window(log(ndx), end = as.Date("2001-10-31")), col = "lightgray") abline(v = end(rndx90), lty = 2) lines(window(log(ndx), end = end(rndx90))) ## fitted log-series n <- length(rndx90) n.ahead <- 208 pred <- coredata(log(ndx))[n+1] + 0:n.ahead * coef(fm1)/100 pred <- zoo(pred, time(rndx)[n:(n+n.ahead)]) ## add predictions to visualization lines(pred, col = 2) ################## ## Segmentation ## ################## ## exploratory plot(rollapply(rndx, 52, mean)) ## breakpoint estimation library("strucchange") bp <- breakpoints(coredata(rndx) ~ 1, h = 52) bp.date <- time(rndx)[breakpoints(bp, breaks = 5)$breakpoints] ## visualization ## log-series plot(log(ndx), ylab = "log(NASDAQ)", xlab = "Time") abline(v = bp.date, lty = 2) ## returns plot(rndx, col = "lightgray") lines(rollapply(rndx, 52, mean)) abline(h = 0, lty = 2) lines(zoo(as.vector(fitted(bp, breaks = 5)), time(rndx)), col = "red", lwd = 2) ## various aggregations (annual return level) plot(rollapply(rndx, 26, mean) * 52, col = "lightgray") lines(rollapply(rndx, 52, mean) * 52) lines(zoo(as.vector(fitted(bp, breaks = 5) * 52), time(rndx)), col = "red", lwd = 2)