library(quantmod)
## Warning: package 'quantmod' was built under R version 4.4.3
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.4.3
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 4.4.3
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 4.4.3
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
getSymbols("AAPL", from = "2015-01-01", to = Sys.Date(), src = "yahoo")
## [1] "AAPL"
head(AAPL)
## AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
## 2015-01-02 27.8475 27.8600 26.8375 27.3325 212818400 24.28858
## 2015-01-05 27.0725 27.1625 26.3525 26.5625 257142000 23.60433
## 2015-01-06 26.6350 26.8575 26.1575 26.5650 263188400 23.60656
## 2015-01-07 26.8000 27.0500 26.6750 26.9375 160423600 23.93757
## 2015-01-08 27.3075 28.0375 27.1750 27.9725 237458000 24.85731
## 2015-01-09 28.1675 28.3125 27.5525 28.0025 214798000 24.88396
apple_prices <- AAPL[, "AAPL.Adjusted"]
plot(apple_prices, main = "Apple Adjusted Closing Price")

library(tseries)
## Warning: package 'tseries' was built under R version 4.4.3
adf.test(na.omit(as.numeric(apple_prices)))
##
## Augmented Dickey-Fuller Test
##
## data: na.omit(as.numeric(apple_prices))
## Dickey-Fuller = -2.8219, Lag order = 13, p-value = 0.2304
## alternative hypothesis: stationary
apple_diff <- diff(apple_prices, lag = 1)
plot(apple_diff, main = "First Difference of Apple Prices")

library(forecast)
## Warning: package 'forecast' was built under R version 4.4.3
fit <- auto.arima(apple_prices)
summary(fit)
## Series: apple_prices
## ARIMA(0,1,0) with drift
##
## Coefficients:
## drift
## 0.0671
## s.e. 0.0426
##
## sigma^2 = 4.796: log likelihood = -5806.05
## AIC=11616.11 AICc=11616.11 BIC=11627.86
##
## Training set error measures:
## ME RMSE MAE MPE MAPE MASE
## Training set 9.185247e-06 2.18906 1.290308 -0.05802689 1.274627 0.9987194
## ACF1
## Training set -0.00497109
forecast_apple <- forecast(fit, h = 30)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(forecast)
autoplot(forecast_apple) +
labs(
title = "30-Day Forecast of Apple Stock Price",
x = "Date",
y = "Adjusted Close Price (USD)"
) +
scale_x_continuous(
labels = function(x) as.Date(x, origin = "1970-01-01"),
breaks = pretty(time(forecast_apple$mean), n = 10)
) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
## Scale for x is already present.
## Adding another scale for x, which will replace the existing scale.
