### Method 1: Naive Approach ###

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

# Part A. Most Recent Value as Forecast
forecast_a <- values[-length(values)] #Excludes the last value
actual_a <- values [-1] #Exclude the first sale

# MAE
mae_a <- mean(abs(actual_a - forecast_a))
mae_a
## [1] 3.8
#3.8

# MAPE
mape_a <- mean(abs(actual_a - forecast_a) / actual_a) * 100
mape_a
## [1] 27.43778
#27.44

#Mean Squared Error
mse_a <- mean((actual_a - forecast_a)^2)
mse_a #Mean Square Error is 16.2
## [1] 16.2
#Forecast the sales for week 11
forecast_week7_a <- tail(values, 1)
forecast_week7_a 
## [1] 14
#Interpretation: 14 will be sold in week 7

#Part B. Average of All Data as Forecast

#Note: We're still working on the same dataset
cumluative_averages <- cumsum(values[-length(values)]) / (1:(length(values) -1))
cumluative_averages
## [1] 17.0 15.0 15.0 14.0 14.6
forecast_b <- cumluative_averages
actual_b <- values[-1] #Exclude the first value
mse_b <- mean((actual_b - forecast_b)^2)
mse_b #Mean square error is 8.27
## [1] 8.272
#Forecast the sales for week 11
forecast_week7_b <- mean(values) # Average of all weeks as forecast for week 7
forecast_week7_b 
## [1] 14.5
### Method 2 : Moving average and expontential smoothing apporach ###

# Part A. Moving Average and install packages

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.2
## 
## 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.4.2
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
# Time Series Data
df <- data.frame(week=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)
##       week           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 week period is 269.5

plot(df$week, df$sales, type = "o", col = "blue", 
     xlab = "week", ylab = "sales", 
     main = "Alabama Building Contracts Plot")

#Part A Moving Average


# Manually Calculate the Three-Week 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 [2] + 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 square errors (only for months were moving average is available)
df <- df %>%
  mutate(
    square_error = ifelse(is.na(avg_sales3), NA, (sales - avg_sales3)^2))

#Compute MSE (Excluding the initial weeks with NA)
mse <- mean(df$square_error, na.rm = TRUE) 
mse #Output is 1896.30
## [1] 1896.296
#Part B

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:12] - exp_smooth [2:12])^2)
mse_exp_smooth # 2593.76
## [1] 2593.762
#Comparision

better_method <- ifelse(mse < mse_exp_smooth, "Three-Month Moving Average", 
                        "Exponential Smoothing")

list(
  MSE_Moving_Average = mse,
  MSE_Exponential_Smoothing = mse_exp_smooth,
  better_method = better_method
)
## $MSE_Moving_Average
## [1] 1896.296
## 
## $MSE_Exponential_Smoothing
## [1] 2593.762
## 
## $better_method
## [1] "Three-Month Moving Average"
### Method 3: Linear Trend Regression Approach ###

#load the libraries

library(ggplot2)

#load data

library(readxl)            
## Warning: package 'readxl' was built under R version 4.4.2
df <- read_excel(file.choose())

# Descriptive Statistics
summary(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 over a 20 year month period is 5.09

#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")

# Interpretation : There's a downward trend in the time series plot



# 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
# Results - Estimated Linear Trend Equation : Mortage = 6.7 + -0.13*Period

#Calculate the fitted values from the model
df$predicted_Interest_Rate <- predict(model)

#Calculate the residuals
df$residuals <- df$Interest_Rate - df$predicted_Interest_Rate

#calculate the mean squared error (MSE)
mse <- mean(df$residuals^2)
cat("Mean Squared Error (MSE):", mse, "\n")
## Mean Squared Error (MSE): 0.989475
#Forecast the number of interest rate (Period 25)
forecast_period_25 <- predict(model, newdata = data.frame(Period = 25))
forecast_period_25
##        1 
## 3.472942
#Interpretation : the forecasted number is 3.47