# load packages
library(tidyverse)
library(tidyquant)
1 Get Stock Prices and Convert to Returns
Ra <- c("HD", "XOM", "AXP") %>%
tq_get(get = "stock.prices",
from = "2022-01-01") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Ra")
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: 27 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 HD 2022-01-31 -0.102 -0.101
## 2 HD 2022-02-28 -0.139 -0.0343
## 3 HD 2022-03-31 -0.0465 0.0341
## 4 HD 2022-04-29 0.00357 -0.133
## 5 HD 2022-05-31 0.00782 -0.0205
## 6 HD 2022-06-30 -0.0883 -0.0871
## 7 HD 2022-07-29 0.0972 0.123
## 8 HD 2022-08-31 -0.0353 -0.0464
## 9 HD 2022-09-20 -0.0494 -0.0331
## 10 XOM 2022-01-31 0.195 -0.101
## # … with 17 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 ActiveP…¹ Alpha Annua…² Beta `Beta-` `Beta+` Corre…³ Corre…⁴ Infor…⁵
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 HD -0.045 -0.0221 -0.235 0.517 -0.0756 1.61 0.564 0.113 -0.189
## 2 XOM 1.07 0.0607 1.03 0.328 -0.0402 0.88 0.267 0.488 2.97
## 3 AXP 0.248 0.0124 0.159 0.543 0.630 1.68 0.473 0.199 0.845
## # … with 3 more variables: `R-squared` <dbl>, TrackingError <dbl>,
## # TreynorRatio <dbl>, and abbreviated variable names ¹ActivePremium,
## # ²AnnualizedAlpha, ³Correlation, ⁴`Correlationp-value`, ⁵InformationRatio
Which stock has a positively 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 HD 0.502
## 2 XOM 3946.
## 3 AXP 0.632