Construct a Time Series Plot and Compare Forecasting Methods
# Data for Alabama Building Contracts
contracts <- c(240, 352, 230, 260, 280, 322, 220, 310, 240, 310, 240, 230)
months <- 1:12 # Month numbers
# -----------------------------------
# 2A. Construct a Time Series Plot
# -----------------------------------
# Construct the time series plot
plot(months, contracts, type = "o", col = "blue", xlab = "Months", ylab = "Contracts ($M)",
main = "Time Series Plot: Alabama Building Contracts")
# Observation: The data shows fluctuations with no clear trend or seasonality.
# -----------------------------------
# 2B. Comparison of Three-Month MA and Exponential Smoothing
# -----------------------------------
# 1. Three-Month Moving Average (MA)
ma_forecast <- numeric(length(contracts)) # Initialize forecast vector
for (i in 3:length(contracts)) {
ma_forecast[i] <- mean(contracts[(i-2):i]) # Average of current and previous two months
}
# Add NAs to the first two months to align
ma_forecast[1:2] <- NA
# 2. Exponential Smoothing with alpha = 0.2
alpha <- 0.2
es_forecast <- numeric(length(contracts))
es_forecast[1] <- contracts[1] # Initialize with first value
for (i in 2:length(contracts)) {
es_forecast[i] <- alpha * contracts[i-1] + (1 - alpha) * es_forecast[i-1]
}
# 3. Calculate Mean Squared Error (MSE) for both methods
# Exclude first two months for MA and first month for ES to avoid NAs
ma_errors <- ma_forecast[3:length(contracts)] - contracts[3:length(contracts)]
es_errors <- es_forecast[2:length(contracts)] - contracts[2:length(contracts)]
mse_ma <- mean(ma_errors^2, na.rm = TRUE)
mse_es <- mean(es_errors^2)
# Output MSE results and comparison
cat("MSE for Three-Month Moving Average:", mse_ma, "\n")
## MSE for Three-Month Moving Average: 996.8
cat("MSE for Exponential Smoothing (alpha = 0.2):", mse_es, "\n")
## MSE for Exponential Smoothing (alpha = 0.2): 2593.762
# -----------------------------------
# Plotting the Forecasts
# -----------------------------------
# Plot the actual data, MA and ES forecasts
plot(months, contracts, type = "o", col = "blue", xlab = "Months", ylab = "Contracts ($M)",
main = "Time Series Plot: Alabama Building Contracts")
# Add Three-Month MA and Exponential Smoothing forecasts to the plot
lines(months, ma_forecast, type = "o", col = "red", lty = 2, pch = 16)
lines(months, es_forecast, type = "o", col = "green", lty = 3, pch = 17)
# Add a legend to the plot
legend("topright", legend = c("Actual", "3-Month MA", "Exp. Smoothing"),
col = c("blue", "red", "green"), lty = c(1, 2, 3), pch = c(1, 16, 17))
