**Predicting The Average Interest Rate

Project Objective

To investigate the average interest rate (%) for a 30-year fixed-rate mortgage over a 20-year period 

Question 1 & 2 Develop the model & Assess Predictor Significance

Step 1: install and load required libraries

library(readxl)  # For reading Excel files
## Warning: 套件 'readxl' 是用 R 版本 4.4.2 來建造的
library(ggplot2) # For creating plots
## Warning: 套件 'ggplot2' 是用 R 版本 4.4.2 來建造的

Step 2: Import & clean the data

df <- read_excel("Mortgage.xlsx")  # Choose file using a file dialog

Step 3: Summarize the data

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

Step 4: Check Data Frame Column Names

colnames(df)
## [1] "Year"          "Period"        "Interest_Rate"

Step 5: Construct a time series plot

ggplot(df, aes(x = Period, y = Interest_Rate)) +
  geom_line() +               # Add line for time series
  geom_point() +              # Add points for data visualization
  xlab("Period") +            # Label for x-axis
  ylab("Interest_Rate") +     # Label for y-axis
  ggtitle("30-year fixed-rate mortgage over a 20-year period")  # Title of the plot

Fit a linear model (InterestRate ~ Period)

model <- lm(Interest_Rate ~ Period, data = df)

Summary of the model

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

Step 6: Predicting with New Information

model <- lm(Interest_Rate ~ Period, data = df)
new_data1 <- data.frame(Period = 25)
prob1 <- predict(model, newdata = new_data1, type = "response")
cat("Forecasted rate for Period 25:", prob1, "\n")
## Forecasted rate for Period 25: 3.472942