# Load Package
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("LULU", "AMZN", "TSLA") %>%
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: 27 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 LULU 2022-01-31 -0.139
## 2 LULU 2022-02-28 -0.0414
## 3 LULU 2022-03-31 0.142
## 4 LULU 2022-04-29 -0.0290
## 5 LULU 2022-05-31 -0.175
## 6 LULU 2022-06-30 -0.0686
## 7 LULU 2022-07-29 0.139
## 8 LULU 2022-08-31 -0.0340
## 9 LULU 2022-09-21 0.0605
## 10 AMZN 2022-01-31 -0.122
## # … with 17 more rows
2 Get baseline and convert to returns
Rb <- "XLK" %>%
tq_get(get = "stock.prices",
from = "2022-01-01") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Rb")
Rb
## # A tibble: 9 × 2
## date Rb
## <date> <dbl>
## 1 2022-01-31 -0.0772
## 2 2022-02-28 -0.0488
## 3 2022-03-31 0.0335
## 4 2022-04-29 -0.110
## 5 2022-05-31 -0.00686
## 6 2022-06-30 -0.0926
## 7 2022-07-29 0.135
## 8 2022-08-31 -0.0621
## 9 2022-09-21 -0.0612
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 LULU 2022-01-31 -0.139 -0.0772
## 2 LULU 2022-02-28 -0.0414 -0.0488
## 3 LULU 2022-03-31 0.142 0.0335
## 4 LULU 2022-04-29 -0.0290 -0.110
## 5 LULU 2022-05-31 -0.175 -0.00686
## 6 LULU 2022-06-30 -0.0686 -0.0926
## 7 LULU 2022-07-29 0.139 0.135
## 8 LULU 2022-08-31 -0.0340 -0.0621
## 9 LULU 2022-09-21 0.0605 -0.0612
## 10 AMZN 2022-01-31 -0.122 -0.0772
## # … with 17 more rows
4 Caculate CAPM
RaRb_capm <- RaRb %>%
tq_performance(Ra = Ra,
Rb = Rb,
performance_fun = table.CAPM)
RaRb_capm
## # A tibble: 3 × 13
## # Groups: symbol [3]
## symbol ActivePr…¹ Alpha Annua…² Beta `Beta-` `Beta+` Corre…³ Corre…⁴ Infor…⁵
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 LULU 0.115 0.0121 0.155 0.874 -0.913 -0.025 0.599 0.0882 0.372
## 2 AMZN -0.0369 0.0268 0.373 1.78 2.00 2.07 0.948 0.0001 -0.143
## 3 TSLA 0.0307 0.0527 0.852 2.12 0.834 0.848 0.846 0.004 0.0667
## # … 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 LULU 3.73
## 2 AMZN 1.80
## 3 TSLA 2.90