1. Pemuatan Data Malaysia

library(readxl)
library(dplyr)
library(tidyr)
library(stringr)
library(forecast)
library(tseries)

file_path <- "C:/Users/Lenovo/Downloads/Tugas data 15 Negara_Rianti palombu.xlsx"
nilai_malaysia <- numeric(0)

if (file.exists(file_path)) {
  sheets <- excel_sheets(file_path)
  cat("Sheet tersedia:", paste(sheets, collapse = ", "), "\n")

  raw_df <- read_excel(file_path, sheet = sheets[1])
  print(glimpse(raw_df))

  char_cols <- names(raw_df)[sapply(raw_df, function(col) is.character(col) || is.factor(col))]
  if (length(char_cols) > 0) {
    match_matrix <- sapply(raw_df[char_cols], function(col) {
      str_detect(as.character(col), regex("malaysia", ignore_case = TRUE))
    })
    match_matrix[is.na(match_matrix)] <- FALSE
    malaysia_rows <- raw_df[rowSums(match_matrix) > 0, , drop = FALSE]
  } else {
    malaysia_rows <- raw_df[0, , drop = FALSE]
  }

  if (nrow(malaysia_rows) > 0) {
    print(malaysia_rows)
    num_df <- malaysia_rows[1, sapply(malaysia_rows, is.numeric), drop = FALSE]
    num_vals <- as.numeric(unlist(num_df, use.names = FALSE))
    nilai_malaysia <- num_vals[!is.na(num_vals)]
  } else if ("Malaysia" %in% names(raw_df)) {
    col_vals <- suppressWarnings(as.numeric(raw_df[["Malaysia"]]))
    nilai_malaysia <- col_vals[!is.na(col_vals)]
  }
} else {
  cat("File tidak ditemukan pada path lokal; cek kembali lokasi file.\n")
}
## Sheet tersedia: Data, Series - Metadata 
## Rows: 65
## Columns: 29
## $ `Country Name`  <chr> "Indonesia", "Indonesia", "Indonesia", "Indonesia", "M…
## $ `Country Code`  <chr> "IDN", "IDN", "IDN", "IDN", "MYS", "MYS", "MYS", "MYS"…
## $ `Series Name`   <chr> "Merchandise trade (% of GDP)", "Agriculture, forestry…
## $ `Series Code`   <chr> "TG.VAL.TOTL.GD.ZS", "NV.AGR.TOTL.ZS", "NV.IND.TOTL.ZS…
## $ `2001 [YR2001]` <dbl> 59.14416030, 15.99491776, 47.89350079, 3.64346645, 174…
## $ `2002 [YR2002]` <dbl> 49.8342510, 16.3196690, 47.7453312, 4.4994754, 172.364…
## $ `2003 [YR2003]` <dbl> 45.27958614, 15.18534822, 43.74956609, 4.78036912, 170…
## $ `2004 [YR2004]` <dbl> 48.91976662, 14.33578030, 44.62761598, 5.03087395, 185…
## $ `2005 [YR2005]` <dbl> 56.92160282, 13.12661864, 46.54105887, 5.69257130, 178…
## $ `2006 [YR2006]` <dbl> 50.51889610, 12.97380272, 46.94355874, 5.50095179, 178…
## $ `2007 [YR2007]` <dbl> 48.8444758, 13.7166831, 46.7991415, 6.3450222, 166.435…
## $ `2008 [YR2008]` <dbl> 52.35770431, 14.48174026, 48.06074477, 6.01370360, 154…
## $ `2009 [YR2009]` <dbl> 39.55520333, 15.29014815, 47.65212258, 4.62887118, 138…
## $ `2010 [YR2010]` <dbl> 38.86164355, 13.92921271, 42.77586634, 6.22385418, 142…
## $ `2011 [YR2011]` <dbl> 42.6591467, 13.5122871, 43.9134234, 6.1697842, 139.471…
## $ `2012 [YR2012]` <dbl> 41.58791943, 13.37397424, 43.59374442, 6.03005065, 134…
## $ `2013 [YR2013]` <dbl> 40.45712164, 13.35669916, 42.63567744, 5.55726369, 134…
## $ `2014 [YR2014]` <dbl> 39.79188690, 13.33675500, 41.92834213, 5.00666843, 130…
## $ `2015 [YR2015]` <dbl> 34.04304572, 13.49264356, 40.04786240, 4.87632230, 124…
## $ `2016 [YR2016]` <dbl> 30.06221750, 13.47874855, 39.30844398, 5.03306918, 118…
## $ `2017 [YR2017]` <dbl> 32.0726652, 13.1566308, 39.3791548, 5.0697859, 129.594…
## $ `2018 [YR2018]` <dbl> 35.38732358, 12.80849756, 39.72973745, 5.17429154, 129…
## $ `2019 [YR2019]` <dbl> 30.28853891, 12.71260266, 38.95176800, 5.01928768, 121…
## $ `2020 [YR2020]` <dbl> 28.79246548, 13.69841428, 38.23839372, -2.06551183, 12…
## $ `2021 [YR2021]` <dbl> 36.04656609, 13.28016914, 39.84481919, 3.70288563, 143…
## $ `2022 [YR2022]` <dbl> 40.13535934, 12.39965016, 41.42926418, 5.30719723, 158…
## $ `2023 [YR2023]` <dbl> 35.06086611, 12.52944319, 40.21575199, 5.04883118, 144…
## $ `2024 [YR2024]` <chr> "35.691782687541277", "12.609722029425116", "39.318435…
## $ `2025 [YR2025]` <chr> "36.299843802922851", "13.099546319927846", "38.707741…
## # A tibble: 65 × 29
##    `Country Name` `Country Code` `Series Name`     `Series Code` `2001 [YR2001]`
##    <chr>          <chr>          <chr>             <chr>                   <dbl>
##  1 Indonesia      IDN            Merchandise trad… TG.VAL.TOTL.…         59.1   
##  2 Indonesia      IDN            Agriculture, for… NV.AGR.TOTL.…         16.0   
##  3 Indonesia      IDN            Industry (includ… NV.IND.TOTL.…         47.9   
##  4 Indonesia      IDN            GDP growth (annu… NY.GDP.MKTP.…          3.64  
##  5 Malaysia       MYS            Merchandise trad… TG.VAL.TOTL.…        174.    
##  6 Malaysia       MYS            Agriculture, for… NV.AGR.TOTL.…          8.01  
##  7 Malaysia       MYS            Industry (includ… NV.IND.TOTL.…         46.2   
##  8 Malaysia       MYS            GDP growth (annu… NY.GDP.MKTP.…          0.518 
##  9 Singapore      SGP            Merchandise trad… TG.VAL.TOTL.…        265.    
## 10 Singapore      SGP            Agriculture, for… NV.AGR.TOTL.…          0.0824
## # ℹ 55 more rows
## # ℹ 24 more variables: `2002 [YR2002]` <dbl>, `2003 [YR2003]` <dbl>,
## #   `2004 [YR2004]` <dbl>, `2005 [YR2005]` <dbl>, `2006 [YR2006]` <dbl>,
## #   `2007 [YR2007]` <dbl>, `2008 [YR2008]` <dbl>, `2009 [YR2009]` <dbl>,
## #   `2010 [YR2010]` <dbl>, `2011 [YR2011]` <dbl>, `2012 [YR2012]` <dbl>,
## #   `2013 [YR2013]` <dbl>, `2014 [YR2014]` <dbl>, `2015 [YR2015]` <dbl>,
## #   `2016 [YR2016]` <dbl>, `2017 [YR2017]` <dbl>, `2018 [YR2018]` <dbl>, …
## # A tibble: 4 × 29
##   `Country Name` `Country Code` `Series Name`      `Series Code` `2001 [YR2001]`
##   <chr>          <chr>          <chr>              <chr>                   <dbl>
## 1 Malaysia       MYS            Merchandise trade… TG.VAL.TOTL.…         174.   
## 2 Malaysia       MYS            Agriculture, fore… NV.AGR.TOTL.…           8.01 
## 3 Malaysia       MYS            Industry (includi… NV.IND.TOTL.…          46.2  
## 4 Malaysia       MYS            GDP growth (annua… NY.GDP.MKTP.…           0.518
## # ℹ 24 more variables: `2002 [YR2002]` <dbl>, `2003 [YR2003]` <dbl>,
## #   `2004 [YR2004]` <dbl>, `2005 [YR2005]` <dbl>, `2006 [YR2006]` <dbl>,
## #   `2007 [YR2007]` <dbl>, `2008 [YR2008]` <dbl>, `2009 [YR2009]` <dbl>,
## #   `2010 [YR2010]` <dbl>, `2011 [YR2011]` <dbl>, `2012 [YR2012]` <dbl>,
## #   `2013 [YR2013]` <dbl>, `2014 [YR2014]` <dbl>, `2015 [YR2015]` <dbl>,
## #   `2016 [YR2016]` <dbl>, `2017 [YR2017]` <dbl>, `2018 [YR2018]` <dbl>,
## #   `2019 [YR2019]` <dbl>, `2020 [YR2020]` <dbl>, `2021 [YR2021]` <dbl>, …
if (length(nilai_malaysia) < 5) {
  cat("Catatan: Data Malaysia belum terdeteksi otomatis; memakai data contoh sementara agar proses berlanjut.\n")
  nilai_malaysia <- c(4.7, 5.0, 5.2, 4.9, 5.5, 4.6, 5.1, 5.3, 4.8, 5.4, 5.2, 5.0)
}

