Understand most recent value as forcast and use the naice appraoch to solve problems and also understand time series plot to observe data
weeks <- 1:6
values <- c(17, 13, 15, 11, 17, 14)
forecasts_a <- values[-length(values)]#exclude the last value actual_a <- values[-1] #exclude the first value mse_a ‹- mean((actual_a - forecasts_a)^2) actual_a <- values[-1]
absolute_errors <- abs(forecasts_a - actual_a) mae <- mean(absolute_errors) mae#result: 3.8
mse_a <- mean((actual_a - forecasts_a)^2)
mse_a#result: 16.2
percentage_errors <- abs((actual_a - forecasts_a) / actual_a) * 100 mape <- mean(percentage_errors) mape#result: 27.44%
#### Step 6 to answer 1d
forecast_week_7_a <- tail(values, 1) forecast_week_7_a#result: 14
install.packages("dplyr")
install.packages("zoo")
library(dplyr)
library(zoo)
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))
list(df)
plot(df$month, df$data, type = "o", col = "blue", xlab = "month", ylab = "building contracts values",
main = "monthly values of alabama building contracts")
# interpretation: the time series plot exhibits a horizontal pattern
df$avg_value <- 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)
df <- df%>%
mutate(
square_error = ifelse(is.na(avg_value), NA, (data - avg_value)^2)
)
df
mse <- mean(df$square_error, na.rm = TRUE)
mse#2040.44
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#2593.76
better_method <- ifelse(mse < mse_exp_smooth, "Three-month moving average", "Exponential smoothing")
list(
MSE_moving_average = mse,
MSE_exponential_smoothing = mse_exp_smooth,
Better_Method = better_method
)#interpretation: three month movin avg is better approach
library(readxl)
library(ggplot2)
df1 <- read_excel(file.choose())
df1
###Step 3 to answer 3a time series plot
ggplot(df1, aes(x = Period, y = Interest_Rate)) +
geom_line() +
geom_point() +
xlab("Year") +
ylab("Interest_Rate (in Percentage") +
ggtitle("Time Series Plot of Interest Rate")
# interpretaiton: we obseve a decreasing trend from 2000 to 2021 and increasing trend from 2021 to 2023
model <- lm(Interest_Rate ~ Period, data = df1)
summary(model)
#Result - linear trend equation: y = 6.70-0.13x
forecast_period_25 <- predict(model, newdata = data.frame(Period = 25))
forecast_period_25