# Load required libraries library(quantmod) library(forecast) library(genalg) # Function to calculate the Mean Absolute Error (MAE) mape <- function(actual, forecast) { mean(abs((actual - forecast) / actual)) * 100 } # Fetch stock prices using quantmod getSymbols("HDFCBANK.NS", from = "2014-01-01", to = "2022-12-31", src = "yahoo") prices <- Cl(HDFCBANK.NS) # Set training and validation data split <- round(0.8 * length(prices)) training_data <- prices[1:split] validation_data <- prices[(split + 1):length(prices)] # Set GWO parameters maxorder <- 3 # Maximum order for ARIMA num_dimensions <- 2 * maxorder + 1 # Number of parameters to be optimized population_size <- 20 # Number of individuals in each generation max_iter <- 50 # Maximum number of generations # Define the objective function for GWO gwo_objective <- function(x) { order <- round(x[1]) ar <- x[2:(order + 1)] ma <- x[(order + 2):(2 * order + 1)] model <- Arima(training_data, order = c(order, 0, 0), seasonal = FALSE, include.mean = FALSE) model_coef <- coef(model) # Set AR coefficients for (i in seq_along(ar)) { model_coef[names(model_coef) == paste0("ar", i)] <- ar[i] } # Set MA coefficients for (i in seq_along(ma)) { model_coef[names(model_coef) == paste0("ma", i)] <- ma[i] } model$coef <- model_coef forecast <- forecast(model, h = length(validation_data))$mean error <- mape(validation_data, forecast) return(error) } # Define the search space for GWO search_space <- rbga.bin(size = num_dimensions, popSize = population_size, iters = max_iter, mutationChance = 0.01, evalFunc = gwo_objective) # Extract the optimized parameters best_order <- ifelse(is.numeric(search_space$bestIndiv[1]), round(search_space$bestIndiv[1]), 1) best_ar <- search_space$bestIndiv[2:(best_order + 1)] best_ma <- search_space$bestIndiv[(best_order + 2):(2 * best_order + 1)] # Build the ARIMA model using the optimized parameters best_model <- Arima(training_data, order = c(best_order, 0, 0), seasonal = FALSE, include.mean = FALSE) model_coef <- coef(best_model) # Set AR coefficients for (i in seq_along(best_ar)) { model_coef[names(model_coef) == paste0("ar", i)] <- best_ar[i] } # Set MA coefficients for (i in seq_along(best_ma)) { model_coef[names(model_coef) == paste0("ma", i)] <- best_ma[i] } best_model$coef <- model_coef # Forecast future Apple stock prices forecast <- forecast(best_model, h = 3000) # Convert actual and predicted to numeric vectors actual <- as.numeric(validation_data) predicted <- as.numeric(forecast$mean) # Calculate RMSE and MSE rmse <- sqrt(mean((actual - predicted)^2)) mse <- mean((actual - predicted)^2) # Print RMSE and MSE cat("RMSE:", rmse, "\n") cat("MSE:", mse, "\n") # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "AXISBANK.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) #### hdfc bank # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "HDFCBANK.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) #### ##### #### SBI bank # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "SBIN.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) #### ADANI PORT #### # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "ADANIPORTS.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) ######infy #### # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "INFY.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) ####tcs # Load required libraries library(quantmod) library(rugarch) library(ggplot2) # Define the stock symbol and download stock price data symbol <- "TCS.NS" # Replace with the desired stock symbol getSymbols(symbol) stock_data <- na.omit(Ad(get(symbol))) # Split the data into training and testing sets n <- nrow(stock_data) train_data <- stock_data[1:round(0.8 * n), ] test_data <- stock_data[(round(0.8 * n) + 1):n, ] # Get the column name for stock price price_col <- colnames(train_data)[1] # Fit the GARCH(1,1) model garch_spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0)), distribution.model = "std") garch_fit <- ugarchfit(spec = garch_spec, data = train_data[, price_col]) # Set the forecast horizon horizon <- nrow(test_data) # Forecast the volatility garch_forecast <- ugarchforecast(garch_fit, n.ahead = horizon) predicted_volatility <- sigma(garch_forecast) # Convert test_data to a data frame test_data_df <- data.frame(Time = index(test_data), Actual = as.vector(test_data[, price_col]), Volatility = as.vector(predicted_volatility)) # Plot actual and predicted stock prices ggplot(test_data_df, aes(x = Time)) + geom_line(aes(y = Actual, color = "Actual"), linetype = "solid") + geom_line(aes(y = Volatility, color = "Predicted"), linetype = "dashed") + labs(x = "Time", y = "Stock Price / Volatility", color = "Legend") + scale_color_manual(values = c("Actual" = "blue", "Predicted" = "red")) + theme_minimal() # QQ plot for residuals residuals <- residuals(garch_fit) qqnorm(residuals) qqline(residuals) ### # QQ plot for residuals residuals <- residuals(garch_fit) # Open a new plot window par(new = TRUE) # Generate the QQ plot qqnorm(residuals) qqline(residuals) # Install and load the required packages library(quantmod) # Define the stock symbol and the time range stock_symbol <- "AXISBANK.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "Axis Bank Stock Price", ylab = "Volatility", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "Axis Bank Stock Prices", ylab = "Price", xlab = "Date") ####hdfc # Define the stock symbol and the time range stock_symbol <- "HDFCBANK.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "HDFC Bank Stock Price", ylab = "Volatility", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "HDFC Bank Stock Prices", ylab = "Price", xlab = "Date") ####sbi # Define the stock symbol and the time range stock_symbol <- "SBIN.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "SBI Bank Stock Price", ylab = "Volatility", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "SBIN Bank Stock Prices", ylab = "Price", xlab = "Date") #### ####adni port # Define the stock symbol and the time range stock_symbol <- "ADANIPORTS.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "Adani Port Stock", ylab = "Volatility", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "Adani Port Stock Prices", ylab = "Price", xlab = "Date") ###infosys stock_symbol <- "INFY.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "Infosys Stock", ylab = "Volatility", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "Infosys Stock Prices", ylab = "Price", xlab = "Date") ###tcs stock_symbol <- "TCS.NS" start_date <- "2023-01-01" end_date <- "2023-05-17" # Download the stock data using the getSymbols function getSymbols(stock_symbol, from = start_date, to = end_date) # Calculate the daily volatility using the volatility function volatility <- volatility(Cl(get(stock_symbol))) # Plot the volatility with appropriate labeling plot(volatility, type = "l", main = "TCS Stock", ylab = "Volatility", xlab = "Date") # Extract the adjusted close prices stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "TCS Stock Prices", ylab = "Price", xlab = "Date") stock_prices <- Ad(get(stock_symbol)) # Plot the stock prices with appropriate labeling plot(stock_prices, type = "l", main = "TCS Stock Prices", ylab = "Price", xlab = "Date") #########garch # Install and load required packages # Install and load required packages # Install and load required packages install.packages(c("ggplot2", "quantmod", "rugarch")) library(ggplot2) library(quantmod) library(rugarch) # Set the stock symbol and start/end dates for data retrieval stock_symbol <- "AAPL" # Change this to your desired stock symbol start_date <- as.Date("2020-01-01") end_date <- Sys.Date() # Download stock price data using quantmod getSymbols(stock_symbol, from = start_date, to = end_date) # Extract adjusted closing prices stock_data <- Ad(get(stock_symbol)) stock_data <- na.omit(stock_data) # Remove any missing values # Fit GARCH(1, 1) model to predict returns garch_model <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1))) garch_fit <- ugarchfit(spec = garch_model, data = stock_data) # Predict returns using the fitted GARCH model returns_forecast <- ugarchforecast(garch_fit, n.ahead = 20) predicted_returns <- tail(returns_forecast@forecast$seriesFor, 20) # Calculate predicted prices last_price <- stock_data[length(stock_data)] predicted_prices <- last_price * (1 + cumsum(predicted_returns)) # Create a dataframe with actual and predicted prices price_df <- data.frame( Date = index(stock_data), Actual = coredata(stock_data), Predicted = c(rep(NA, length(stock_data) - length(predicted_prices)), predicted_prices) ) # Convert Date to a regular column price_df$Date <- as.Date(price_df$Date) # Plot actual and predicted prices ggplot(price_df, aes(x = Date)) + geom_line(aes(y = Actual, color = "Actual")) + geom_line(aes(y = Predicted, color = "Predicted"), linetype = "dashed") + scale_color_manual( values = c(Actual = "blue", Predicted = "red"), labels = c(Actual = "Actual", Predicted = "Predicted") ) + labs(title = paste("Actual vs Predicted Stock Prices for", stock_symbol), x = "Date", y = "Price") + theme_minimal()