Class Exercise 16: Chapter 17

library(readxl)
library(dplyr)
## 
## 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)
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(ggplot2)

Question 1: Naive Forecasting Time Series Data

# Time Series Data
week <- 1:6
values <- c(17, 13, 15, 11, 17, 14)

# Naive Forecasting Approach
forecast_a <- values[-length(values)]
actual_a <- values[-1]

# Calculate MSE
mse_a <- mean((actual_a - forecast_a)^2)
mse_a # MSE is 16.2
## [1] 16.2
# Calculate MAE
mae_a <- mean(abs(actual_a - forecast_a))
mae_a # MAE is 3.8
## [1] 3.8
# Calculate MAPE
mape_a <- mean(abs((actual_a - forecast_a) / actual_a)) * 100
mape_a # MAPE is 27.44%
## [1] 27.43778
# Forecast the value for week 7
forecast_week7_a <- tail(values,1)
forecast_week7_a
## [1] 14
# Interpretation: The value will be 14 in week 7.

Question 2: Moving Average vs Exponential Smoothing Forecasting

# Time Series Data
df_b <- data.frame(month=c(1,2,3,4,5,6,7,8,9,10,11,12),
                   values=c(240, 352, 230, 260, 280, 322, 220, 310, 240, 310, 240, 230))

# Descriptive Statistics
summary(df_b)
##      month           values     
##  Min.   : 1.00   Min.   :220.0  
##  1st Qu.: 3.75   1st Qu.:237.5  
##  Median : 6.50   Median :250.0  
##  Mean   : 6.50   Mean   :269.5  
##  3rd Qu.: 9.25   3rd Qu.:310.0  
##  Max.   :12.00   Max.   :352.0
# Time series plot
plot(df_b$month, df_b$values, type = "o", col = "blue", xlab = "Month", ylab = "Values (in $ millions)",
     main = "The Values of Alabama Building Contracts for a 12-Month Period")

# Interpretation: Time series plot data is horizontal.

# Manually calculate the 3-Month Moving Average
df_b$avg_values3 <- c(NA, NA, NA,
                      (df_b$values[1] + df_b$values[2] + df_b$values[3])/3,
                      (df_b$values[2] + df_b$values[3] + df_b$values[4])/3,
                      (df_b$values[3] + df_b$values[4] + df_b$values[5])/3,
                      (df_b$values[4] + df_b$values[5] + df_b$values[6])/3,
                      (df_b$values[5] + df_b$values[6] + df_b$values[7])/3,
                      (df_b$values[6] + df_b$values[7] + df_b$values[8])/3,
                      (df_b$values[7] + df_b$values[8] + df_b$values[9])/3,
                      (df_b$values[8] + df_b$values[9] + df_b$values[10])/3,
                      (df_b$values[9] + df_b$values[10] + df_b$values[11])/3
                      )

df_b <- df_b %>%
  mutate(
    squared_error_b_ma = ifelse(is.na(avg_values3), NA, (df_b$values - avg_values3)^2)
  )

# Compute MSE for 3 Month Moving Average
mse_b_ma <- mean(df_b$squared_error_b_ma, na.rm = TRUE)
mse_b_ma # MSE for Moving Average is 2040.44
## [1] 2040.444
# Compute Exponential Smoothing

alpha <- 0.2
exp_smooth <- rep(NA, length(df_b$values))
exp_smooth[1] <- df_b$values[1]
for(i in 2: length(df_b$values)) {
  exp_smooth[i] <- alpha * df_b$values[i-1] + (1 - alpha) * exp_smooth[i-1]
}

mse_b_exp_smooth <- mean((df_b$values[2:length(df_b$values)] - exp_smooth[2:length(exp_smooth)])^2, na.rm = TRUE)
mse_b_exp_smooth # MSE for EXP Smoothing is 2593.76
## [1] 2593.762
# Comparison
better_method <- (ifelse(mse_b_ma < mse_b_exp_smooth, "Three-Month Moving Average", "Exponential Smoothing"))

# Results
list(
  MSE_B_Moving_Average = mse_b_ma,
  MSE_B_Exponential_Smoothing = mse_b_exp_smooth,
  Better_Method = better_method
)
## $MSE_B_Moving_Average
## [1] 2040.444
## 
## $MSE_B_Exponential_Smoothing
## [1] 2593.762
## 
## $Better_Method
## [1] "Three-Month Moving Average"
# Interpretation: The Three-Month Moving Average method is more accurate because it's mean square error is lower at 2040, when compared to the mean
# square error of the Exponential Smoothing method whose mean square error is 2593.76.

Question 3: Mortgage Data

# Time Series Data
mortgage_df <- read_excel("Mortgage.xlsx")

# Descriptive Statistics
summary(mortgage_df)
##       Year                         Period      Interest_Rate  
##  Min.   :2000-01-01 00:00:00   Min.   : 1.00   Min.   :2.958  
##  1st Qu.:2005-10-01 18:00:00   1st Qu.: 6.75   1st Qu.:3.966  
##  Median :2011-07-02 12:00:00   Median :12.50   Median :4.863  
##  Mean   :2011-07-02 18:00:00   Mean   :12.50   Mean   :5.084  
##  3rd Qu.:2017-04-02 06:00:00   3rd Qu.:18.25   3rd Qu.:6.105  
##  Max.   :2023-01-01 00:00:00   Max.   :24.00   Max.   :8.053
# On average, the interest rate is 5.08% over a 23-year period (24 periods). The median interest rate is 4.86%.

# Time series plot
ggplot(mortgage_df, aes(x = Period, y = Interest_Rate,)) +
  geom_line() +
  geom_point() +
  xlab("Period") +
  ylab("Interest Rate") +
  ggtitle("Mortgage Interest Rates Time Series Plot")

# Interpretation: This time series data plot exhibits a decreasing pattern or trend.

# Develop a 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 - estimated linear trend equation: Interest Rate = 6.70 - 0.13 * Period OR
# T_hat = 6.70 - 0.13 * t

# The R-squared is 0.45, which shows it moderately fits the data
# The overall model is significant because the p-value is less than alpha at 0.5
# Calculate MSE and MAPE values and begin prediction
mortgage_df$predicted_interest_rate <- predict(model)

# Calculate the residuals
mortgage_df$residuals <- mortgage_df$Interest_Rate - mortgage_df$predicted_interest_rate

# Calculate the MSE
mse_mortgage <- mean(mortgage_df$residuals^2)
cat("MSE:", mse_mortgage, "\n") # MSE for this model is 0.99
## MSE: 0.989475
# Calculate the MAPE
mortgage_df$percentage_error <- abs(mortgage_df$residuals / mortgage_df$Interest_Rate) * 100
mape_mortgage <- mean(mortgage_df$percentage_error)
cat("MAPE:", mape_mortgage, "%\n") # MAPE is 15.79% 
## MAPE: 15.79088 %
# Forecast the interest rate for Period 25 (2024)
forecast_period_25 <- predict(model, newdata = data.frame(Period = 25))
forecast_period_25 
##        1 
## 3.472942
# Interpretation: The interest rate for 30-year mortgages will be ~3.47% in 2024 (Period 25).