# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Collect individual returns into a portfolio by assigning a weight to each stock

five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”

from 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c ("SPY", "EFA", "IJS", "EEM", "AGG")

prices <- tq_get(x = symbols,
                 get = "stockprices",
                 from = "2012-12-31",
                 to = "2017-12-31")

2 Convert prices to returns

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"))

3 Get Market Returns

market_returns_tbl <- tq_get(x = "SPY",
                 get = "stockprices",
                 from = "2012-12-31",
                 to = "2017-12-31") %>%

  tq_transmute(select = adjusted, 
               mutate_fun = periodReturn, 
               period = "monthly", 
               type = "log") %>%
  
  slice(-1)

4 Calculate Sharpe Ratio

asset_beta_tbl <- asset_returns_tbl %>%
  
  nest(data = -asset) %>%
  
  # Cal CAPM Beta
  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) %>%
  filter(term != "(Intercepti)")

asset_beta_tbl %>%
  
  ggplot(aes(x = estimate, 
             y = 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")