# Load packages
# Core
library(tidyverse)
library(tidyquant)
Measure the beta coefficient by asset.
five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”
from 2012-12-31 to 2017-12-31
symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
asset_returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))
market_returns_tbl <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1)
asset_beta_tbl <- asset_returns_tbl %>%
nest(data = -asset) %>%
# Build CAPM
mutate(model = map(.x = data, .f = ~lm(returns ~ market_returns_tbl$monthly.returns, data = .x))) %>%
# Extract beta
mutate(model = map(.x = model, .f = broom::tidy)) %>%
unnest(model) %>%
select(asset, term, estimate, p.value) %>%
filter(term != "(Intercept)")
asset_beta_tbl %>%
ggplot(aes(estimate,
fct_reorder(asset, estimate),
fill = asset)) +
geom_col() +
scale_fill_tq() +
theme_tq() +
theme(legend.position = "none") +
labs(y = NULL, x = "Beta Coefficient",
title = "The Best Coefficient by Asset")