# Load packages

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

# Time series
library(lubridate)
library(tibbletime)

# 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

Refresh your memory on covariance with this video. Click this link Refresh your memory on matrix multiplication. Click this link

# Transform data into wide form
asset_returns_wide_tbl <- asset_returns_tbl %>%

    pivot_wider(names_from = asset, values_from = returns) %>%

    column_to_rownames(var = "date")

asset_returns_wide_tbl
##                      AGG           EEM           EFA          IJS           SPY
## 2013-01-31 -0.0062309050 -0.0029352585  0.0366064135  0.052133107  4.992283e-02
## 2013-02-28  0.0058916389 -0.0231055723 -0.0129693806  0.016175669  1.267792e-02
## 2013-03-28  0.0009846233 -0.0102351142  0.0129693806  0.040257987  3.726825e-02
## 2013-04-30  0.0096401513  0.0120847780  0.0489676260  0.001222744  1.902993e-02
## 2013-05-31 -0.0202143618 -0.0494835903 -0.0306556875  0.041976287  2.333549e-02
## 2013-06-28 -0.0157787181 -0.0547281647 -0.0271442523 -0.001403198 -1.343467e-02
## 2013-07-31  0.0026878024  0.0131598622  0.0518603956  0.063541619  5.038606e-02
## 2013-08-30 -0.0082986738 -0.0257057056 -0.0197465144 -0.034743667 -3.045076e-02
## 2013-09-30  0.0111444323  0.0695887157  0.0753387023  0.063873628  3.115546e-02
## 2013-10-31  0.0082923872  0.0408614187  0.0320817394  0.034234344  4.526609e-02
## 2013-11-29 -0.0025104984 -0.0025941931  0.0054495994  0.041660822  2.920816e-02
## 2013-12-31 -0.0055823556 -0.0040740045  0.0215278476  0.012892133  2.559574e-02
## 2014-01-31  0.0152913917 -0.0903230931 -0.0534131927 -0.035775487 -3.588486e-02
## 2014-02-28  0.0037567458  0.0332207412  0.0595048489  0.045258096  4.451116e-02
## 2014-03-31 -0.0014819419  0.0380214613 -0.0046022549  0.013314985  8.260698e-03
## 2014-04-30  0.0081836469  0.0077726757  0.0165291855 -0.023184271  6.927654e-03
## 2014-05-30  0.0117217418  0.0290914332  0.0158286006  0.006205040  2.294087e-02
## 2014-06-30 -0.0005760295  0.0237339449  0.0091652625  0.037719056  2.043464e-02
## 2014-07-31 -0.0025118708  0.0135556888 -0.0263798940 -0.052009743 -1.352860e-02
## 2014-08-29  0.0114304332  0.0279044995  0.0018004770  0.043658191  3.870496e-02
## 2014-09-30 -0.0061672594 -0.0808565541 -0.0395982195 -0.061260558 -1.389246e-02
## 2014-10-31  0.0105839906  0.0140964557 -0.0026547696  0.068874805  2.327798e-02
## 2014-11-28  0.0065494564 -0.0155413256  0.0006251657  0.004773809  2.710131e-02
## 2014-12-31  0.0014749717 -0.0404421179 -0.0407468145  0.025295829 -2.540003e-03
## 2015-01-30  0.0203152655 -0.0068958811  0.0062263668 -0.054628200 -3.007673e-02
## 2015-02-27 -0.0089883924  0.0431362088  0.0614508370  0.056914690  5.468151e-02
## 2015-03-31  0.0037405333 -0.0150861232 -0.0143888736  0.010156390 -1.583006e-02
## 2015-04-30 -0.0032334177  0.0662812921  0.0358166599 -0.018417572  9.785785e-03
## 2015-05-29 -0.0043834442 -0.0419111554  0.0019527114  0.007509784  1.277399e-02
## 2015-06-30 -0.0108254163 -0.0297464684 -0.0316789202  0.004171360 -2.052089e-02
## 2015-07-31  0.0085850533 -0.0651782708  0.0201144168 -0.027375504  2.233776e-02
## 2015-08-31 -0.0033639680 -0.0925121278 -0.0771523411 -0.047268359 -6.288672e-02
## 2015-09-30  0.0080811610 -0.0318252450 -0.0451950235 -0.038464931 -2.584697e-02
## 2015-10-30  0.0006853614  0.0618084243  0.0640261675  0.063590106  8.163472e-02
## 2015-11-30 -0.0038980756 -0.0255604049 -0.0075558110  0.024414959  3.648768e-03
## 2015-12-31 -0.0019190851 -0.0389470640 -0.0235952201 -0.052156689 -1.743350e-02
## 2016-01-29  0.0123302035 -0.0516366963 -0.0567577006 -0.060306980 -5.106877e-02
## 2016-02-29  0.0088311349 -0.0082116146 -0.0339139220  0.020605386 -8.263362e-04
## 2016-03-31  0.0087097651  0.1218791652  0.0637457506  0.089910057  6.510025e-02
## 2016-04-29  0.0025457589  0.0040789675  0.0219750143  0.021044323  3.933256e-03
## 2016-05-31  0.0001354204 -0.0376283957 -0.0008559984  0.004397028  1.686851e-02
## 2016-06-30  0.0191665388  0.0445822210 -0.0244916117  0.008292550  3.469846e-03
## 2016-07-29  0.0054299440  0.0524422375  0.0390002385  0.049348276  3.582200e-02
## 2016-08-31 -0.0021560036  0.0087984716  0.0053266748  0.011260917  1.196974e-03
## 2016-09-30  0.0005156931  0.0248731704  0.0132794159  0.008614877  5.778028e-05
## 2016-10-31 -0.0082055419 -0.0083123261 -0.0224038336 -0.038134810 -1.748906e-02
## 2016-11-30 -0.0259894459 -0.0451616897 -0.0179744875  0.125246255  3.617608e-02
## 2016-12-30  0.0025384174 -0.0025299829  0.0267029875  0.031491867  2.006906e-02
## 2017-01-31  0.0021262162  0.0644314710  0.0323818267 -0.012144020  1.773641e-02
## 2017-02-28  0.0064370642  0.0172575302  0.0118363502  0.013429085  3.853941e-02
## 2017-03-31 -0.0005522345  0.0361892719  0.0318056735 -0.006533498  1.249270e-03
## 2017-04-28  0.0090294318  0.0168661758  0.0239524080  0.005108330  9.877007e-03
## 2017-05-31  0.0068470028  0.0280600145  0.0348100674 -0.022863051  1.401428e-02
## 2017-06-30 -0.0001822131  0.0092236606  0.0029561481  0.029151581  6.354939e-03
## 2017-07-31  0.0033341403  0.0565945349  0.0261877320  0.007481962  2.034551e-02
## 2017-08-31  0.0093690679  0.0232439210 -0.0004482871 -0.027564707  2.913569e-03
## 2017-09-29 -0.0057321766 -0.0004462596  0.0233428816  0.082321780  1.994921e-02
## 2017-10-31  0.0009780019  0.0322785967  0.0166535112  0.005915865  2.329061e-02
## 2017-11-30 -0.0014843218 -0.0038970180  0.0068699622  0.036913148  3.010821e-02
## 2017-12-29  0.0047404246  0.0369253201  0.0133982764 -0.003731416  1.205488e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398479e-05 0.0001042117 4.178628e-05 -7.811829e-05 -9.029894e-06
## EEM  1.042117e-04 0.0017547126 1.039018e-03  6.437760e-04  6.795426e-04
## EFA  4.178628e-05 0.0010390184 1.064238e-03  6.490325e-04  6.975402e-04
## IJS -7.811829e-05 0.0006437760 6.490325e-04  1.565453e-03  8.290270e-04
## SPY -9.029894e-06 0.0006795426 6.975402e-04  8.290270e-04  7.408278e-04
# Standard deviation of portfolio
# Summarizes how much each asset's returns vary with those of other assets within the portfolio into a single number
w <- c(0.25, 0.25, 0.2, 0.2, 0.1)

