**Class Exercise 16:Chapter 17

Class exercise objective

Naive Approach, Linear trend approach, and Smoothing approach

Question 1:Using naive method, compute mean squared error and forecast for week 7 in a six-week data table.

Step 1:write out data

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

#Step 2: Compute MSE

# Part A. Most Recent Value as Forecast
forecast_a <- values[-length(values)] #Excludes the last value
actual_a <- values[-1] #Exclude the first sale 
mse_a <-mean((actual_a - forecast_a)^2)
mse_a #Mean square error is 16.2
## [1] 16.2

#Step 3:Forecast value for seventh week

#Forecast the values for week 7
forecast_week7_a <- tail(values, 1)
forecast_week7_a
## [1] 14
Interpretation: The value projected for week 7 is 14.

Question 2:Using the values of building contracts in a 12-month period, Construct time series plot and identify pattern. Also, Compare three month-moving average approach with exponential smoothing forecast using alpha = 0.2. Which provides more accurate forecasts based on MSE? upload screenshot of code outputs with proper explanation of answers.

###Step 1:Install and Load packages

# install.packages("dplyr")
# install.packages("zoo")
# Load the libraries
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

##Step 2:Import and summarize data

#Import the data
# Time Series Data
df <- data.frame(month=c(1,2,3,4,5,6,7,8,9,10,11,12),
                 sales=c(240,352,230,260,280,322,220,310,240,310,240,230))
                 
# Descriptive statistics
summary(df)
##      month           sales      
##  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
# Interpretation: The average sales over the 12 month period is 269.5 million.

##Step 3: Construct time series plot and identify pattern

# Time series plot
plot(df$month, df$sales, type = "o", col =  "blue", xlab = "month", ylab = "sales",
     main = "Alabama Building Sales Plot")

#Interpretation: time series plot exhibits seasonal pattern

##Step 4:Calculate three-month moving average, and compute MSE

# Manually Calculate the three-month moving average
df$avg_sales3 <- c(NA, NA, NA,
                  (df$sales[1] + df$sales[2] + df$sales[3]) / 3,
                  (df$sales[2] + df$sales[3] + df$sales[4]) / 3,
                  (df$sales[3] + df$sales[4] + df$sales[5]) / 3,
                  (df$sales[4] + df$sales[5] + df$sales[6]) / 3,
                  (df$sales[5] + df$sales[6] + df$sales[7]) / 3,
                  (df$sales[6] + df$sales[7] + df$sales[8]) / 3,
                  (df$sales[7] + df$sales[8] + df$sales[9]) / 3,
                  (df$sales[8] + df$sales[9] + df$sales[10]) / 3,
                  (df$sales[9] + df$sales[10] + df$sales[11]) / 3
                  )

# Calculate the squared errors (only for months where moving average is available)
df <- df %>%
  mutate(
    squared_error = ifelse(is.na(avg_sales3), NA, (sales - avg_sales3)^2)
  )
# Compute MSE (excluding the initial weeks with NA)
mse <- mean(df$squared_error, na.rm = TRUE)
mse #Output the MSE - 2040.44
## [1] 2040.444

##Step 5:Find exponential smoothing forecast value and compare with three-month moving average using alpha = 0.2

# Part B. Exponental Smoothing
#Note : were using the same data from line 13

alpha <- 0.2
exp_smooth <- rep(NA, length(df$sales))
exp_smooth[1] <- df$sales[1] #Starting point
for(i in 2: length(df$sales)) {
  exp_smooth[i] <- alpha * df$sales[i-1] + (1 - alpha) * exp_smooth[i-1]
}
mse_exp_smooth <- mean((df$sales[2:11] - exp_smooth[2:11])^2)
mse_exp_smooth #Output the MSE - 2710.93
## [1] 2710.93
# Comparison
better_method <- ifelse(mse < mse_exp_smooth, "three-month moving average", "exponential smoothing")
# Results
list(MSE_Moving_Average = mse,
     MSE_Exponential_Smoothing = mse_exp_smooth,
     Better_Method = better_method
)
## $MSE_Moving_Average
## [1] 2040.444
## 
## $MSE_Exponential_Smoothing
## [1] 2710.93
## 
## $Better_Method
## [1] "three-month moving average"
Interpretation:Threee month moving average provides more accurate forecasts since it has a smaller MSE compared to the exponential smoothing forecast

###Question 3: Using data that shows average interest rate for a 30-year fixed-rate mortgage over a 20-year-period, Construct time series plot and identify pattern, develop linear trend equation for time series, and use the equation to forecast average interest rate for 2024(i.e., period 25)

##Step 1:Install and load packages, and also load the data

# install.packages("ggplot2")
# install.packages("readxl")
# Load the libraries
library(ggplot2)
library(readxl)

#Load the data
df <- read_excel("~/Desktop/class-exercise/Mortgage.xlsx")

##Step 2:Construct time series plot

# Construct a time series plot
ggplot(df, aes(x = Period, y = Interest_Rate)) +
  geom_line() +
  geom_point() +
  xlab("Period") +
  ylab("Interest_Rate") +
  ggtitle("Time Series Plot of Mortgage Interest Rates")

Interpretation: Trend pattern exists in the data as we observe a decreasing pattern or trend in the data.

##Step3: Develop linear trend equation for the time series

# Develop a linear trend equation
model <- lm(Interest_Rate ~ Period, data = df)
summary(model)
## 
## Call:
## lm(formula = Interest_Rate ~ Period, data = 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

##Step4: Using the linear trend equation, forecast average interest rate for period 25(i.e., 2024)

# Forecast the average interest rate for 2024(i.e., period 25)
forecast_period_25 <- predict(model, newdata = data.frame(Period= 10))
forecast_period_25
##        1 
## 5.406425
Interpretation: Average interest rate for period 25(2024) is 5.41%.