# 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 = "stock.prices",
                 from = "2012-12-31",
                 to   = "2017-12-31")

2 Convert prices to returns

asset_returns_tbl <- prices %>%
# I added asset_returns_tbl here (wasn't in video) otherwise the code would not run, and mistake code wouldn't be fixable
# In video
    
    group_by(symbol) %>%

    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly",
                 type       = "log") %>%
    slice(-1) %>%
    #Remove the first row, but since data is group, it will remove the first line of each group
    
    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)

4 Calculate CAPM Beta by asset

asset_beta_tbl <- asset_returns_tbl %>%
    
    nest(data = -asset) %>%
    
    # Calculate 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)")

# Column "estimate" = beta

asset_beta_tbl %>%
    
    ggplot(aes(x = estimate, 
               y = fct_reorder(asset, estimate),
               fill = asset)) +
# Fill when column chart etc (2D), color if 1D (line)
    
    geom_col() +
    
    scale_fill_tq() +
    theme_tq() +
    theme(legend.position = "none") +
    
    labs(y = NULL, x = "Beta Coefficient",
         title = "The Best Coefficient by Asset")