# Time Series Analysis and Forecasting in R ----
# Video 8 of R Programming: Zero to Expert.
# Trends, seasons, smoothing, ARIMA and honest forecasts.

# Setup ----

library(tidyverse)
library(forecast)

# What makes time series different ----
# Order matters, the past informs the future, and we never peek ahead.

# The ts object ----

AirPassengers

class(AirPassengers)
start(AirPassengers)
end(AirPassengers)
frequency(AirPassengers)
length(AirPassengers)

sales <- c(120, 132, 101, 134, 190, 230, 210, 205, 170, 160, 140, 180,
           130, 145, 115, 150, 200, 245, 225, 220, 185, 170, 150, 195)
sales_ts <- ts(sales, start = c(2023, 1), frequency = 12)
sales_ts

time(sales_ts)[1:3]
cycle(sales_ts)[1:14]

window(sales_ts, start = c(2024, 6), end = c(2024, 9))

# Plot first, always ----

autoplot(AirPassengers) +
  labs(title = "Monthly airline passengers",
       y = "Passengers (thousands)", x = NULL)

# Seasonal plots ----

ggseasonplot(AirPassengers, year.labels = TRUE) +
  labs(title = "Season plot", y = "Passengers")

ggsubseriesplot(AirPassengers) +
  labs(title = "Subseries plot", y = "Passengers")

# Taking a series apart: decomposition ----

dec <- decompose(AirPassengers, type = "multiplicative")
autoplot(dec)

round(dec$figure, 2)

fit_stl <- stl(log(AirPassengers), s.window = "periodic")
autoplot(fit_stl)

ap_sa <- seasadj(fit_stl)
autoplot(exp(ap_sa)) + labs(title = "Seasonally adjusted passengers",
                            y = "Passengers")

# Taming growing swings with logs ----

autoplot(log(AirPassengers)) +
  labs(title = "Log of passengers", y = "log(passengers)")

lambda <- BoxCox.lambda(AirPassengers)
lambda

# Moving averages ----

ma12 <- ma(AirPassengers, order = 12)
autoplot(AirPassengers, series = "Data") +
  autolayer(ma12, series = "12-month MA") +
  labs(y = "Passengers", colour = NULL)

head(ma12, 9)

# Lags, differences and autocorrelation ----

x <- ts(c(5, 7, 6, 9, 12, 11))
stats::lag(x, -1)
diff(x)
diff(x, lag = 2)

ggAcf(AirPassengers, lag.max = 36) +
  labs(title = "ACF of airline passengers")

gglagplot(sales_ts, lags = 4, do.lines = FALSE)

ap_diff <- diff(log(AirPassengers), lag = 12)
autoplot(ap_diff) + labs(title = "Year-on-year change (log)")

ndiffs(log(AirPassengers))
nsdiffs(log(AirPassengers))

# Train and test: forecasting honestly ----
# Hold back the latest data, forecast it, compare.

train <- window(AirPassengers, end = c(1958, 12))
test <- window(AirPassengers, start = c(1959, 1))
h <- length(test)
h

# Benchmark forecasts ----

f_mean <- meanf(train, h = h)
f_naive <- naive(train, h = h)
f_snaive <- snaive(train, h = h)
f_drift <- rwf(train, h = h, drift = TRUE)

autoplot(window(AirPassengers, start = 1955)) +
  autolayer(f_mean, series = "Mean", PI = FALSE) +
  autolayer(f_naive, series = "Naive", PI = FALSE) +
  autolayer(f_snaive, series = "Seasonal naive", PI = FALSE) +
  autolayer(f_drift, series = "Drift", PI = FALSE) +
  labs(y = "Passengers", colour = "Forecast")

# Measuring accuracy ----

accuracy(f_snaive, test)

bench <- list(Mean = f_mean, Naive = f_naive,
              SNaive = f_snaive, Drift = f_drift)
map_dfr(bench, \(f) {
  a <- accuracy(f, test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAE = a["MAE"], MAPE = a["MAPE"])
}, .id = "method")

# Exponential smoothing ----

f_ses <- ses(train, h = h)
f_holt <- holt(train, h = h)
f_hw <- hw(train, h = h, seasonal = "multiplicative")
accuracy(f_hw, test)["Test set", c("RMSE", "MAE", "MAPE")]

fit_ets <- ets(train)
fit_ets

f_ets <- forecast(fit_ets, h = h)
accuracy(f_ets, test)["Test set", c("RMSE", "MAE", "MAPE")]

# ARIMA ----

# AR = autoregressive (past values)
# I = integrated (differencing)
# MA = moving average (past errors)

fit_arima <- auto.arima(train, lambda = 0)
fit_arima

f_arima <- forecast(fit_arima, h = h)
accuracy(f_arima, test)["Test set", c("RMSE", "MAE", "MAPE")]

checkresiduals(fit_arima)

inside <- test >= f_arima$lower[, "95%"] &
  test <= f_arima$upper[, "95%"]
mean(inside)

# Comparing every model ----

