# Load Packages
library(tidyverse)
library(tidyquant)
1 Get stock prices and convert to returns
Ra <- c("COST", "ELF", "GOOG") %>%
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: 87 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 COST 2022-01-31 -0.109
## 2 COST 2022-02-28 0.0295
## 3 COST 2022-03-31 0.109
## 4 COST 2022-04-29 -0.0751
## 5 COST 2022-05-31 -0.123
## 6 COST 2022-06-30 0.0280
## 7 COST 2022-07-29 0.131
## 8 COST 2022-08-31 -0.0355
## 9 COST 2022-09-30 -0.0954
## 10 COST 2022-10-31 0.0638
## # ℹ 77 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: 87 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 COST 2022-01-31 -0.109 -0.101
## 2 COST 2022-02-28 0.0295 -0.0343
## 3 COST 2022-03-31 0.109 0.0341
## 4 COST 2022-04-29 -0.0751 -0.133
## 5 COST 2022-05-31 -0.123 -0.0205
## 6 COST 2022-06-30 0.0280 -0.0871
## 7 COST 2022-07-29 0.131 0.123
## 8 COST 2022-08-31 -0.0355 -0.0464
## 9 COST 2022-09-30 -0.0954 -0.105
## 10 COST 2022-10-31 0.0638 0.0390
## # ℹ 77 more rows
4 Calcualte CAPM
Which of your stock beat the market in 2022?
All of my stocks have a positive Alpha, therefore all of them beat
the Market.
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 COST 0.150 0.0126 0.162 0.894 0.507 0.774 0.791
## 2 ELF 1.04 0.0671 1.18 1.02 1.19 0.723 0.495
## 3 GOOG 0.0562 0.0059 0.0726 0.915 1.13 0.432 0.766
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a positively skewed distribution of returns?
None of my stocks are positively skewed.
RaRb_capm <- RaRb %>%
tq_performance(Ra = Ra,
Rb = NULL,
performance_fun = skewness)
RaRb_capm
## # A tibble: 3 × 2
## # Groups: symbol [3]
## symbol skewness.1
## <chr> <dbl>
## 1 COST -0.408
## 2 ELF -0.215
## 3 GOOG -0.295