# Load packages
library(tidyquant)
library(tidyverse)
library(moments)
1. Get stock prices and convert to returns
Ra <- c("X", "CMC", "ZEUS") %>%
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 X 2022-01-31 -0.134
## 2 X 2022-02-28 0.316
## 3 X 2022-03-31 0.387
## 4 X 2022-04-29 -0.192
## 5 X 2022-05-31 -0.176
## 6 X 2022-06-30 -0.286
## 7 X 2022-07-29 0.320
## 8 X 2022-08-31 -0.0309
## 9 X 2022-09-30 -0.208
## 10 X 2022-10-31 0.124
## # ℹ 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")
Rb
## # A tibble: 33 × 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
## # ℹ 23 more rows
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 X 2022-01-31 -0.134 -0.101
## 2 X 2022-02-28 0.316 -0.0343
## 3 X 2022-03-31 0.387 0.0341
## 4 X 2022-04-29 -0.192 -0.133
## 5 X 2022-05-31 -0.176 -0.0205
## 6 X 2022-06-30 -0.286 -0.0871
## 7 X 2022-07-29 0.320 0.123
## 8 X 2022-08-31 -0.0309 -0.0464
## 9 X 2022-09-30 -0.208 -0.105
## 10 X 2022-10-31 0.124 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 X 0.132 0.0202 0.270 1.36 2.44 1.89 0.504
## 2 CMC 0.111 0.0123 0.158 0.958 0.701 1.06 0.567
## 3 ZEUS 0.170 0.0224 0.304 1.16 1.83 1.45 0.456
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a positively skewed distribution of returns?
RaRb_scew <- RaRb %>%
tq_performance(Ra = Ra,
Rb = Rb,
performance_fun = CoSkewness)
RaRb_scew
## # A tibble: 3 × 2
## # Groups: symbol [3]
## symbol CoSkewness.1
## <chr> <dbl>
## 1 X -0.000163
## 2 CMC -0.0000242
## 3 ZEUS -0.000111