We download daily stock price data for Apple (AAPL), Microsoft (MSFT), Alphabet (GOOG), Amazon (AMZN), Taiwan Semiconductor Manufacturing Company (TSM), and NVIDIA (NVDA) from January 1, 2024 to the present.
library(quantmod)
library(dplyr)
library(tidyr)
library(knitr)
library(ggplot2)
# Stock tickers
tickers <- c("AAPL", "MSFT", "GOOG", "AMZN", "TSM", "NVDA")
# Download daily stock data
getSymbols(
tickers,
src = "yahoo",
from = "2024-01-01",
to = Sys.Date(),
auto.assign = TRUE
)
## [1] "AAPL" "MSFT" "GOOG" "AMZN" "TSM" "NVDA"
Daily stock returns are calculated using the adjusted closing price:
\[ R_t = \frac{P_t-P_{t-1}}{P_{t-1}} \]
where \(P_t\) is the adjusted closing price on day \(t\).
# Extract adjusted closing prices
prices <- do.call(
merge,
lapply(tickers, function(ticker) {
Ad(get(ticker))
})
)
# Rename columns
colnames(prices) <- tickers
# Calculate daily returns
returns <- na.omit(prices / lag(prices) - 1)
# Convert returns to a data frame
returns_df <- data.frame(
Date = index(returns),
coredata(returns)
)
The table below shows the first five daily returns for all six stocks.
returns_df %>%
head(5) %>%
mutate(
across(
all_of(tickers),
~ round(.x * 100, 4)
)
) %>%
kable(
caption = "First Five Daily Returns (%)"
)
| Date | AAPL | MSFT | GOOG | AMZN | TSM | NVDA |
|---|---|---|---|---|---|---|
| 2024-01-03 | -0.7488 | -0.0728 | 0.5733 | -0.9738 | -1.3395 | -1.2436 |
| 2024-01-04 | -1.2700 | -0.7178 | -1.6529 | -2.6268 | -1.0382 | 0.9019 |
| 2024-01-05 | -0.4013 | -0.0516 | -0.4708 | 0.4634 | 0.4842 | 2.2897 |
| 2024-01-08 | 2.4175 | 1.8872 | 2.2854 | 2.6577 | 2.6403 | 6.4281 |
| 2024-01-09 | -0.2263 | 0.2936 | 1.4445 | 1.5225 | -0.3423 | 1.6975 |
prices_df <- data.frame(
Date = index(prices),
coredata(prices)
)
head(prices_df, 5) %>%
mutate(
across(
all_of(tickers),
~ round(.x, 2)
)
) %>%
kable(
caption = "First Five Adjusted Closing Prices"
)
| Date | AAPL | MSFT | GOOG | AMZN | TSM | NVDA |
|---|---|---|---|---|---|---|
| 2024-01-02 | 183.40 | 363.12 | 138.25 | 149.93 | 98.27 | 48.03 |
| 2024-01-03 | 182.03 | 362.85 | 139.04 | 148.47 | 96.96 | 47.43 |
| 2024-01-04 | 179.72 | 360.25 | 136.74 | 144.57 | 95.95 | 47.86 |
| 2024-01-05 | 179.00 | 360.06 | 136.10 | 145.24 | 96.42 | 48.96 |
| 2024-01-08 | 183.32 | 366.86 | 139.21 | 149.10 | 98.96 | 52.10 |
The daily stock prices for AAPL, MSFT, GOOG, AMZN, TSM, and NVDA were downloaded from Yahoo Finance from January 2024 to the present. Daily returns were calculated from the adjusted closing prices, and the first five daily returns for all six stocks are presented above.