1. Daily Prices from 2024 to Present

library(quantmod)
library(knitr)

tickers <- c("AAPL", "MSFT", "GOOG", "AMZN", "TSM", "NVDA")

prices <- list()

for (ticker in tickers) {
  stock_data <- getSymbols(
    ticker,
    src = "yahoo",
    from = "2024-01-01",
    to = Sys.Date(),
    auto.assign = FALSE
  )
  
  prices[[ticker]] <- Ad(stock_data)
}

prices <- do.call(merge, prices)

colnames(prices) <- tickers

head(prices)
##                AAPL     MSFT     GOOG   AMZN      TSM     NVDA
## 2024-01-02 183.4040 363.1179 138.2505 149.93 98.27406 48.02879
## 2024-01-03 182.0307 362.8535 139.0430 148.47 96.95768 47.43152
## 2024-01-04 179.7189 360.2491 136.7448 144.57 95.95101 47.85929
## 2024-01-05 178.9977 360.0631 136.1009 145.24 96.41562 48.95510
## 2024-01-08 183.3250 366.8581 139.2114 149.10 98.96128 52.10199
## 2024-01-09 182.9100 367.9351 141.2224 151.37 98.62252 52.98643

2. Compute Daily Returns

Daily returns are calculated using the adjusted closing prices.

returns <- prices / lag(prices) - 1

returns <- na.omit(returns)

head(returns)
##                    AAPL          MSFT         GOOG         AMZN          TSM
## 2024-01-03 -0.007487709 -0.0007280659  0.005732427 -0.009737821 -0.013394947
## 2024-01-04 -0.012699959 -0.0071775532 -0.016528824 -0.026267892 -0.010382551
## 2024-01-05 -0.004013054 -0.0005163222 -0.004708924  0.004634420  0.004842130
## 2024-01-08  0.024174917  0.0188715579  0.022854736  0.026576704  0.026403004
## 2024-01-09 -0.002263370  0.0029358119  0.014445334  0.015224607 -0.003423161
## 2024-01-10  0.005671303  0.0185740503  0.008698075  0.015590941 -0.010697821
##                    NVDA
## 2024-01-03 -0.012435607
## 2024-01-04  0.009018578
## 2024-01-05  0.022896575
## 2024-01-08  0.064281042
## 2024-01-09  0.016975195
## 2024-01-10  0.022770001

3. First Few Daily Returns for All Stocks

return_table <- data.frame(
  Date = index(returns),
  coredata(returns)
)

kable(
  head(return_table),
  digits = 6,
  caption = "First Six Daily Returns for AAPL, MSFT, GOOG, AMZN, TSM, and NVDA"
)
First Six Daily Returns for AAPL, MSFT, GOOG, AMZN, TSM, and NVDA
Date AAPL MSFT GOOG AMZN TSM NVDA
2024-01-03 -0.007488 -0.000728 0.005732 -0.009738 -0.013395 -0.012436
2024-01-04 -0.012700 -0.007178 -0.016529 -0.026268 -0.010383 0.009019
2024-01-05 -0.004013 -0.000516 -0.004709 0.004634 0.004842 0.022897
2024-01-08 0.024175 0.018872 0.022855 0.026577 0.026403 0.064281
2024-01-09 -0.002263 0.002936 0.014445 0.015225 -0.003423 0.016975
2024-01-10 0.005671 0.018574 0.008698 0.015591 -0.010698 0.022770

4. Summary

cat("Stocks analyzed:", paste(tickers, collapse = ", "))
## Stocks analyzed: AAPL, MSFT, GOOG, AMZN, TSM, NVDA
cat("\nData period: January 1, 2024 to present")
## 
## Data period: January 1, 2024 to present
cat("\nNumber of trading days:", nrow(returns))
## 
## Number of trading days: 675

}