# 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.0062317473 -0.0029353524  0.0366062134  0.052133312  4.992316e-02
## 2013-02-28  0.0058916385 -0.0231054542 -0.0129692033  0.016175454  1.267785e-02
## 2013-03-28  0.0009848859 -0.0102350107  0.0129692033  0.040257887  3.726803e-02
## 2013-04-30  0.0096391558  0.0120847911  0.0489678089  0.001222769  1.903030e-02
## 2013-05-31 -0.0202137293 -0.0494834959 -0.0306554188  0.041976082  2.333492e-02
## 2013-06-28 -0.0157782471 -0.0547283917 -0.0271446506 -0.001402946 -1.343400e-02
## 2013-07-31  0.0026873382  0.0131598859  0.0518602606  0.063541446  5.038576e-02
## 2013-08-30 -0.0082976224 -0.0257057373 -0.0197462012 -0.034743465 -3.045137e-02
## 2013-09-30  0.0111438879  0.0695889042  0.0753383340  0.063873562  3.115600e-02
## 2013-10-31  0.0082920299  0.0408609559  0.0320817209  0.034234198  4.526658e-02
## 2013-11-29 -0.0025099412 -0.0025938005  0.0054497809  0.041661010  2.920724e-02
## 2013-12-31 -0.0055836580 -0.0040741329  0.0215282869  0.012892127  2.559577e-02
## 2014-01-31  0.0152918095 -0.0903231017 -0.0534136985 -0.035774993 -3.588434e-02
## 2014-02-28  0.0037572005  0.0332207306  0.0595052487  0.045257083  4.451050e-02
## 2014-03-31 -0.0014815515  0.0380218224 -0.0046025662  0.013315355  8.261118e-03
## 2014-04-30  0.0081823532  0.0077729741  0.0165293692 -0.023184279  6.927372e-03
## 2014-05-30  0.0117225538  0.0290910723  0.0158284238  0.006205384  2.294157e-02
## 2014-06-30 -0.0005760564  0.0237337214  0.0091654077  0.037718489  2.043440e-02
## 2014-07-31 -0.0025121115  0.0135558994 -0.0263799323 -0.052009295 -1.352864e-02
## 2014-08-29  0.0114310424  0.0279043617  0.0018005750  0.043658050  3.870474e-02
## 2014-09-30 -0.0061677837 -0.0808568050 -0.0395984905 -0.061260702 -1.389256e-02
## 2014-10-31  0.0105846503  0.0140965675 -0.0026548111  0.068874984  2.327833e-02
## 2014-11-28  0.0065491489 -0.0155410693  0.0006251511  0.004773717  2.710095e-02
## 2014-12-31  0.0014748271 -0.0404422216 -0.0407467341  0.025295528 -2.539486e-03
## 2015-01-30  0.0203147467 -0.0068958558  0.0062266698 -0.054627746 -3.007725e-02
## 2015-02-27 -0.0089876631  0.0431361387  0.0614506896  0.056914639  5.468172e-02
## 2015-03-31  0.0037404215 -0.0150861354 -0.0143889389  0.010156462 -1.583011e-02
## 2015-04-30 -0.0032333810  0.0662810801  0.0358167334 -0.018417742  9.785952e-03
## 2015-05-29 -0.0043835601 -0.0419110247  0.0019526477  0.007509874  1.277439e-02
## 2015-06-30 -0.0108252720 -0.0297465004 -0.0316788228  0.004171446 -2.052170e-02
## 2015-07-31  0.0085848366 -0.0651781336  0.0201143281 -0.027375517  2.233823e-02
## 2015-08-31 -0.0033639067 -0.0925122731 -0.0771525747 -0.047268587 -6.288659e-02
## 2015-09-30  0.0080812883 -0.0318249917 -0.0451947318 -0.038464390 -2.584741e-02
## 2015-10-30  0.0006858257  0.0618083039  0.0640261348  0.063589632  8.163496e-02
## 2015-11-30 -0.0038988689 -0.0255603347 -0.0075560418  0.024415186  3.648534e-03
## 2015-12-31 -0.0019189833 -0.0389473124 -0.0235949460 -0.052156750 -1.743365e-02
## 2016-01-29  0.0123300071 -0.0516365338 -0.0567578149 -0.060307108 -5.106848e-02
## 2016-02-29  0.0088320138 -0.0082114542 -0.0339138983  0.020605459 -8.265770e-04
## 2016-03-31  0.0087083502  0.1218788343  0.0637455110  0.089910239  6.510016e-02
## 2016-04-29  0.0025463726  0.0040792162  0.0219751842  0.021044158  3.933651e-03
## 2016-05-31  0.0001360014 -0.0376285104 -0.0008560460  0.004397041  1.686863e-02
## 2016-06-30  0.0191664118  0.0445824046 -0.0244914502  0.008292327  3.469549e-03
## 2016-07-29  0.0054296126  0.0524420934  0.0390001108  0.049348308  3.582223e-02
## 2016-08-31 -0.0021564307  0.0087987250  0.0053269451  0.011260901  1.196574e-03
## 2016-09-30  0.0005159728  0.0248726900  0.0132791575  0.008615016  5.813593e-05
## 2016-10-31 -0.0082054001 -0.0083121305 -0.0224038311 -0.038134785 -1.748913e-02
## 2016-11-30 -0.0259894493 -0.0451619631 -0.0179743989  0.125246222  3.617614e-02
## 2016-12-30  0.0025381570 -0.0025298824  0.0267028606  0.031491864  2.006917e-02
## 2017-01-31  0.0021259881  0.0644314594  0.0323818767 -0.012144032  1.773638e-02
## 2017-02-28  0.0064376758  0.0172579571  0.0118365499  0.013428687  3.853934e-02
## 2017-03-31 -0.0005527023  0.0361889820  0.0318054031 -0.006532896  1.248940e-03
## 2017-04-28  0.0090293395  0.0168663974  0.0239525177  0.005107774  9.877237e-03
## 2017-05-31  0.0068472669  0.0280599834  0.0348101105 -0.022862752  1.401452e-02
## 2017-06-30 -0.0001820194  0.0092236560  0.0029559982  0.029151876  6.354475e-03
## 2017-07-31  0.0033341305  0.0565943378  0.0261877962  0.007481738  2.034579e-02
## 2017-08-31  0.0093691611  0.0232440751 -0.0004482935 -0.027564793  2.913656e-03
## 2017-09-29 -0.0057320851 -0.0004463953  0.0233427751  0.082321661  1.994901e-02
## 2017-10-31  0.0009777544  0.0322785714  0.0166535960  0.005916202  2.329061e-02
## 2017-11-30 -0.0014838909 -0.0038971458  0.0068702391  0.036913172  3.010807e-02
## 2017-12-29  0.0047399508  0.0369254932  0.0133982026 -0.003731136  1.205525e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398348e-05 0.0001042082 4.178171e-05 -7.811753e-05 -9.030540e-06
## EEM  1.042082e-04 0.0017547109 1.039018e-03  6.437736e-04  6.795427e-04
## EFA  4.178171e-05 0.0010390178 1.064238e-03  6.490301e-04  6.975421e-04
## IJS -7.811753e-05 0.0006437736 6.490301e-04  1.565447e-03  8.290245e-04
## SPY -9.030540e-06 0.0006795427 6.975421e-04  8.290245e-04  7.408293e-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.02347491
# 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.0003874105 0.009257143 0.005815637 0.005684468 0.002330251
rowSums(component_contribution)
## [1] 0.02347491
# 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."))