# Load Packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("TSLA", "DKNG", "SMCI") %>%
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: 87 × 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-30 -0.0376
## 10 TSLA 2022-10-31 -0.142
## # ℹ 77 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")
Rb
## # A tibble: 29 × 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-30 -0.105
## 10 2022-10-31 0.0390
## # ℹ 19 more rows
3 Join the two tables
RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 87 × 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-30 -0.0376 -0.105
## 10 TSLA 2022-10-31 -0.142 0.0390
## # ℹ 77 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 TSLA -0.310 -0.0185 -0.201 1.80 1.79 4.42 0.658
## 2 DKNG 0.145 0.0189 0.251 1.55 3.00 1.88 0.660
## 3 SMCI 2.38 0.133 3.48 1.72 1.42 -1.60 0.385
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a postively 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 TSLA 1.76
## 2 DKNG 2.86
## 3 SMCI 21.8