# Install packages if needed
# install.packages(c("quantmod", "tidyverse", "ggplot2"))
library(quantmod)
library(tidyverse)
library(ggplot2)
# Define stock symbols and date range
stocks <- c('AAPL', 'AMD', 'MU', 'NIO', 'NVDA', 'PRPL', 'SNAP', 'TSLA', 'TWTR')
start_date <- "2016-01-01"
end_date <- "2024-12-31"
# Download stock data
stock_data <- list()
for (stock in stocks) {
cat(paste("Downloading", stock, "...\n"))
tryCatch({
stock_data[[stock]] <- getSymbols(stock, src = "yahoo",
from = start_date,
to = end_date,
auto.assign = FALSE)
}, error = function(e) {
cat(paste("Error downloading", stock, "\n"))
})
}
## Downloading AAPL ...
## Downloading AMD ...
## Downloading MU ...
## Downloading NIO ...
## Downloading NVDA ...
## Downloading PRPL ...
## Downloading SNAP ...
## Downloading TSLA ...
## Downloading TWTR ...
## Error downloading TWTR
This plot shows the normalized stock prices for 8 major tech stocks, with all prices starting at $1 for easy comparison.
# Prepare data for normalized plot
normalized_data <- data.frame()
for (stock in stocks[1:8]) { # Exclude TWTR from first plot
if (!is.null(stock_data[[stock]])) {
df <- data.frame(
Date = index(stock_data[[stock]]),
Close = as.numeric(Cl(stock_data[[stock]]))
)
# Normalize to base = 1
df$Normalized <- df$Close / df$Close[1]
df$Stock <- stock
normalized_data <- rbind(normalized_data, df)
}
}
# Create Plot 1
ggplot(normalized_data, aes(x = Date, y = Normalized, color = Stock)) +
geom_line(linewidth = 1) +
scale_color_manual(values = c('AAPL' = 'orange', 'AMD' = 'blue',
'MU' = 'green', 'NIO' = 'purple',
'NVDA' = 'yellow', 'PRPL' = 'brown',
'SNAP' = 'red', 'TSLA' = 'pink')) +
labs(title = "Normalized Stock Prices (2016-2024)",
x = "Date",
y = "Normalized price (Base = $1)") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
legend.position = "right",
panel.grid.major = element_line(color = "gray90"),
panel.grid.minor = element_line(color = "gray95"))
This faceted plot shows the closing prices for each stock individually in a 3x3 grid layout.
# Prepare data for faceted plot
facet_data <- data.frame()
for (stock in stocks) {
if (!is.null(stock_data[[stock]])) {
df <- data.frame(
Date = index(stock_data[[stock]]),
Close = as.numeric(Cl(stock_data[[stock]])),
Stock = stock
)
facet_data <- rbind(facet_data, df)
}
}
# Create Plot 2
ggplot(facet_data, aes(x = Date, y = Close)) +
geom_line(color = "darkblue", linewidth = 0.8) +
facet_wrap(~ Stock, scales = "free_y", ncol = 3) +
labs(title = "",
x = "Date",
y = "") +
theme_minimal() +
theme(strip.background = element_rect(fill = "lightgray", color = "lightgray"),
strip.text = element_text(size = 11, face = "bold"),
panel.grid.major = element_line(color = "gray90"),
panel.grid.minor = element_line(color = "gray95"),
axis.text = element_text(size = 8)) +
ylab("Closing prices")
Both plots successfully visualize stock price trends from 2016 to 2024: