# 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

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

prices <- tq_get(x    = symbols, 
                get  = "stock.prices",
                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  = "stock.prices",
                from = "2012-12-31", 
                to   = "2017-12-31") %>%
    
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly",
                 type       = "log") %>%
    
    slice(-1)
    
market_returns_tbl
## # A tibble: 60 × 2
##    date       monthly.returns
##    <date>               <dbl>
##  1 2013-01-31          0.0499
##  2 2013-02-28          0.0127
##  3 2013-03-28          0.0373
##  4 2013-04-30          0.0190
##  5 2013-05-31          0.0233
##  6 2013-06-28         -0.0134
##  7 2013-07-31          0.0504
##  8 2013-08-30         -0.0305
##  9 2013-09-30          0.0312
## 10 2013-10-31          0.0453
## # … with 50 more rows

4 Calculate CAPM Beta by asset

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 != "(Intercept)")

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 Beta Coefficient by Asset")