sd_portfolio <- sqrt(t(w) %*% covariance_matrix %*% w)
sd_portfolio
##            [,1]
## [1,] 0.02347495
# Component contribution
# Similar to the formula for sd_portfolio
# Mathematical trick to summarize the same, sd_portfolio, by asset instead of a single number
component_contribution <- (t(w) %*% covariance_matrix * w) / sd_portfolio[1,1]
component_contribution
##               AGG         EEM         EFA         IJS         SPY
## [1,] 0.0003874314 0.009257148 0.005815641 0.005684479 0.002330248
rowSums(component_contribution)
## [1] 0.02347495
# Component contribution in percentage
component_percentages <- (component_contribution / sd_portfolio[1,1]) %>%
    round(3) %>%
    as_tibble()

component_percentages
## # 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
component_percentages %>%

    as_tibble() %>%
    gather(key = "asset", value = "contribution")
## # 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

# Transform data into wide form
asset_returns_wide_tbl <- asset_returns_tbl %>%

    pivot_wider(names_from = asset, values_from = returns) %>%

    column_to_rownames(var = "date")

# Custom function
calculate_component_contribution <- function(asset_returns_wide_tbl, w) {

    # Covariance of asset returns
    covariance_matrix <- cov(asset_returns_wide_tbl)
    
    # Standard deviation of portfolio
    sd_portfolio <- sqrt(t(w) %*% covariance_matrix %*% w)

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

    # Component contribution in percentage
    component_percentages <- (component_contribution / sd_portfolio[1,1]) %>%
        round(3) %>%
        as_tibble()
    
    return(component_percentages)

}

