# Load packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("TLSA", "HD", "MSFT") %>%
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: 63 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 TLSA 2022-01-31 -0.239
## 2 TLSA 2022-02-28 -0.217
## 3 TLSA 2022-03-31 0.615
## 4 TLSA 2022-04-29 -0.0286
## 5 TLSA 2022-05-31 -0.353
## 6 TLSA 2022-06-30 0.136
## 7 TLSA 2022-07-29 -0.0267
## 8 TLSA 2022-08-31 0.0411
## 9 TLSA 2022-09-30 0.0263
## 10 TLSA 2022-10-31 -0.103
## # ℹ 53 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: 21 × 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
## # ℹ 11 more rows
3 Join the two tables
RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 63 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 TLSA 2022-01-31 -0.239 -0.101
## 2 TLSA 2022-02-28 -0.217 -0.0343
## 3 TLSA 2022-03-31 0.615 0.0341
## 4 TLSA 2022-04-29 -0.0286 -0.133
## 5 TLSA 2022-05-31 -0.353 -0.0205
## 6 TLSA 2022-06-30 0.136 -0.0871
## 7 TLSA 2022-07-29 -0.0267 0.123
## 8 TLSA 2022-08-31 0.0411 -0.0464
## 9 TLSA 2022-09-30 0.0263 -0.105
## 10 TLSA 2022-10-31 -0.103 0.0390
## # ℹ 53 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 TLSA -0.151 0.015 0.195 1.06 -0.921 1.21 0.263
## 2 HD -0.0322 -0.0057 -0.0664 0.583 -0.102 0.380 0.607
## 3 MSFT 0.0766 0.0054 0.0662 0.811 0.778 0.325 0.844
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
which stock has a positively skewd distribution of return?
RaRb_capm <- RaRb %>%
tq_performance(Ra = Ra,
Rb = Rb,
performance_fun = SkewnessKurtosisRatio)
RaRb_capm
## # A tibble: 3 × 2
## # Groups: symbol [3]
## symbol SkewnessKurtosisRatio.1
## <chr> <dbl>
## 1 TLSA 0.285
## 2 HD 0.0378
## 3 MSFT 0.172