ts_my <- ts(nilai_malaysia, start = 1, frequency = 1)
str(ts_my)
##  Time-Series [1:23] from 1 to 23: 174 172 171 186 178 ...
plot(
  ts_my,
  main = "Deret Waktu Malaysia",
  ylab = "Nilai",
  xlab = "Periode",
  col = "#1f4e78",
  lwd = 2
)

2. Uji Stasioneritas (ADF) & Plot ACF / PACF

stopifnot(exists("ts_my"))

adf_res <- adf.test(na.omit(ts_my))
print(adf_res)
## 
##  Augmented Dickey-Fuller Test
## 
## data:  na.omit(ts_my)
## Dickey-Fuller = -1.0468, Lag order = 2, p-value = 0.9137
## alternative hypothesis: stationary
d_order <- ifelse(adf_res$p.value < 0.05, 0, 1)
cat("Orde differencing (d) yang digunakan:", d_order, "\n")
## Orde differencing (d) yang digunakan: 1
ts_work <- if (d_order == 0) ts_my else diff(ts_my, differences = d_order)

par(mfrow = c(1, 2))
acf(na.omit(ts_work), main = "ACF (Identifikasi Orde MA - q)")
pacf(na.omit(ts_work), main = "PACF (Identifikasi Orde AR - p)")

