# load packages
library(tidyverse)
library(tidyquant)
get stock prices and convert to returns
Ra <- c("AMD", "NVDA", "INTU") %>%
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: 99 × 3
## # Groups: symbol [3]
## symbol date Ra
## <chr> <date> <dbl>
## 1 AMD 2022-01-31 -0.240
## 2 AMD 2022-02-28 0.0796
## 3 AMD 2022-03-31 -0.114
## 4 AMD 2022-04-29 -0.218
## 5 AMD 2022-05-31 0.191
## 6 AMD 2022-06-30 -0.249
## 7 AMD 2022-07-29 0.235
## 8 AMD 2022-08-31 -0.102
## 9 AMD 2022-09-30 -0.253
## 10 AMD 2022-10-31 -0.0521
## # ℹ 89 more rows
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: 33 × 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
## # ℹ 23 more rows
join the two tables
RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 99 × 4
## # Groups: symbol [3]
## symbol date Ra Rb
## <chr> <date> <dbl> <dbl>
## 1 AMD 2022-01-31 -0.240 -0.101
## 2 AMD 2022-02-28 0.0796 -0.0343
## 3 AMD 2022-03-31 -0.114 0.0341
## 4 AMD 2022-04-29 -0.218 -0.133
## 5 AMD 2022-05-31 0.191 -0.0205
## 6 AMD 2022-06-30 -0.249 -0.0871
## 7 AMD 2022-07-29 0.235 0.123
## 8 AMD 2022-08-31 -0.102 -0.0464
## 9 AMD 2022-09-30 -0.253 -0.105
## 10 AMD 2022-10-31 -0.0521 0.0390
## # ℹ 89 more rows
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 AMD -0.033 0.0028 0.0336 1.89 2.53 2.06 0.754
## 2 NVDA 0.587 0.0424 0.645 2.27 2.77 1.63 0.867
## 3 INTU -0.0324 -0.0013 -0.0156 1.02 0.892 1.28 0.773
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## # `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>
Which stock has a positively skewed distribution of returns? INTU
has a positively skewed distribution of returns
RaRb_skewness <- RaRb %>%
tq_performance(Ra = Ra,
Rb = NULL,
performance_fun = skewness)
RaRb_skewness
## # A tibble: 3 × 2
## # Groups: symbol [3]
## symbol skewness.1
## <chr> <dbl>
## 1 AMD 0.174
## 2 NVDA -0.182
## 3 INTU 0.312