# Load packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("AAPL", "VRTX", "NFLX") %>%
tq_get(get = "stock.prices",
from = "2023-01-01") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Ra")
Ra
## # A tibble: 51 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 AAPL 2023-01-31 0.154
## 2 AAPL 2023-02-28 0.0232
## 3 AAPL 2023-03-31 0.119
## 4 AAPL 2023-04-28 0.0290
## 5 AAPL 2023-05-31 0.0461
## 6 AAPL 2023-06-30 0.0943
## 7 AAPL 2023-07-31 0.0128
## 8 AAPL 2023-08-31 -0.0424
## 9 AAPL 2023-09-29 -0.0887
## 10 AAPL 2023-10-31 -0.00257
## # ℹ 41 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: 29 × 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
## # ℹ 19 more rows
3 Join the two tables
RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 51 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 AAPL 2023-01-31 0.154 0.107
## 2 AAPL 2023-02-28 0.0232 -0.0111
## 3 AAPL 2023-03-31 0.119 0.0669
## 4 AAPL 2023-04-28 0.0290 0.000382
## 5 AAPL 2023-05-31 0.0461 0.0580
## 6 AAPL 2023-06-30 0.0943 0.0659
## 7 AAPL 2023-07-31 0.0128 0.0405
## 8 AAPL 2023-08-31 -0.0424 -0.0217
## 9 AAPL 2023-09-29 -0.0887 -0.0581
## 10 AAPL 2023-10-31 -0.00257 -0.0278
## # ℹ 41 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 AAPL -0.0526 -0.005 -0.0585 1.09 1.71 1.61 0.798
## 2 VRTX -0.0117 0.0108 0.138 0.663 -0.988 0.295 0.442
## 3 NFLX 0.337 0.0049 0.0607 1.59 1.99 1.54 0.769
## # ℹ 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_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 AAPL -0.0526 -0.005 -0.0585 1.09 1.71 1.61 0.798
## 2 VRTX -0.0117 0.0108 0.138 0.663 -0.988 0.295 0.442
## 3 NFLX 0.337 0.0049 0.0607 1.59 1.99 1.54 0.769
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>