models <- list(SNaive = f_snaive, HoltWinters = f_hw,
               ETS = f_ets, ARIMA = f_arima)
scores <- map_dfr(models, \(f) {
  a <- accuracy(f, test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAPE = a["MAPE"])
}, .id = "model")
scores |> arrange(RMSE)

autoplot(window(AirPassengers, start = 1957)) +
  autolayer(f_ets, series = "ETS", PI = FALSE) +
  autolayer(f_arima, series = "ARIMA", PI = FALSE) +
  labs(y = "Passengers", colour = "Model")

# Regression with trend and season ----

fit_lm <- tslm(log(train) ~ trend + season)
summary(fit_lm)$r.squared
coef(fit_lm)[c("trend", "season7", "season11")]

f_lm <- forecast(fit_lm, h = h)
f_lm_back <- exp(f_lm$mean)
sqrt(mean((test - f_lm_back)^2))

# Combining forecasts ----

f_combo <- (f_hw$mean + f_arima$mean) / 2
sqrt(mean((test - f_combo)^2))

# Time series cross-validation ----
# Many small tests instead of one big one.

snaive_fun <- function(y, h) snaive(y, h = h)
e_snaive <- tsCV(log(AirPassengers), snaive_fun, h = 1)
drift_fun <- function(y, h) rwf(y, h = h, drift = TRUE)
e_drift <- tsCV(log(AirPassengers), drift_fun, h = 1)
c(snaive = sqrt(mean(e_snaive^2, na.rm = TRUE)),
  drift = sqrt(mean(e_drift^2, na.rm = TRUE)))

e12 <- tsCV(log(AirPassengers), snaive_fun, h = 12)
rmse_by_h <- sqrt(colMeans(e12^2, na.rm = TRUE))
round(rmse_by_h, 3)

# Cleaning a series: outliers and gaps ----

messy <- sales_ts
messy[5] <- 900
messy[15] <- NA
tsoutliers(messy)

cleaned <- tsclean(messy)
round(cbind(messy, cleaned, original = sales_ts)[c(5, 15), ])

# Forecasting the future, with uncertainty ----

final <- auto.arima(AirPassengers, lambda = 0)
fc <- forecast(final, h = 24, level = c(80, 95))
autoplot(fc) + labs(y = "Passengers")

head(as_tibble(fc), 3)

fc_df <- tibble(
  month = seq(ymd("1961-01-01"), by = "month", length.out = 24),
  forecast = round(as.numeric(fc$mean)),
  low95 = round(as.numeric(fc$lower[, "95%"])),
  high95 = round(as.numeric(fc$upper[, "95%"]))
)
write_csv(fc_df, "passenger_forecast.csv")
head(fc_df, 4)

# From a data frame to a time series ----

set.seed(42)
daily <- tibble(
  date = seq(ymd("2023-01-01"), ymd("2024-12-31"), by = "day"),
  visits = round(200 + 0.15 * seq_along(date) +
                 40 * (wday(date) %in% c(1, 7)) +
                 rnorm(length(date), sd = 15))
)
daily

monthly <- daily |>
  mutate(month = floor_date(date, "month")) |>
  group_by(month) |>
  summarise(visits = sum(visits))
monthly_ts <- ts(monthly$visits, start = c(2023, 1),
                 frequency = 12)
monthly_ts

weekly_pattern <- daily |>
  mutate(day = wday(date, label = TRUE, week_start = 1)) |>
  group_by(day) |>
  summarise(avg = mean(visits))
weekly_pattern

ggplot(weekly_pattern, aes(day, avg)) +
  geom_col(fill = "steelblue") +
  labs(title = "Average visits by weekday", x = NULL, y = "Visits")

daily_roll <- daily |>
  mutate(roll7 = as.numeric(stats::filter(visits, rep(1 / 7, 7),
                                          sides = 1)))
ggplot(daily_roll, aes(date)) +
  geom_line(aes(y = visits), colour = "grey70") +
  geom_line(aes(y = roll7), colour = "firebrick", linewidth = 1) +
  labs(title = "Daily visits with 7-day rolling average", x = NULL)

fc_visits <- forecast(ets(monthly_ts), h = 6)
round(fc_visits$mean)

# Daily data with two seasons ----

visits_msts <- msts(daily$visits, seasonal.periods = c(7, 365.25))
fit_mstl <- mstl(visits_msts)
autoplot(fit_mstl) + labs(title = "Daily visits: trend, weekly and yearly")

fc_daily <- forecast(fit_mstl, h = 28)
round(as.numeric(head(fc_daily$mean, 7)))

# Adding outside information: regression with ARIMA errors ----

set.seed(11)
promo <- rep(c(0, 0, 1, 0, 0, 0), length.out = 48)
shop <- ts(500 + 4 * (1:48) + 120 * promo + rnorm(48, sd = 25),
           start = c(2021, 1), frequency = 12)
fit_x <- auto.arima(shop, xreg = promo)
fit_x

