# 시계열 분석 — 미래 24개월을 남겨 둔 홀트윈터스 예측 평가
# 적용 범위: HoltWinters()의 공식 AirPassengers·승법 계절 모형 사례를 시간 순서 평가로 확장했습니다. 학습 종료를 1958년 12월로 정하고 이후 24개월은 적합에 사용하지 않았습니다. 계절 나이브와 RMSE 비교는 추가한 학습 설계이며 공식 문서가 제시한 성능 순위가 아닙니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/HoltWinters.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/predict.HoltWinters.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/window.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/datasets/html/AirPassengers.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

data(AirPassengers)
train <- window(AirPassengers, end = c(1958, 12))
test <- window(AirPassengers, start = c(1959, 1))
fit <- HoltWinters(train, seasonal = "multiplicative")
pred <- predict(fit, n.ahead = length(test), prediction.interval = TRUE, level = 0.95)
seasonal_naive <- rep(as.numeric(tail(train, 12)), 2)
rmse <- c(홀트윈터스 = sqrt(mean((as.numeric(test) - pred[, "fit"])^2)),
          계절나이브 = sqrt(mean((as.numeric(test) - seasonal_naive)^2)))
cat("학습 월수:", length(train), " / 미래 평가 월수:", length(test), "\n")
cat("미래 첫 세 달의 예측과 구간 (천 명):\n")
print(round(head(pred, 3), 3))
cat("미래 24개월의 RMSE (천 명):\n")
print(round(rmse, 3))
inside <- sum(as.numeric(test) >= pred[, "lwr"] & as.numeric(test) <= pred[, "upr"])
cat("명목 95% 예측구간 안의 실제 평가 월수:", inside, "/", length(test), "\n")
plot(AirPassengers, type = "n", xlab = "연도", ylab = "항공 승객 (천 명)",
  main = "과거 120개월로 적합하고 미래 24개월로 평가",
  ylim = range(c(AirPassengers, pred)))
polygon(c(time(pred), rev(time(pred))),
  c(pred[, "lwr"], rev(pred[, "upr"])),
  col = adjustcolor("#2563EB", alpha.f = 0.15), border = NA)
lines(train, col = "#374151", lwd = 2)
lines(test, col = "#111827", lwd = 2)
lines(pred[, "fit"], col = "#2563EB", lwd = 2)
lines(as.numeric(time(test)), seasonal_naive, col = "#D97706", lwd = 2, lty = 2)
abline(v = 1959, col = "#9CA3AF", lty = 3)
legend("topleft", c("실제 관측", "홀트윈터스", "계절 나이브", "95% 예측구간"),
  col = c("#111827", "#2563EB", "#D97706", "#93C5FD"),
  lty = c(1, 1, 2, 1), lwd = c(2, 2, 2, 6), bty = "n", cex = 0.8)