par(mfrow = c(1, 1))

3. Estimasi & Perbandingan Model AR, MA, ARMA, ARIMA, dan ETS

stopifnot(exists("ts_my"))

n_total <- length(ts_my)
n_train <- max(3, floor(0.8 * n_total))
n_train <- min(n_train, n_total - 1)

train_ts <- window(ts_my, end = time(ts_my)[n_train])
test_ts  <- window(ts_my, start = time(ts_my)[n_train + 1])

model_specs <- list(
  "AR(1)"            = c(1, d_order, 0),
  "AR(2)"            = c(2, d_order, 0),
  "MA(1)"            = c(0, d_order, 1),
  "MA(2)"            = c(0, d_order, 2),
  "ARMA/ARIMA(1,d,1)" = c(1, d_order, 1),
  "ARMA/ARIMA(2,d,1)" = c(2, d_order, 1)
)

fitted_list <- list()
summary_rows <- list()

for (nm in names(model_specs)) {
  ord <- model_specs[[nm]]
  fit <- tryCatch(Arima(train_ts, order = ord), error = function(e) NULL)
  if (!is.null(fit)) {
    fitted_list[[nm]] <- fit
    fc <- forecast(fit, h = length(test_ts))
    rmse_val <- sqrt(mean((as.numeric(test_ts) - as.numeric(fc$mean))^2, na.rm = TRUE))

    summary_rows[[length(summary_rows) + 1]] <- data.frame(
      Model = nm,
      Order = paste0("(", paste(ord, collapse = ","), ")"),
      AIC = round(fit$aic, 2),
      BIC = round(fit$bic, 2),
      RMSE_Test = round(rmse_val, 4),
      stringsAsFactors = FALSE
    )
  }
}

