# Load packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("ADDYY", "NKE", "WMT") %>%
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: 171 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 ADDYY 2022-01-31 -0.0722
## 2 ADDYY 2022-02-28 -0.137
## 3 ADDYY 2022-03-31 -0.00866
## 4 ADDYY 2022-04-29 -0.143
## 5 ADDYY 2022-05-31 0.0105
## 6 ADDYY 2022-06-30 -0.106
## 7 ADDYY 2022-07-29 -0.0278
## 8 ADDYY 2022-08-31 -0.139
## 9 ADDYY 2022-09-30 -0.226
## 10 ADDYY 2022-10-31 -0.151
## # ℹ 161 more rows
Get baseline and convert to returns
Rb <- "^IXIC" %>%
tq_get(get = "stock.prices",
from = "2022-01-01") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Rb")
Rb
## # A tibble: 57 × 3
## # Groups: symbol [1]
## symbol date Rb
## <chr> <date> <dbl>
## 1 ^IXIC 2022-01-31 -0.101
## 2 ^IXIC 2022-02-28 -0.0343
## 3 ^IXIC 2022-03-31 0.0341
## 4 ^IXIC 2022-04-29 -0.133
## 5 ^IXIC 2022-05-31 -0.0205
## 6 ^IXIC 2022-06-30 -0.0871
## 7 ^IXIC 2022-07-29 0.123
## 8 ^IXIC 2022-08-31 -0.0464
## 9 ^IXIC 2022-09-30 -0.105
## 10 ^IXIC 2022-10-31 0.0390
## # ℹ 47 more rows
3 Join the two tables
RaRb <- left_join(Ra, Rb, by = "date") %>%
select(symbol.x, date, Ra, Rb)
4 Calculate CAPM
RaRb_capm <- RaRb %>%
group_by(symbol.x) %>%
tq_performance(
Ra = Ra,
Rb = Rb,
performance_fun = table.CAPM)
RaRb_capm
## # A tibble: 3 × 18
## # Groups: symbol.x [3]
## symbol.x ActivePremium Alpha AlphaRobust AnnualizedAlpha Beta `Beta-`
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 ADDYY -0.225 -0.0136 -0.0173 -0.151 0.899 1.13
## 2 NKE -0.380 -0.027 -0.0206 -0.280 0.581 0.796
## 3 WMT 0.0784 0.0132 0.0186 0.170 0.335 0.369
## # ℹ 11 more variables: `Beta-Robust` <dbl>, `Beta+` <dbl>, `Beta+Robust` <dbl>,
## # BetaRobust <dbl>, Correlation <dbl>, `Correlationp-value` <dbl>,
## # InformationRatio <dbl>, `R-squared` <dbl>, `R-squaredRobust` <dbl>,
## # TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a positively skewed distribution of returns?
RaRb_capm <- RaRb %>%
group_by(symbol.x) %>%
tq_performance(
Ra = Ra,
Rb = Rb,
performance_fun = table.HigherMoments,
)
RaRb_capm
## # A tibble: 3 × 6
## # Groups: symbol.x [3]
## symbol.x BetaCoKurtosis BetaCoSkewness BetaCoVariance CoKurtosis CoSkewness
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 ADDYY 0.894 1.07 0.899 0 0
## 2 NKE 0.449 2.73 0.581 0 -0.0001
## 3 WMT 0.276 1.65 0.335 0 0
RaRb %>%
group_by(symbol.x) %>%
summarise(
Skewness = skewness(Ra, na.rm = TRUE)
)
## # A tibble: 3 × 2
## symbol.x Skewness
## <chr> <dbl>
## 1 ADDYY 0.465
## 2 NKE -0.0511
## 3 WMT -0.374