install.packages("quantmod")
library(quantmod)
# Fetch Apple Inc. stock data for the past year
getSymbols("AAPL", from = Sys.Date() - 365, to = Sys.Date())
# Extract the closing prices from the data
apple_stock <- AAPL$AAPL.Close
# Create a date sequence for the x-axis
dates <- index(apple_stock)
# Create a step line plot
plot(dates, apple_stock, type = "s", lwd = 2, col = "blue",
xlab = "Date", ylab = "Stock Price (USD)",
main = "Apple Inc. Stock Price (Past Year)")
# Add grid lines
grid(lty = 3, col = "gray")
# Highlight significant events with vertical lines
abline(v = as.Date(c("2023-01-03", "2023-03-01", "2023-06-01", "2023-09-01")),
lty = 2, col = "red")
# Add data points at significant events
points(as.Date(c("2023-01-03", "2023-03-01", "2023-06-01", "2023-09-01")),
apple_stock[c(1, 60, 125, length(apple_stock))], pch = 19, col = "red")
# Add a legend
legend("topleft", legend = "Significant Events", col = "red", pch = 19, lty = 2)
# Add a horizontal line at the initial stock price
abline(h = apple_stock[1], lty = 2, col = "green")
# Annotate the initial stock price
text(dates[1], apple_stock[1], paste("Initial Price: $", round(apple_stock[1], 2)),
pos = 4, col = "green", cex = 0.8)