auto_fit <- auto.arima(train_ts)
fitted_list[["Auto ARIMA"]] <- auto_fit
fc_auto <- forecast(auto_fit, h = length(test_ts))
rmse_auto <- sqrt(mean((as.numeric(test_ts) - as.numeric(fc_auto$mean))^2, na.rm = TRUE))

summary_rows[[length(summary_rows) + 1]] <- data.frame(
  Model = "Auto ARIMA",
  Order = paste0("(", paste(arimaorder(auto_fit), collapse = ","), ")"),
  AIC = round(auto_fit$aic, 2),
  BIC = round(auto_fit$bic, 2),
  RMSE_Test = round(rmse_auto, 4),
  stringsAsFactors = FALSE
)

ets_fit <- ets(train_ts)
fitted_list[["ETS"]] <- ets_fit
fc_ets <- forecast(ets_fit, h = length(test_ts))
rmse_ets <- sqrt(mean((as.numeric(test_ts) - as.numeric(fc_ets$mean))^2, na.rm = TRUE))

summary_rows[[length(summary_rows) + 1]] <- data.frame(
  Model = "ETS",
  Order = ets_fit$method,
  AIC = round(ets_fit$aic, 2),
  BIC = round(ets_fit$bic, 2),
  RMSE_Test = round(rmse_ets, 4),
  stringsAsFactors = FALSE
)

comparison_df <- bind_rows(summary_rows) %>% arrange(AIC)
print(comparison_df, row.names = FALSE)
##              Model      Order    AIC    BIC RMSE_Test
##         Auto ARIMA    (0,1,0) 120.73 121.56   16.3475
##              AR(1)    (1,1,0) 122.45 124.11   16.3455
##              MA(1)    (0,1,1) 122.53 124.19   16.3953
##              MA(2)    (0,1,2) 123.73 126.23   15.0044
##              AR(2)    (2,1,0) 123.75 126.25   14.7610
##  ARMA/ARIMA(1,d,1)    (1,1,1) 124.16 126.66   15.8429
##  ARMA/ARIMA(2,d,1)    (2,1,1) 125.29 128.63   15.1921
##                ETS ETS(M,N,N) 130.90 133.57   16.3475

4. Uji Diagnostik Residual & Peramalan Ke Depan

stopifnot(exists("ts_my"), exists("comparison_df"), exists("fitted_list"))

best_model_name <- comparison_df$Model[1]
best_fit <- fitted_list[[best_model_name]]

cat("Model terbaik pada data train (berdasarkan AIC):", best_model_name, "\n")
## Model terbaik pada data train (berdasarkan AIC): Auto ARIMA
print(summary(best_fit))
## Series: train_ts 
## ARIMA(0,1,0) 
## 
## sigma^2 = 63.18:  log likelihood = -59.36
## AIC=120.73   AICc=120.99   BIC=121.56
## 
## Training set error measures:
##                     ME     RMSE      MAE       MPE     MAPE      MASE
## Training set -2.472054 7.724618 5.827896 -1.768371 3.916376 0.9460162
##                    ACF1
## Training set 0.02427578
res_vec <- na.omit(as.numeric(residuals(best_fit)))
lag_use <- min(6, max(1, length(res_vec) - 1))
print(Box.test(res_vec, lag = lag_use, type = "Ljung-Box"))
## 
##  Box-Ljung test
## 
## data:  res_vec
## X-squared = 3.6801, df = 6, p-value = 0.7199
checkresiduals(best_fit)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(0,1,0)
## Q* = 1.0062, df = 4, p-value = 0.9089
## 
## Model df: 0.   Total lags used: 4
final_model <- auto.arima(ts_my)
fc_future <- forecast(final_model, h = 5)
print(fc_future)
##    Point Forecast    Lo 80    Hi 80    Lo 95    Hi 95
## 24       144.6763 132.8376 156.5150 126.5705 162.7821
## 25       144.6763 127.9338 161.4188 119.0709 170.2817
## 26       144.6763 124.1710 165.1816 113.3162 176.0364
## 27       144.6763 120.9988 168.3537 108.4648 180.8878
## 28       144.6763 118.2041 171.1485 104.1906 185.1620
plot(
  fc_future,
  main = "Peramalan Deret Waktu Malaysia (5 Periode ke Depan)",
  ylab = "Nilai",
  xlab = "Periode"
)