Class Exercise 16

Project objective

Analysing and forecasting time series.

Question 1: Naive approach

Time series data

week <- 1:6
value <- c(17, 13, 15, 11, 17, 14)

Most recent value as forecast

forecast_1 <- value[-length(value)] # exclude the last value
actual_1 <- value[-1] # exclude the first value
mae_1 <- mean(abs(actual_1 - forecast_1))
mae_1 # Result: 3.8
## [1] 3.8
mse_1 <- mean((actual_1 - forecast_1)^2)
mse_1 # Result: 16.2
## [1] 16.2
mape_1 <- mean(abs((mae_1/actual_1)*100))
mape_1 # Result: 27.72
## [1] 27.72107
forecast_week7_1 <- tail(value, 1)
forecast_week7_1 # Result: 14
## [1] 14
Interpretation: 
The mean absolute error is 3.8.
The mean squared error is 16.2.
The mean absolute percentage error is 27.72%.
Using the naive method (most recent value), the forecast for week 7 is 14

Question 2: Average approach

Install and load packages

#install.packages("dplyr")
#install.packages("zoo")
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.3
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(zoo)
## Warning: package 'zoo' was built under R version 4.3.3
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric

Time series data

df <- data.frame(month=c(1:12), values=c(240, 352, 230, 260, 280, 322, 220, 
                                         310, 240, 310, 240, 230))

Time series plot

plot(df$month, df$values, type = "o", col = "blue", 
     xlab = "Month", ylab = "Building Contracts (in $ millions)",
     main = "Alabama Building Contracts")

mean(df$values)
## [1] 269.5
Interpretation: The time series plot exhibits a horizontal pattern, fluctuating around the mean of 269.5.

Three-month moving average approach

df$avg_contracts <- c(NA, NA, NA, 
                      (df$values[1] + df$values[2] + df$values[3]) / 3,
                      (df$values[2] + df$values[3] + df$values[4]) / 3,
                      (df$values[3] + df$values[4] + df$values[5]) / 3,
                      (df$values[4] + df$values[5] + df$values[6]) / 3,
                      (df$values[5] + df$values[6] + df$values[7]) / 3,
                      (df$values[6] + df$values[7] + df$values[8]) / 3,
                      (df$values[7] + df$values[8] + df$values[9]) / 3,
                      (df$values[8] + df$values[9] + df$values[10]) / 3,
                      (df$values[9] + df$values[10] + df$values[11]) / 3)

df <- df %>%
  mutate(
    squared_error = ifelse(is.na(avg_contracts), NA, (values - avg_contracts)^2)
  ) # calculate squared errors

mse_moving <- mean(df$squared_error, na.rm = TRUE)
mse_moving # Result: 2040.44
## [1] 2040.444
Interpretation: Using the three-month moving average approach, the mean squared error is 2040.44.

Exponential smoothing forecast

alpha = 0.02
exp_smooth <- rep(NA, length(df$values))
exp_smooth[1] <- df$values[1] # Starting point
for(i in 2:length(df$values)) {
  exp_smooth[i] <- alpha * df$values[i-1] + (1 - alpha) * exp_smooth[i-1]
}
mse_exp_smooth <- mean((df$values[2:12] - exp_smooth[2:12])^2)
mse_exp_smooth # Result: 2738.34
## [1] 2738.335
Interpretation: Using the exponential smoothing forecast, the mean squared error is 2738.34.

Which method is better

better_method <- ifelse(mse_moving < mse_exp_smooth, 
                        "Three-month moving average", "Exponential smoothing") 
list(
  MSE_moving_average = mse_moving,
  MSE_exponential_smoothing = mse_exp_smooth,
  Better_Method = better_method
) # Result: Better method = three-month moving average
## $MSE_moving_average
## [1] 2040.444
## 
## $MSE_exponential_smoothing
## [1] 2738.335
## 
## $Better_Method
## [1] "Three-month moving average"
Based on the MSE, the three-month moving average provides more accurate forecasts because its MSE of 2040.44 is lower than the exponential smoothing's MSE of 2738.34. The three-month moving average has a smaller error, making it a better method.

Questions 3-5

Install and load packages

#install.packages("readxl")
#install.packages("ggplot2")
library(readxl)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.3

Load the data

mortgage_df <- read_excel("Mortgage.xlsx")

Time series plot

ggplot(mortgage_df, aes(x = Year, y = Interest_Rate)) +
  geom_line() +
  geom_point() +
  xlab("Year") +
  ylab("Interest Rate") +
  ggtitle("Mortgage Average Interest Rate")

Interpretation: The time series plot exhibits a cyclical pattern.

Linear trend equation

model <- lm(Interest_Rate ~ Period, data = mortgage_df)
summary(model)
## 
## Call:
## lm(formula = Interest_Rate ~ Period, data = mortgage_df)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.3622 -0.7212 -0.2823  0.5015  3.1847 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  6.69541    0.43776  15.295 3.32e-13 ***
## Period      -0.12890    0.03064  -4.207 0.000364 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.039 on 22 degrees of freedom
## Multiple R-squared:  0.4459, Adjusted R-squared:  0.4207 
## F-statistic:  17.7 on 1 and 22 DF,  p-value: 0.0003637
Result - linear trend equation: 6.70 - 0.13*Period OR y = 6.70 - 0.13t

Forecast for period 25 (i.e., 2024)

forecast_period_25 <- predict(model, newdata = data.frame(Period = 25))
forecast_period_25 # Result: 3.47
##        1 
## 3.472942
Interpretation: Using the linear trend equation, the average interest rate for period 25, or 2024, is 3.47