Class Exercise 16

Question1

Step 1: Input Data

week <- 1:6
value <- c(17, 13, 15, 11, 17, 14)

Step 2: Forecast using the Naive Method

Naive method: forecast for the next week = most recent value

forecast <- c(NA, value[-length(value)]) # Shift values one step forward (first forecast is NA)

Step 3: Calculate Errors

error <- value - forecast              # Forecast error (actual - forecast)
abs_error <- abs(error)                # Absolute error
squared_error <- error^2               # Squared error
percentage_error <- abs_error / value * 100 # Percentage error

Step 4: Compute Measures of Forecast Accuracy

mae <- mean(abs_error, na.rm = TRUE)   # Mean Absolute Error (skip NA)
mse <- mean(squared_error, na.rm = TRUE) # Mean Squared Error
mape <- mean(percentage_error, na.rm = TRUE) # Mean Absolute Percentage Error

Step 5: Forecast for Week 7

forecast_week_7 <- value[length(value)] # Last actual value as the forecast

Step 6: Print Results

cat("a. Mean Absolute Error (MAE):", mae, "\n")
cat("b. Mean Squared Error (MSE):", mse, "\n")
cat("c. Mean Absolute Percentage Error (MAPE):", mape, "%\n")
cat("d. Forecast for Week 7:", forecast_week_7, "\n")

Question2A: Constructing a time series plot

Alabama building contract data

data \<- c(240, 352, 230, 260, 280, 322, 220, 310, 240, 310, 240, 230)

Step 1:Plot the time series

plot(data, type = "o", col = "blue", xlab = "Month", ylab = "Contract Value ($ Million)",
     main = "Time Series Plot of Alabama Building Contracts")

Question2B: Comparing Three-Month Moving Average with Exponential Smoothing

Step 1: Three-Month Moving Average

library(stats) # Ensure stats package is loaded
moving_avg <- filter(data, rep(1/3, 3), sides = 1) # Calculate 3-month moving average

Step 2: Exponential Smoothing (alpha = 0.2)

alpha <- 0.2
exp_smooth <- numeric(length(data))
exp_smooth[1] <- data[1] # Initialize the first smoothed value
for (i in 2:length(data)) {
  exp_smooth[i] <- alpha * data[i - 1] + (1 - alpha) * exp_smooth[i - 1]
}

Step 3: Mean Squared Error (MSE) Calculation

MSE for Moving Average

mse_moving_avg <- mean((data[4:length(data)] - moving_avg[4:length(data)])^2, na.rm = TRUE)

Step 4: MSE for Exponential Smoothing

mse_exp_smooth <- mean((data - exp_smooth)^2)

Step 5:Print the MSE results

cat("MSE of Moving Average:", mse_moving_avg, "\n")
cat("MSE of Exponential Smoothing:", mse_exp_smooth, "\n")

Step 6: Plotting Comparison

plot(data, type = "o", col = "blue", xlab = "Month", ylab = "Contract Value ($ Million)",
     main = "Forecast Comparison: Moving Average vs Exponential Smoothing")
lines(moving_avg, col = "red", lty = 2, lwd = 2) # Add moving average line
lines(exp_smooth, col = "green", lty = 2, lwd = 2) # Add exponential smoothing line
legend("topright", legend = c("Actual Data", "Moving Average", "Exponential Smoothing"),
       col = c("blue", "red", "green"), lty = c(1, 2, 2), lwd = 2)

Interpretation:

Three-Month Moving Average:
The Mean Squared Error (MSE) for the three-month moving average method is 892.4444.
Exponential Smoothing (Alpha = 0.2):
The MSE for exponential smoothing with alpha = 0.2 is 2377.615.
Conclusion Based on MSE:
The three-month moving average provides more accurate forecasts than exponential smoothing for this dataset, as evidenced by the lower MSE.

#Mortgage ##Question 3

Step 1: Load Necessary Libraries

library(readxl)  # For reading Excel files
library(ggplot2) # For plotting

Step 2: Load the Data

data <- read_excel(file.choose())

Step 3: Inspect the Data

head(data)  # View the first few rows to understand the structure

Step 4: Convert Year to Date Format

data$Year <- as.Date(data$Year) # Ensure Year is in Date format

Step 5: Construct a Time Series Plot

ggplot(data = data, aes(x = Year, y = Interest_Rate)) +
  geom_line(color = "blue", size = 1) +  # Add a line for the interest rates
  geom_point(color = "red", size = 2) +  # Add points for each observation
  labs(
  title = "Average Interest Rate Over 20 Years",
  x = "Year",
  y = "Interest Rate (%)"
  ) +
  theme_minimal()  # Use a clean theme for better visualization

Question 4:

Step 1: Load Necessary Libraries library(readxl)

library(readxl)

Step 2: Load the Data

data \<- read_excel(file.choose()) \# Use file.choose() to manually select the file

Step 3: Perform Linear Regression

model \<- lm(Interest_Rate \~ Period, data = data) \# Linear regression model

Step 4: Extract the Coefficients

intercept \<- coef(model)[1] \# Intercept slope \<- coef(model)[2] \# Slope

Step 5: Construct the Linear Trend Equation

linear_trend_equation \<- paste0(round(intercept, 2), " + ", round(slope, 2), " \* Period") print(linear_trend_equation)

Step 6:Construct a cleaner equation without “+ -”

linear_trend_equation \<- paste0(round(intercept, 2), " - ", abs(round(slope, 2)), " \* Period") print(linear_trend_equation)

#Question 5: ## From the previous question, the equation is: 6.7 - 0.13 * Period ### Step 1: Define the Linear Trend Equation

intercept <- 6.7  # Intercept from the linear trend equation
slope <- -0.13    # Slope from the linear trend equation

Step 2: Define the Period to Forecast

period_25 \<- 25 \# Period 25 represents the year 2024

Step 3: Calculate the Forecasted Interest Rate

forecasted_interest_rate \<- intercept + slope \* period_25

Step 4: Print the Forecasted Value

cat("The forecasted average interest rate for Period 25 (2024) is:", forecasted_interest_rate, "%\n")