# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(readr)

# Time series
library(lubridate)


# modeling
library(broom)

Goal

Examine how each asset contributes to portfolio standard deviation. This is to ensure that our risk is not concentrated in any one asset.

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 %>%
    group_by(symbol) %>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly",
                 type       = "log") %>%
    slice(-1) %>%
    ungroup() %>%
    set_names(c("asset", "date", "returns"))

3 Component Contribution Step-by-Step

asset_returns_wide_tbl <- asset_returns_tbl %>%
    pivot_wider(names_from = asset, values_from = returns) %>%
    column_to_rownames(var = "date")

covariance_matrix <- cov(asset_returns_wide_tbl)

w <- c(0.25, 0.25, 0.2, 0.2, 0.1)

sd_portfolio <- sqrt(t(w) %*% covariance_matrix %*% w)

component_contribution <- (t(w) %*% covariance_matrix * w) / sd_portfolio[1,1]

component_percentages <- (component_contribution / sd_portfolio[1,1]) %>%
    round(3) %>%
    as_tibble()

component_percentages_long <- component_percentages %>%
    gather(key = "asset", value = "contribution")

component_percentages_long
## # A tibble: 5 × 2
##   asset contribution
##   <chr>        <dbl>
## 1 AGG          0.017
## 2 EEM          0.394
## 3 EFA          0.248
## 4 IJS          0.242
## 5 SPY          0.099

4 Component Contribution with a Custom Function

calculate_component_contribution <- function(data, weights) {
  cov_matrix <- cov(data)
  sd_portfolio <- sqrt(t(weights) %*% cov_matrix %*% weights)
  component_contribution <- (t(weights) %*% cov_matrix * weights) / sd_portfolio[1, 1]
  component_percentages <- (component_contribution / sd_portfolio[1, 1]) %>%
    round(3) %>%
    as_tibble()
  return(component_percentages)
}

component_tbl <- calculate_component_contribution(asset_returns_wide_tbl, w)
component_tbl
## # A tibble: 1 × 5
##     AGG   EEM   EFA   IJS   SPY
##   <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 0.017 0.394 0.248 0.242 0.099

5 Visualizing Component Contribution and Weight

plot_data <- component_tbl %>%
  pivot_longer(cols = everything(),
               names_to = "asset",
               values_to = "contribution") %>%
  mutate(weight = w)

plot_data_long <- plot_data %>%
  pivot_longer(cols = c(contribution, weight),
               names_to = "type",
               values_to = "value")

plot_data_long %>%
  ggplot(aes(x = asset, y = value, fill = type)) +
  geom_col(position = "dodge") +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  labs(title = "Contribution to Portfolio Volatility vs. Portfolio Weights",
       y = "Percent", x = NULL, fill = NULL) +
  theme_tq() +
  scale_fill_tq() +
  theme(plot.title = element_text(hjust = 0.5))

6 Rolling Component Contribution