# Load Packages
library(tidyverse)
library(tidyquant)

Get stock prices and convert to returns

Ra <- c("GM", "DKNG", "PFE") %>%
    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: 99 × 3
## # Groups:   symbol [3]
##    symbol date            Ra
##    <chr>  <date>       <dbl>
##  1 GM     2022-01-31 -0.138 
##  2 GM     2022-02-28 -0.114 
##  3 GM     2022-03-31 -0.0638
##  4 GM     2022-04-29 -0.133 
##  5 GM     2022-05-31  0.0203
##  6 GM     2022-06-30 -0.179 
##  7 GM     2022-07-29  0.142 
##  8 GM     2022-08-31  0.0562
##  9 GM     2022-09-30 -0.160 
## 10 GM     2022-10-31  0.223 
## # ℹ 89 more rows

2 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")

3 join the two tables

RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 99 × 4
## # Groups:   symbol [3]
##    symbol date            Ra      Rb
##    <chr>  <date>       <dbl>   <dbl>
##  1 GM     2022-01-31 -0.138  -0.101 
##  2 GM     2022-02-28 -0.114  -0.0343
##  3 GM     2022-03-31 -0.0638  0.0341
##  4 GM     2022-04-29 -0.133  -0.133 
##  5 GM     2022-05-31  0.0203 -0.0205
##  6 GM     2022-06-30 -0.179  -0.0871
##  7 GM     2022-07-29  0.142   0.123 
##  8 GM     2022-08-31  0.0562 -0.0464
##  9 GM     2022-09-30 -0.160  -0.105 
## 10 GM     2022-10-31  0.223   0.0390
## # ℹ 89 more rows

4 calculate CAPM

RaRb_capm <- RaRb %>%
    tq_performance(Ra = Ra,
                   Rb = Rb,
                   performance_fun = table.CAPM)
RaRb_capm
## # A tibble: 3 × 13
## # Groups:   symbol [3]
##   symbol ActivePremium   Alpha AnnualizedAlpha  Beta `Beta-` `Beta+` Correlation
##   <chr>          <dbl>   <dbl>           <dbl> <dbl>   <dbl>   <dbl>       <dbl>
## 1 GM           -0.120  -0.0075         -0.0866 1.26    1.06    0.888       0.729
## 2 DKNG          0.0911  0.0143          0.186  1.49    2.77    2.03        0.616
## 3 PFE          -0.212  -0.0147         -0.162  0.211   0.379  -0.277       0.207
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## #   `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>

which stock has a positive skewed distribution of returns?

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 GM                     2.06
## 2 DKNG                   2.63
## 3 PFE                    1.24