asset_returns_wide_tbl %>% calculate_component_contribution(w = c(0.25,0.25,0.2,0.2,0.1))
## # 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

# Figure 10.1 Contribution to Standard Deviation ----
asset_returns_wide_tbl %>%

    calculate_component_contribution(w = c(0.25,0.25,0.2,0.2,0.1)) %>%
    gather(key = "asset", value = "contribution") %>%

    ggplot(aes(asset, contribution)) +
    geom_col(fill = "cornflowerblue") +
    
    theme(plot.title = element_text(hjust = 0.5)) +
    scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
    
    labs(title = "Percent Contribution to Portfolio Standard Deviation",
         y = "Percent Contribution to Risk",
         x = NULL)

# Figure 10.2 Weight versus Contribution ----
asset_returns_wide_tbl %>%

    calculate_component_contribution(w = c(0.25,0.25,0.2,0.2,0.1)) %>%
    gather(key = "asset", value = "contribution") %>%
    add_column(weights = c(0.25,0.25,0.2,0.2,0.1)) %>%
    pivot_longer(cols = c(contribution, weights), names_to = "type", values_to = "value") %>%

    ggplot(aes(asset, value, fill = type)) +
    geom_col(position = "dodge") +
    
    theme(plot.title = element_text(hjust = 0.5)) +
    scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
    theme_tq() +
    scale_fill_tq() +

    labs(title = "Percent Contribution to Volatility",
         y = "percent",
         x = "asset") 

6 Rolling Component Contribution

calculate_comp_contrib_by_window <- function(asset_returns_wide_tbl,
                                             start = 1,
                                             window = 24,
                                             weights) {

    # 1 Define start date
    start_date <- rownames(asset_returns_wide_tbl)[start]

    # 2 Define end date
    end_date <- rownames(asset_returns_wide_tbl)[start + window]

    # 3 Subset df
    df_subset <- asset_returns_wide_tbl %>%

        rownames_to_column(var = "date") %>%

        filter(date >= start_date & date < end_date) %>%

        column_to_rownames(var = "date")

    # 4 Calculate component contribution
    component_percentages <-df_subset %>%
        calculate_component_contribution(w = weights)

    # 5 Add end date to df
    component_percentages %>%

        mutate(date = ymd(end_date)) %>%
        select(date, everything())

}


