Load Required Libraries
library(tidyverse)
library(tidyquant)
library(lubridate)
Data Collection
Download Stock Data
# Define stock symbols
stock_symbols <- c("AAPL", "AMD", "MU", "NIO", "NVDA", "PRPL", "SNAP", "TSLA")
# Download stock data from 2016 to 2024
stock_prices <- tq_get(stock_symbols,
from = "2016-01-01",
to = "2024-12-31",
get = "stock.prices")
# Display summary
cat("Total observations:", nrow(stock_prices), "\n")
## Total observations: 17134
cat("Date range:", min(stock_prices$date), "to", max(stock_prices$date), "\n")
## Date range: 16804 to 20087
Data Preview
# View first few rows
head(stock_prices, 10)
## # A tibble: 10 × 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2016-01-04 25.7 26.3 25.5 26.3 270597600 23.8
## 2 AAPL 2016-01-05 26.4 26.5 25.6 25.7 223164000 23.2
## 3 AAPL 2016-01-06 25.1 25.6 25.0 25.2 273829600 22.7
## 4 AAPL 2016-01-07 24.7 25.0 24.1 24.1 324377600 21.7
## 5 AAPL 2016-01-08 24.6 24.8 24.2 24.2 283192000 21.9
## 6 AAPL 2016-01-11 24.7 24.8 24.3 24.6 198957600 22.2
## 7 AAPL 2016-01-12 25.1 25.2 24.7 25.0 196616800 22.5
## 8 AAPL 2016-01-13 25.1 25.3 24.3 24.3 249758400 22.0
## 9 AAPL 2016-01-14 24.5 25.1 23.9 24.9 252680400 22.4
## 10 AAPL 2016-01-15 24.0 24.4 23.8 24.3 319335600 21.9
# Summary statistics
summary(stock_prices %>% select(symbol, close, volume))
## symbol close volume
## Length:17134 Min. : 0.564 Min. :0.000e+00
## Class :character 1st Qu.: 10.050 1st Qu.:1.993e+07
## Mode :character Median : 24.017 Median :5.210e+07
## Mean : 54.663 Mean :1.144e+08
## 3rd Qu.: 71.667 3rd Qu.:1.121e+08
## Max. :479.860 Max. :3.693e+09
Visualization
Plot 1: Normalized Stock Prices (All Stocks)
plot1 <- stock_normalized %>%
ggplot(aes(x = date, y = normalized_price, color = symbol)) +
geom_line(linewidth = 0.8) +
labs(
title = "Normalized Stock Prices (2016-2024)",
x = "Date",
y = "Normalized price (Base = $1)",
color = "Stock"
) +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, face = "bold", size = 14),
legend.position = "right",
panel.grid.minor = element_blank()
) +
scale_y_continuous(breaks = seq(0, 200, 50))
print(plot1)

Plot 2: Individual Stock Charts (Faceted)
# Download stock data for plot 2
stocks_plot2 <- c("AAPL", "AMD", "MU", "NIO", "NVDA", "PRPL", "SNAP", "TSLA")
stock_prices_plot2 <- tq_get(stocks_plot2,
from = "2016-01-01",
to = "2023-12-31",
get = "stock.prices")
plot2 <- stock_prices_plot2 %>%
ggplot(aes(x = date, y = close)) +
geom_line(color = "navy", linewidth = 0.6) +
facet_wrap(~ symbol, scales = "free_y", ncol = 3) +
labs(
x = "Date",
y = "Closing prices"
) +
theme_minimal() +
theme(
strip.background = element_rect(fill = "gray85", color = NA),
strip.text = element_text(face = "bold", size = 11),
panel.grid.minor = element_blank(),
axis.text = element_text(size = 9)
)
print(plot2)
