# Load packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("NKE", "GE", "DIS") %>%
tq_get(get = "stock.prices",
from = "2010-01-01") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Ra")
Ra
## # A tibble: 495 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 NKE 2010-01-29 -0.0245
## 2 NKE 2010-02-26 0.0604
## 3 NKE 2010-03-31 0.0916
## 4 NKE 2010-04-30 0.0328
## 5 NKE 2010-05-28 -0.0465
## 6 NKE 2010-06-30 -0.0633
## 7 NKE 2010-07-30 0.0902
## 8 NKE 2010-08-31 -0.0494
## 9 NKE 2010-09-30 0.149
## 10 NKE 2010-10-29 0.0162
## # ℹ 485 more rows
2 Get baseline and convert to returns
Rb <- "^IXIC" %>%
tq_get(get = "stock.prices",
from = "2010-01-01") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Rb")
Rb
## # A tibble: 165 × 2
## date Rb
## <date> <dbl>
## 1 2010-01-29 -0.0698
## 2 2010-02-26 0.0423
## 3 2010-03-31 0.0714
## 4 2010-04-30 0.0264
## 5 2010-05-28 -0.0829
## 6 2010-06-30 -0.0655
## 7 2010-07-30 0.0690
## 8 2010-08-31 -0.0624
## 9 2010-09-30 0.120
## 10 2010-10-29 0.0586
## # ℹ 155 more rows
3 Join the two tables
RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 495 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 NKE 2010-01-29 -0.0245 -0.0698
## 2 NKE 2010-02-26 0.0604 0.0423
## 3 NKE 2010-03-31 0.0916 0.0714
## 4 NKE 2010-04-30 0.0328 0.0264
## 5 NKE 2010-05-28 -0.0465 -0.0829
## 6 NKE 2010-06-30 -0.0633 -0.0655
## 7 NKE 2010-07-30 0.0902 0.0690
## 8 NKE 2010-08-31 -0.0494 -0.0624
## 9 NKE 2010-09-30 0.149 0.120
## 10 NKE 2010-10-29 0.0162 0.0586
## # ℹ 485 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 NKE 0.0118 0.0049 0.0601 0.772 0.877 0.790 0.548
## 2 GE -0.0985 -0.0042 -0.0492 0.955 1.18 1.05 0.524
## 3 DIS -0.0567 -0.0025 -0.0297 0.979 1.22 0.934 0.652
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a positively skewed distrabution of return?
RaRb_capm <- RaRb %>%
tq_performance(Ra = Ra,
Rb = Rb,
performance_fun = CoSkewness)
RaRb_capm
## # A tibble: 3 × 2
## # Groups: symbol [3]
## symbol CoSkewness.1
## <chr> <dbl>
## 1 NKE -0.0000248
## 2 GE -0.0000399
## 3 DIS -0.0000416