# Load packages 
library(tidyverse)
library(tidyquant)

Get Stock price and convert to returns

Ra <- c("TSLA", "DIS", "BAC") %>%
    tq_get(get  = "stock.prices",
           from = "2022-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 TSLA   2022-01-31 -0.219 
##  2 TSLA   2022-02-28 -0.0708
##  3 TSLA   2022-03-31  0.238 
##  4 TSLA   2022-04-29 -0.192 
##  5 TSLA   2022-05-31 -0.129 
##  6 TSLA   2022-06-30 -0.112 
##  7 TSLA   2022-07-29  0.324 
##  8 TSLA   2022-08-31 -0.0725
##  9 TSLA   2022-09-21  0.0914
## 10 DIS    2022-01-31 -0.0880
## # … with 17 more rows

get baseline and convert to returns

Rb <- "^IXIC" %>%
    tq_get(get  = "stock.prices",
           from = "2022-01-01") %>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly", 
                 col_rename = "Rb")
Rb
## # A tibble: 9 × 2
##   date            Rb
##   <date>       <dbl>
## 1 2022-01-31 -0.101 
## 2 2022-02-28 -0.0343
## 3 2022-03-31  0.0341
## 4 2022-04-29 -0.133 
## 5 2022-05-31 -0.0205
## 6 2022-06-30 -0.0871
## 7 2022-07-29  0.123 
## 8 2022-08-31 -0.0464
## 9 2022-09-21 -0.0504

Join the two data 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 TSLA   2022-01-31 -0.219  -0.101 
##  2 TSLA   2022-02-28 -0.0708 -0.0343
##  3 TSLA   2022-03-31  0.238   0.0341
##  4 TSLA   2022-04-29 -0.192  -0.133 
##  5 TSLA   2022-05-31 -0.129  -0.0205
##  6 TSLA   2022-06-30 -0.112  -0.0871
##  7 TSLA   2022-07-29  0.324   0.123 
##  8 TSLA   2022-08-31 -0.0725 -0.0464
##  9 TSLA   2022-09-21  0.0914 -0.0504
## 10 DIS    2022-01-31 -0.0880 -0.101 
## # … with 17 more rows

Calculate CAPM

RaRb_capm <- RaRb %>%
    tq_performance(Ra = Ra, 
                   Rb = Rb, 
                   performance_fun = VolatilitySkewness)
RaRb_capm
## # A tibble: 3 × 2
## # Groups:   symbol [3]
##   symbol VolatilitySkewness.1
##   <chr>                 <dbl>
## 1 TSLA                  3.28 
## 2 DIS                   1.32 
## 3 BAC                   0.743

Which stock has a positively skewed distribution of returns