Class Exercise 16

#Time Series Analysis

#Question 1 #Time series data

week <- 1:6 #This is the independent value variable
value <- c(17,13,15,11,17,14) #dependent variable

#Forecast values

forecast_a <- value[-length(value)] # Excludes the last value
actual_a <- value [-1] #Exclude the first sale

#Mean absolute error

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

#Mean absolute percent error

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

#mean squared error

forecast_a <- value[-length(value)] # Excludes the last value
actual_a <- value [-1] #Exclude the first sale
mse_a <- mean((actual_a - forecast_a)^2)
mse_a
## [1] 16.2

#forecast sales for week 7

forecast_week7 <- tail(value, 1)
forecast_week7
## [1] 14
#Interpretation: the value for week 7 is 14

#Question2: moving average

#Moving average

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

#Import the data

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

#Descriptive statistics

summary(df)
##      month            data      
##  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$month, df$data, type = "o", col = "blue",
     xlab = "Month", ylab = "Data",
     main = "Alabama buiding contracts value plot")

#Interpretation: the time series plot exhbits a horizontal pattern

#Manually calculate the three month moving average

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

#calc the squared errors ( only for months were moving average is available)

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

#computing MSE

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

#Exponential smoothing

alpha <- 0.2
exp_smooth <- rep(NA, length(df$data))
exp_smooth[1] <- df$data[1] #starting point
for(i in 2: length(df$data)) {
  exp_smooth[i] <- alpha * df$data[i-1] + (1 - alpha) * exp_smooth[i-1]
}
mse_exp_smooth <- mean((df$data[2:12] - exp_smooth[2:12])^2)
mse_exp_smooth #output the MSE = 2593.76
## [1] 2593.762

#comparison

better_method <- ifelse(mse < mse_exp_smooth, "Three-Month moving average", "Exponential smoothing")

#final 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 moving average"

#Question 3:

#Load the libraries

library(readxl)
library(ggplot2)

#load the data

df <- read_excel("~/Downloads/RMarkdown/Mortgage.xlsx")
df
## # A tibble: 24 × 3
##    Year                Period Interest_Rate
##    <dttm>               <dbl>         <dbl>
##  1 2000-01-01 00:00:00      1          8.05
##  2 2001-01-01 00:00:00      2          6.97
##  3 2002-01-01 00:00:00      3          6.54
##  4 2003-01-01 00:00:00      4          5.83
##  5 2004-01-01 00:00:00      5          5.84
##  6 2005-01-01 00:00:00      6          5.87
##  7 2006-01-01 00:00:00      7          6.41
##  8 2007-01-01 00:00:00      8          6.34
##  9 2008-01-01 00:00:00      9          6.03
## 10 2009-01-01 00:00:00     10          5.04
## # ℹ 14 more rows

#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

#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 fixed-rate mortgage")

#interpretation: we observe a downward trend pattern 

#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

#Forecast the average interest rate for period 25

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