# Time series examples: six charts from freely available data
# Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
# Base R only: no packages needed.
base <- "https://www.drnickygrant.com/teaching/data/"

monthly <- function(file) {                 # read a month,value file and add a date column
  d <- read.csv(paste0(base, file))
  d$date <- as.Date(paste0(d$month, "-01"))
  d
}
open_png <- function(name, w = 6.2, h = 4.4) png(name, width = w, height = h, units = "in", res = 200)

# 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
cpi <- monthly("uk-cpi-inflation-d7g7.csv")
y <- cpi$cpi_inflation[cpi$date <= as.Date("2016-08-01")]
fit <- lm(y[-1] ~ y[-length(y)])            # OLS of y_t on 1 and y_{t-1}
c0 <- coef(fit)[1]; phi <- coef(fit)[2]; sigma <- summary(fit)$sigma
H <- 36; f <- se <- numeric(H); m <- tail(y, 1); v <- 0
for (h in 1:H) {
  m <- c0 + phi * m                         # E[Y_{T+h} | Y_T]
  v <- sigma^2 + phi^2 * v                  # forecast-error variance
  f[h] <- m; se[h] <- sqrt(v)
}
fdates <- seq(as.Date("2016-08-01"), by = "month", length.out = H + 1)
hist <- cpi[cpi$date >= as.Date("2012-01-01") & cpi$date <= as.Date("2016-08-01"), ]
open_png("fig1-uk-cpi-forecast-fan.png")
plot(hist$date, hist$cpi_inflation, type = "n", xlim = range(c(hist$date, fdates)), ylim = c(-1.5, 4),
     xlab = "", ylab = "% change on a year earlier", main = "UK CPI inflation and an AR(1) forecast fan")
for (band in list(list(0.90, "#f6c7b6"), list(0.60, "#ef9a84"), list(0.30, "#e06650"))) {
  z <- qnorm(0.5 + band[[1]] / 2)
  upper <- c(tail(y, 1), f + z * se); lower <- c(tail(y, 1), f - z * se)
  polygon(c(fdates, rev(fdates)), c(upper, rev(lower)), col = band[[2]], border = NA)
}
lines(hist$date, hist$cpi_inflation, col = "firebrick", lwd = 2)
abline(h = 2, lty = 2, col = "grey40")
dev.off()

# 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
ftse <- read.csv(paste0(base, "ftse-daily-1991-1998.csv"))
ret <- 100 * diff(log(ftse$ftse))
open_png("fig2-ftse-daily-returns.png", 7.6, 3.0)
plot(ftse$time[-1], ret, type = "l", lwd = 0.5, xlab = "Daily FTSE 100 returns, 1991 to 1998", ylab = "log return, %")
abline(h = 0, col = "grey50")
dev.off()

# 3. US population at each census, 1790 to 1990 (US Census Bureau)
pop <- read.csv(paste0(base, "us-population-1790-1990.csv"))
open_png("fig3-us-population.png", 6.0, 4.2)
plot(pop$year, pop$population_millions, type = "o", pch = 0,
     xlab = "US population at each census, 1790 to 1990", ylab = "millions")
dev.off()

# 4. UK unemployment rate, monthly (ONS series MGSX)
u <- monthly("uk-unemployment-rate-mgsx.csv")
open_png("fig4-uk-unemployment.png", 6.0, 4.2)
plot(u$date, u$unemployment_rate, type = "l", xlab = "UK unemployment rate, monthly", ylab = "%")
dev.off()

# 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
r <- monthly("uk-retail-sales-j5ah.csv")
r <- r[r$date >= as.Date("2010-01-01") & r$date <= as.Date("2019-12-01"), ]
open_png("fig5-uk-retail-sales.png", 6.0, 4.2)
plot(r$date, r$retail_sales_index, type = "o", pch = 0, cex = 0.5,
     xlab = "UK retail sales, monthly, not seasonally adjusted", ylab = "index")
dev.off()

# 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
br <- monthly("uk-bank-rate-1987-2017.csv")
open_png("fig6-uk-bank-rate.png", 6.0, 3.3)
plot(br$date, br$bank_rate, type = "s", col = "#0f5c5c", lwd = 2, xlab = "UK Bank Rate, 1987 to 2017", ylab = "%")
dev.off()
