Question 1

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 values as forecast

forecast_a <- values[-length(values)] #Excludes the last values
actual_a <- values[-1] # Excludes the first values
mse_a <- mean((actual_a - forecast_a)^2)
mse_a #Mean square error is 16.2
## [1] 16.2

#forecast the values for week 7

forecast_week7_a <- tail(values, 1)
forecast_week7_a 
## [1] 14

#Inrepretation: The number of week 7 is 14

Part B. Average of all data as forecast

Note: We’re still working with the same dataseet in line 4&5

cumulative_averages <- cumsum(values[-length(values)]) / (1:(length(values) - 1))
cumulative_averages
## [1] 17.0 15.0 15.0 14.0 14.6
forecast_b <- cumulative_averages
actual_b <- values[-1] #Exclude the first value
mse_b <- mean((actual_b - forecast_b)^2)
mse_b #Mean square error is 8.272
## [1] 8.272

forecast the values for week 7

forecast_week7_b <- mean(values) #Average of week 7
forecast_week7_b
## [1] 14.5

#Inrepretation: The number of week 7 is 14.5

#Part c. comparison

better_method <- ifelse(mse_a < mse_b, "Most Recent Value", "Average of All Data")

Results

list(
  MSE_Most_Recent_Value = mse_a,
  Forecast_Week7_Most_Recant = forecast_week7_a,
  MSE_Average = mse_b,
  Forecast_Week7_Average = forecast_week7_b,
  Better_Method = better_method
)  
## $MSE_Most_Recent_Value
## [1] 16.2
## 
## $Forecast_Week7_Most_Recant
## [1] 14
## 
## $MSE_Average
## [1] 8.272
## 
## $Forecast_Week7_Average
## [1] 14.5
## 
## $Better_Method
## [1] "Average of All Data"

Qustion 2

Method 2 : Moving Average and Exponential Smoothing Approach

Part A. Moving Average:

Note: Install the “dplyr” package if you don’t have it. Just uncomment it

install.packages(“dplyr”)

install.packages(“zoo”)

Load the libraries

library(dplyr)
## Warning: 套件 'dplyr' 是用 R 版本 4.4.2 來建造的
## 
## 載入套件:'dplyr'
## 下列物件被遮斷自 'package:stats':
## 
##     filter, lag
## 下列物件被遮斷自 'package:base':
## 
##     intersect, setdiff, setequal, union
library(zoo)
## Warning: 套件 'zoo' 是用 R 版本 4.4.2 來建造的
## 
## 載入套件:'zoo'
## 下列物件被遮斷自 'package:base':
## 
##     as.Date, as.Date.numeric

Time Series Data

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

Descriptive statistics

summary(df)
##      month          contract    
##  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 contract over the 12 month period is 250.0

Time series plot:

plot(df$month, df$contract, type = "o", col = "blue", xlab = "month", ylab="contract(million)",
     main = "Alabama building contracts")

#Inteprtation: The time series plot exhibits as norizontal pattern as it is # steady on the moon

Manually calculate the three-month moving average

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

Calculate the square errors (only for month were moving average is available)

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

Compute MSE (excluding the initialcmoths with Na)

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

Paart B. Exponential Smoothing

Note; We’re using the same data set fror line 13

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

Qustion 3~5

Method 3: Linear Trend Regression Approach

Note: Install the “ggplot2” package if you don’t have it. Just uncomment it

#install.packages(“ggplot2”)

Load the libararies

library(readxl) 
## Warning: 套件 'readxl' 是用 R 版本 4.4.2 來建造的
library(ggplot2)
## Warning: 套件 'ggplot2' 是用 R 版本 4.4.2 來建造的

#Load the data # If using excel:

df <- read_excel(file.choose())
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

On average the number of interest rate over 20-year period

Construct a time series plot

ggplot(df, aes(x = Period, y = Interest_Rate)) +
  geom_line() +
  geom_point() +
  xlab("Period") +
  ylab("Interest") +
  ggtitle(" average interest rate for a 30-year fixed-rate mortgage over a 20-year period")

Interpretation: we observe an decreasing pattern or trend in the time series polt

Develope a lonear 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_Rat = 6.69541 + -0.12890*Period or

T_hat = 6.69541 + -0.12890*t

The R-square is 0.4459(Moderately fit the data)

The overall model is significant as p-value < 0.05

To find the MSE and Mape values

Caculate the fitted values from the miodel

df$predicted_Interest_Rate <- predict(model)

Calculate the risiduals

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

Bonus section : Calculate mean absolute percentage error (mape)

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

Focecast the number of Interest_Rate in 2024 (i.e., Period 25).

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