#** Basic Times Series Analysis **

Excersice Objectives

Use Different methods for Basic Times Series Analysis : Naive Approach, Moving Averages/Exponential Smoothing, and Linear Trend Regression approach.

Q1 - Using naive method (most recent value) as the forecast for the next week, compute the following measures of forecast accuracy (MAE, MSE, MAPE) & forecast the value for week 7?

Step (1) Time Series Data

week <- 1:6 # this is the independent variable -time
Value <- c(17,13,15,11,17,14) # dependent variabl 

Step (2) Most recent value as forecast

forecast <- Value[-length(Value)] #excludes the last sale (14)
actual <- Value[-1] #excludes the first sale (17)

Step (3) Part a. Calculating Mean Absolute Error:

mae <- mean(abs(actual - forecast))
mae # Mean Absolute Error is 3.80
## [1] 3.8

Step (4) Part b. Calculating Mean Square Error:

mse <- mean((actual - forecast)^2)
mse # mean square error is 16.20
## [1] 16.2

Step (5) Part c. Calculating Mean Perccentage Absolute Error:

errors <- (abs(actual - forecast) / actual) * 100
mape <- mean(errors)
mape
## [1] 27.43778

Step (6) Part d. Forecast the Value for Week 7

forecast_week7 <- tail(Value, 1) 
forecast_week7 #Interpretation : In week 7 value would be 14
## [1] 14

Q2 - (a.) Construct a time series plot. What type of pattern exists in the data? Upload a screenshot of your time series plot.

Step (1) 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 the data

df <- 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))

Step (3) Descriptive Stats

summary(df)

Step (4) Create Time Series Plot

plot(df$month, df$values, type = "o", col = "pink", xlab = "Month", ylab = "Contract Values (in $ millions)",
     main = "12 Month Alabama building contracts (in $ millions)")

#Interpretation:  Their is fluctuation that goes up and down but not consistent gradual shift upward or downward making it a horizontal pattern.

Q2 - (b). Compare the three-month moving average approach with the exponential smoothing forecast using alpha = 0.2. Which provides more accurate forecasts based on MSE? Upload a screenshot of your code outputs with proper explanation of your answers.

Step (1) Manually Calculate the Three-Week - Moving Average Method

df$avg_values3 <- 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
                   )

Step (2) Calculate the square errors (only for months avaliable)

df <- df %>%
  mutate(
    squared_error = ifelse(is.na(avg_values3), NA, (values - avg_values3)^2)
  )

Step (3) Compute MSE (exclude the initial weeks w/NA)

mse <- mean(df$squared_error, na.rm = TRUE)
mse #Output the MSE = 2040.444
## [1] 2040.444

###Step (4) Exponential Smoothing Method (Note we are still using the same data & alpha <- 0.2)

alpha <- 0.2

exp_smooth <- rep(NA, length(df$values))
exp_smooth[1] <- df$values[1] #start 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 #Output the MSE = 2593.76
## [1] 2593.762

Step (5) Comparison Between Moving Average & Exponential Smoothing

better_method <-ifelse(mse < mse_exp_smooth, "Three-Month 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] 2593.762
## 
## $Better_Method
## [1] "Three-Month Average"
#Interpretation: Moving average gives a more accurate forecast

Q3 - (a.) Construct a time series plot. What type of pattern exists in the data?

Step (1) Load Libraries

library(ggplot2)
library(readxl)

Step (2)Load the Data

df <- read_excel("Mortgage.xlsx")
df
## # A tibble: 24 × 2
##    Period Interest_Rate
##     <dbl>         <dbl>
##  1      1          8.05
##  2      2          6.97
##  3      3          6.54
##  4      4          5.83
##  5      5          5.84
##  6      6          5.87
##  7      7          6.41
##  8      8          6.34
##  9      9          6.03
## 10     10          5.04
## # ℹ 14 more rows

Step (3) Descriptive Stats:

summary(df)
##      Period      Interest_Rate  
##  Min.   : 1.00   Min.   :2.958  
##  1st Qu.: 6.75   1st Qu.:3.966  
##  Median :12.50   Median :4.863  
##  Mean   :12.50   Mean   :5.084  
##  3rd Qu.:18.25   3rd Qu.:6.105  
##  Max.   :24.00   Max.   :8.053
#Interpretation: on average the interest rate over a 20-year period is 5.08%

Step (4) Constructing 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 Interest Rate (%) over a 20-year period")

#Interpretation : We observed a decreasing pattern or trend in the time series plot that fluctuates upward after a period of time.

Q4 - Develop the linear trend equation for this time series.

Step (1) Develop a Linar 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: T_hat = 6.70 - 0.13*t

Q5 - Using the linear trend equation from question 3B, forecast the average interest rate for period 25 (i.e., 2024).

Step (1) Find MSE and MAPE values: Calculate the fitted values from the model

df$predicted_Interest_Rate <- predict(model)

Step (2) Calculate the rResiduals

df$residuals <- df$Interest_Rate - df$predicted_Interest_Rate

Step (3)Calculate the MSE (Mean Squared Error)

mse <- mean(df$residuals^2)
cat("Mean Squared Error (MSE):", mse, "\n") # MSE = 0.99
## Mean Squared Error (MSE): 0.989475

Step (4) Calculate the MAPE (MEAN ABSOLUTE PERCENTAGE ERROR)

df$percentage_error <- abs(df$residuals / df$Interest_Rate) *100
mape <- mean(df$percentage_error)
cat("Mean Absolute Percentage Error (MAPE):",mape, "%\n") #MAPE = 15.79%
## Mean Absolute Percentage Error (MAPE): 15.79088 %

Step (5)Forcast the number of the average interest rate for period 25 (i.e., 2024).

forecast_period_25 <- predict(model, newdata = data.frame(Period = 25))
forecast_period_25 # 3.47
##        1 
## 3.472942