future_promo <- c(0, 0, 1, 0, 0, 0)
fc_x <- forecast(fit_x, xreg = future_promo)
round(fc_x$mean)

# Financial series: returns and volatility ----
# Prices are not forecast like sales. We study their returns.

dax <- EuStockMarkets[, "DAX"]
frequency(dax)
ret <- diff(log(dax))
round(c(mean = mean(ret), sd = sd(ret)) * 100, 3)

vol <- zoo::rollapply(ret, 60, sd) * sqrt(260) * 100
autoplot(vol) + labs(title = "DAX 60-day volatility (annualised %)",
                     y = "Volatility %")

naive_dax <- naive(dax, h = 20)
autoplot(window(dax, start = 1997.5)) + autolayer(naive_dax) +
  labs(y = "DAX")

# Forecasting many series at once ----

stocks <- as.list(as.data.frame(EuStockMarkets))
stock_fc <- map_dfr(stocks, \(p) {
  y <- ts(tail(p, 500))
  f <- forecast(ets(y), h = 10)
  tibble(last = tail(p, 1), day10 = as.numeric(f$mean[10]),
         change_pct = 100 * (day10 / last - 1))
}, .id = "index")
stock_fc |> mutate(across(where(is.numeric), \(x) round(x, 1)))

# Mini project: Nottingham temperatures ----
# A pure seasonal series with no trend.

temp_c <- (nottem - 32) * 5 / 9
autoplot(temp_c) + labs(y = "Temperature (C)", x = NULL)

t_train <- window(temp_c, end = c(1936, 12))
t_test <- window(temp_c, start = c(1937, 1))
t_fc <- list(SNaive = snaive(t_train, h = 36),
             ETS = forecast(ets(t_train), h = 36),
             Regression = forecast(tslm(t_train ~ season), h = 36))
map_dbl(t_fc, \(f) accuracy(f, t_test)["Test set", "RMSE"]) |>
  round(2)

# Common mistakes in forecasting ----

# 1. Random train/test splits on time series
# 2. Judging a model on its training fit
# 3. Forgetting the benchmarks
# 4. Reporting a single number without intervals
# 5. Forecasting far beyond what the data supports

set.seed(3)
idx <- sample(length(AirPassengers), 24)
peek <- AirPassengers
peek[idx] <- NA
filled <- na.interp(peek)
sqrt(mean((filled[idx] - AirPassengers[idx])^2))

# Pause and try ----

# Exercise 1: seasonal naive vs ETS on the co2 series, last 3 years as test

co2_train <- window(co2, end = c(1994, 12))
co2_test <- window(co2, start = c(1995, 1))
co2_fc <- list(SNaive = snaive(co2_train, h = 36),
               ETS = forecast(ets(co2_train), h = 36))
map_dbl(co2_fc, \(f) accuracy(f, co2_test)["Test set", "RMSE"])

# Exercise 2: the month with the most accidental deaths, on average

tapply(USAccDeaths, cycle(USAccDeaths), mean) |>
  setNames(month.abb) |>
  sort(decreasing = TRUE) |> head(3)

# Project: forecast US accidental deaths ----
# Choose a model on a holdout year, then forecast 1979.

deaths <- USAccDeaths
autoplot(deaths) + labs(title = "US accidental deaths", y = "Deaths")

d_train <- window(deaths, end = c(1977, 12))
d_test <- window(deaths, start = c(1978, 1))
cands <- list(
  SNaive = snaive(d_train, h = 12),
  ETS = forecast(ets(d_train), h = 12),
  ARIMA = forecast(auto.arima(d_train), h = 12)
)

proj_scores <- map_dfr(cands, \(f) {
  a <- accuracy(f, d_test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAE = a["MAE"], MAPE = a["MAPE"])
}, .id = "model") |> arrange(RMSE)
proj_scores

best_name <- proj_scores$model[1]
best_name
fit_1979 <- if (best_name == "ARIMA") auto.arima(deaths) else ets(deaths)
fc_1979 <- forecast(fit_1979, h = 12)

autoplot(fc_1979) +
  labs(title = "Forecast of US accidental deaths, 1979",
       y = "Deaths", x = NULL)

fc_1979 |>
  as_tibble() |>
  mutate(month = month.abb, .before = 1) |>
  mutate(across(where(is.numeric), round)) |>
  select(month, forecast = `Point Forecast`,
         low95 = `Lo 95`, high95 = `Hi 95`)

p_final <- autoplot(fc_1979) +
  labs(title = "US accidental deaths: 1979 forecast", y = "Deaths")
ggsave("deaths_forecast_1979.png", p_final, width = 8, height = 4.5,
       dpi = 150)
file.exists("deaths_forecast_1979.png")

# Recap ----

# 1. ts objects: ts(), start(), frequency(), window()
# 2. Plot first: autoplot, season and subseries plots
# 3. Decompose: trend + season + remainder; logs for growing swings
# 4. Split train/test, beat the benchmarks, measure with accuracy()
# 5. ETS and ARIMA, check residuals, forecast with intervals