library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(tseries)
library(forecast)

Stationarity Test and Model Fitting

ticker <- "SMH"
start_date <- "2018-10-02"
end_date <- "2024-03-28"

# getting the general plot
getSymbols(ticker, src = "yahoo", from = start_date, to = end_date)
## [1] "SMH"
data <- get(ticker)
adjusted_column_name <- paste(ticker, "Adjusted", sep = ".")
price_data <- data[, adjusted_column_name]
plot(index(price_data), as.numeric(price_data), main = paste(ticker, "Price Forecast"), col = "blue", type = 'l', xlab = "Date", ylab = "Adjusted Close Price")

# Splitting data into training and testing sets
split_index <- floor(0.9 * nrow(price_data))
train_data <- price_data[1:split_index]
test_data <- price_data[(split_index + 1):nrow(price_data)]

#Applying adf test
adf_result <- adf.test(train_data)
print(adf_result)
## 
##  Augmented Dickey-Fuller Test
## 
## data:  train_data
## Dickey-Fuller = -1.9762, Lag order = 10, p-value = 0.5884
## alternative hypothesis: stationary
# Fitting an ARIMA model
best_fit <- auto.arima(train_data,ic = "aic")
print(best_fit)
## Series: train_data 
## ARIMA(0,1,1) with drift 
## 
## Coefficients:
##           ma1   drift
##       -0.0908  0.0802
## s.e.   0.0285  0.0562
## 
## sigma^2 = 4.748:  log likelihood = -2726.48
## AIC=5458.97   AICc=5458.99   BIC=5474.34

Forecast Prices of ETFs

forecast_etf <- function(ticker) {
  start_date <- "2018-10-02"
  end_date <- "2024-03-28"

  getSymbols(ticker, src = "yahoo", from = start_date, to = end_date)
  data <- get(ticker)
  adjusted_column_name <- paste(ticker, "Adjusted", sep = ".")
  
  price_data <- data[, adjusted_column_name]
  
  split_index <- floor(0.9 * length(price_data))
  train_data <- price_data[1:split_index]
  test_data <- price_data[(split_index + 1):length(price_data)]

  fit <- auto.arima(train_data)

  forecasts <- forecast(fit, h = length(test_data))

  plot(index(price_data), as.numeric(price_data), main = paste(ticker, "Price Forecast"), 
       col = "blue", type = 'l', xlab = "Date", ylab = "Adjusted Close Price")
  lines(index(test_data), as.numeric(test_data), col = "red")
  forecast_dates <- index(price_data)[(split_index + 1):length(price_data)]
  lines(forecast_dates, forecasts$mean, col = "green")
  legend("topleft", legend = c("Historical Data", "Actual Test Data", "Forecasts"), 
         col = c("blue", "red", "green"), lty = 1, cex = 0.8)
}

etfs <- c("SMH", "TIME", "TINY", "TRFK", "MOON", "PSCT", "CLOU", "VGT", "XLK", "BULD")

for (ticker in etfs) {
  forecast_etf(ticker)
}