Answer To: Objective: Using the random forest and time series analysis in r, predict stock prices. You can use...
Hemanth answered on Nov 29 2021
# Installing required packages
install.packages("dplyr")
install.packages("randomForest")
install.packages("forecast")
# Loading required packages
library(dplyr)
library(randomForest)
library(forecast)
# ============ Starbucks Corporation =================
# Reading Starbucks Corporation dataset
SBUX <- read.csv("SBUX.csv", header = TRUE, sep = ",")
# Showing first SIX records
head(SBUX)
# Printing structure of the data
str(SBUX)
# Converting Date variable datatype
SBUX$Date <- as.Date(SBUX$Date, format = "%m/%d/%Y")
# Removing Special character(Dollor)s from "Close.Last" variable.
SBUX$Close.Last <- as.numeric(gsub("\\$", "", SBUX$Close.Last))
# Selecting data from march month 2019 stocks
period <- as.Date(c('03/01/2019','03/31/2019'),"%m/%d/%Y")
SBUX <- SBUX[SBUX$Date>=period[1] & SBUX$Date<=period[2],]
# Showing first & last SIX records of the data
head(SBUX)
tail(SBUX)
# Sorting data based on "Date" variable
SBUX <- SBUX %>% arrange(Date)
head(SBUX)
# Selecting "Close.Last" variable data
SBUX_Stock <- SBUX$Close.Last
# Summary statistics of the month of march SBUX stocks in 2019
summary(SBUX_Stock)
# Performing Random Forest model
set.seed(1234)
sbux_rf <- randomForest(SBUX_Stock ~ c(1:length(SBUX_Stock)),
importance=TRUE,
proximity=TRUE)
# Print the model
sbux_rf
# Plot the model
plot(sbux_rf, main="SBUX Stocks")
# plot Observed vs predicted values from the model
plot(SBUX_Stock,sbux_rf$predicted,
pch=19,xlab="observed Stocks",
ylab="predicted Stocks")
mtext(paste("R-squared",85.42))
# plotting residuals
plot(SBUX_Stock,c(sbux_rf$predicted - SBUX_Stock),
pch=18,ylab="residuals (predicted-observed)",
xlab="observed SBUX Stocks",
main = "Residual vs Actual",
col="blue3")
abline(h=0,col="red4",lty=1, lwd=2)
# Converting actual data into Time Series data
SBUX_ts <- ts(SBUX_Stock, frequency = 5)
# Plotting data
plot(SBUX_ts, ylab = "Stocks", main = "SBUX Stocks")
# Plotting Auto Correlation Function & Partial Auto Correlation...