# Load packages
library(tidyverse)
library(tidyquant)

1 Get stock prices and convert to returns

Ra <- c("RIVN", "F", "LCID") %>%
    tq_get(get  = "stock.prices",
           from = "2025-01-01") %>%
    group_by(symbol) %>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly", 
                 col_rename = "Ra")
Ra
## # A tibble: 27 × 3
## # Groups:   symbol [3]
##    symbol date            Ra
##    <chr>  <date>       <dbl>
##  1 RIVN   2025-01-31 -0.0521
##  2 RIVN   2025-02-28 -0.0573
##  3 RIVN   2025-03-31  0.0515
##  4 RIVN   2025-04-30  0.0972
##  5 RIVN   2025-05-30  0.0637
##  6 RIVN   2025-06-30 -0.0544
##  7 RIVN   2025-07-31 -0.0633
##  8 RIVN   2025-08-29  0.0544
##  9 RIVN   2025-09-16  0.0553
## 10 F      2025-01-31  0.0446
## # ℹ 17 more rows

2 Get baseline and convert to returns

Rb <- "^IXIC" %>%
    tq_get(get  = "stock.prices",
           from = "2025-01-01") %>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly", 
                 col_rename = "Rb")
Rb
## # A tibble: 9 × 2
##   date             Rb
##   <date>        <dbl>
## 1 2025-01-31  0.0180 
## 2 2025-02-28 -0.0397 
## 3 2025-03-31 -0.0821 
## 4 2025-04-30  0.00850
## 5 2025-05-30  0.0956 
## 6 2025-06-30  0.0657 
## 7 2025-07-31  0.0370 
## 8 2025-08-29  0.0158 
## 9 2025-09-16  0.0409

3 Join the two tables

RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 27 × 4
## # Groups:   symbol [3]
##    symbol date            Ra       Rb
##    <chr>  <date>       <dbl>    <dbl>
##  1 RIVN   2025-01-31 -0.0521  0.0180 
##  2 RIVN   2025-02-28 -0.0573 -0.0397 
##  3 RIVN   2025-03-31  0.0515 -0.0821 
##  4 RIVN   2025-04-30  0.0972  0.00850
##  5 RIVN   2025-05-30  0.0637  0.0956 
##  6 RIVN   2025-06-30 -0.0544  0.0657 
##  7 RIVN   2025-07-31 -0.0633  0.0370 
##  8 RIVN   2025-08-29  0.0544  0.0158 
##  9 RIVN   2025-09-16  0.0553  0.0409 
## 10 F      2025-01-31  0.0446  0.0180 
## # ℹ 17 more rows

4 Calculate CAPM

RaRb_capm <- RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM)

RaRb_capm

Which stock has a positively skewed distribution of returns?