# Check the custom function
asset_returns_wide_tbl %>% calculate_comp_contrib_by_window(start = 1, window = 24,
                                                            w = c(0.25,0.25,0.2,0.2,0.1))
## # A tibble: 1 × 6
##   date         AGG   EEM   EFA   IJS   SPY
##   <date>     <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2015-01-30 0.039 0.372 0.256 0.245 0.088
asset_returns_wide_tbl %>% calculate_comp_contrib_by_window(start = 2, window = 24,
                                                            w = c(0.25,0.25,0.2,0.2,0.1))
## # A tibble: 1 × 6
##   date         AGG   EEM   EFA   IJS   SPY
##   <date>     <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2015-02-27 0.036 0.374 0.249 0.252 0.089
dump(list = c("calculate_component_contribution",
              "calculate_comp_contrib_by_window"),
     file = "../00_scripts/calculate_comp_contrib_to_portfolio_volatility.R")
# Iterate the custom function
w <- c(0.25,0.25,0.2,0.2,0.1)
window <- 24

rolling_comp_contrib_tbl <- 1:(nrow(asset_returns_wide_tbl) - window) %>%

    map_df(.x = ., .f = ~calculate_comp_contrib_by_window(asset_returns_wide_tbl,
                                                          start = .x,
                                                          weights = w,
                                                          window = window))
rolling_comp_contrib_tbl
## # A tibble: 36 × 6
##    date         AGG   EEM   EFA   IJS   SPY
##    <date>     <dbl> <dbl> <dbl> <dbl> <dbl>
##  1 2015-01-30 0.039 0.372 0.256 0.245 0.088
##  2 2015-02-27 0.036 0.374 0.249 0.252 0.089
##  3 2015-03-31 0.027 0.37  0.255 0.255 0.092
##  4 2015-04-30 0.027 0.372 0.256 0.252 0.093
##  5 2015-05-29 0.024 0.385 0.254 0.246 0.092
##  6 2015-06-30 0.018 0.383 0.248 0.257 0.094
##  7 2015-07-31 0.014 0.375 0.253 0.261 0.096
##  8 2015-08-31 0.013 0.404 0.237 0.257 0.09 
##  9 2015-09-30 0.012 0.407 0.248 0.238 0.094
## 10 2015-10-30 0.003 0.405 0.244 0.243 0.105
## # ℹ 26 more rows
# Figure 10.3 Component Contribution ggplot ----
rolling_comp_contrib_tbl %>%

    # Transform data to long form
    pivot_longer(cols = -date, names_to = "asset", values_to = "contribution") %>%

    # Plot
    ggplot(aes(date, contribution, color = asset)) +
    geom_line() +

    scale_x_date(breaks = scales::pretty_breaks(n = 7)) +
    scale_y_continuous(labels = scales::percent_format()) +

    annotate(geom = "text",
             x = as.Date("2016-07-01"),
             y = 0.03,
             color = "red", size = 5,
             label = str_glue("AGG dips below zero sometimes, indicating
                              it reduces the portfolio volatility."))

# Figure 10.4 Stacked Component Contribution ggplot ----
rolling_comp_contrib_tbl %>%

    # Transform data to long form
    pivot_longer(cols = -date, names_to = "asset", values_to = "contribution") %>%

    # Plot
    ggplot(aes(date, contribution, fill = asset)) +
    geom_area() +

    scale_x_date(breaks = scales::pretty_breaks(n = 7)) +
    scale_y_continuous(labels = scales::percent_format()) +

    annotate(geom = "text",
             x = as.Date("2016-07-01"),
             y = 0.08,
             color = "red", size = 5,
             label = str_glue("AGG dips below zero sometimes, indicating
                              it reduces the portfolio volatility."))