# 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.0062300938 -0.0029357305  0.0366065026  0.052133168  4.992341e-02
## 2013-02-28  0.0058907664 -0.0231051036 -0.0129694926  0.016175416  1.267768e-02
## 2013-03-28  0.0009851148 -0.0102352033  0.0129694926  0.040258177  3.726829e-02
## 2013-04-30  0.0096389753  0.0120849871  0.0489675055  0.001222177  1.903009e-02
## 2013-05-31 -0.0202142167 -0.0494837072 -0.0306553609  0.041976279  2.333517e-02
## 2013-06-28 -0.0157784232 -0.0547281714 -0.0271444130 -0.001402940 -1.343394e-02
## 2013-07-31  0.0026878205  0.0131598101  0.0518602160  0.063541538  5.038547e-02
## 2013-08-30 -0.0082981576 -0.0257053223 -0.0197462770 -0.034743504 -3.045119e-02
## 2013-09-30  0.0111441764  0.0695883669  0.0753381639  0.063873479  3.115624e-02
## 2013-10-31  0.0082918343  0.0408614131  0.0320821275  0.034234338  4.526615e-02
## 2013-11-29 -0.0025096125 -0.0025940994  0.0054496601  0.041660995  2.920715e-02
## 2013-12-31 -0.0055829992 -0.0040746633  0.0215281351  0.012892066  2.559636e-02
## 2014-01-31  0.0152914695 -0.0903223211 -0.0534133990 -0.035775106 -3.588489e-02
## 2014-02-28  0.0037570439  0.0332205818  0.0595048281  0.045257392  4.451050e-02
## 2014-03-31 -0.0014817680  0.0380219217 -0.0046024808  0.013315390  8.261430e-03
## 2014-04-30  0.0081834467  0.0077724039  0.0165293818 -0.023184463  6.927083e-03
## 2014-05-30  0.0117218149  0.0290912949  0.0158283376  0.006205346  2.294165e-02
## 2014-06-30 -0.0005759727  0.0237340283  0.0091656063  0.037718582  2.043434e-02
## 2014-07-31 -0.0025123159  0.0135555274 -0.0263799315 -0.052009190 -1.352821e-02
## 2014-08-29  0.0114302238  0.0279047730  0.0018004596  0.043657634  3.870430e-02
## 2014-09-30 -0.0061666833 -0.0808567507 -0.0395983845 -0.061260207 -1.389233e-02
## 2014-10-31  0.0105838868  0.0140966284 -0.0026549362  0.068874695  2.327780e-02
## 2014-11-28  0.0065492238 -0.0155414384  0.0006254262  0.004773850  2.710161e-02
## 2014-12-31  0.0014756395 -0.0404422001 -0.0407468067  0.025295956 -2.540010e-03
## 2015-01-30  0.0203147715 -0.0068958564  0.0062265795 -0.054628227 -3.007711e-02
## 2015-02-27 -0.0089881904  0.0431363665  0.0614504309  0.056914578  5.468219e-02
## 2015-03-31  0.0037401399 -0.0150866789 -0.0143887661  0.010156378 -1.583061e-02
## 2015-04-30 -0.0032328098  0.0662815737  0.0358166812 -0.018417663  9.786119e-03
## 2015-05-29 -0.0043830966 -0.0419108429  0.0019524810  0.007509783  1.277427e-02
## 2015-06-30 -0.0108265359 -0.0297465286 -0.0316786651  0.004171332 -2.052160e-02
## 2015-07-31  0.0085849196 -0.0651780945  0.0201144464 -0.027375236  2.233794e-02
## 2015-08-31 -0.0033636240 -0.0925125948 -0.0771524492 -0.047268658 -6.288683e-02
## 2015-09-30  0.0080815271 -0.0318249808 -0.0451948062 -0.038464409 -2.584698e-02
## 2015-10-30  0.0006847906  0.0618083630  0.0640260411  0.063589409  8.163497e-02
## 2015-11-30 -0.0038979013 -0.0255607491 -0.0075559812  0.024415600  3.648829e-03
## 2015-12-31 -0.0019191180 -0.0389467614 -0.0235950118 -0.052157047 -1.743380e-02
## 2016-01-29  0.0123301239 -0.0516367829 -0.0567577196 -0.060306953 -5.106871e-02
## 2016-02-29  0.0088317637 -0.0082116787 -0.0339142075  0.020605296 -8.263143e-04
## 2016-03-31  0.0087085611  0.1218788741  0.0637458877  0.089910381  6.510037e-02
## 2016-04-29  0.0025466986  0.0040794280  0.0219751583  0.021043992  3.933277e-03
## 2016-05-31  0.0001352027 -0.0376284773 -0.0008561257  0.004397330  1.686864e-02
## 2016-06-30  0.0191670107  0.0445823224 -0.0244915778  0.008292145  3.469836e-03
## 2016-07-29  0.0054294369  0.0524422824  0.0390003137  0.049348334  3.582186e-02
## 2016-08-31 -0.0021559617  0.0087984748  0.0053267378  0.011261095  1.197108e-03
## 2016-09-30  0.0005157743  0.0248727366  0.0132791928  0.008614788  5.777177e-05
## 2016-10-31 -0.0082052777 -0.0083121569 -0.0224036999 -0.038134766 -1.748885e-02
## 2016-11-30 -0.0259899633 -0.0451614702 -0.0179744772  0.125246283  3.617582e-02
## 2016-12-30  0.0025386270 -0.0025302619  0.0267028530  0.031491978  2.006906e-02
## 2017-01-31  0.0021255438  0.0644314499  0.0323820281 -0.012144091  1.773645e-02
## 2017-02-28  0.0064382660  0.0172577163  0.0118360937  0.013428555  3.853929e-02
## 2017-03-31 -0.0005529883  0.0361892145  0.0318059692 -0.006532714  1.249283e-03
## 2017-04-28  0.0090292034  0.0168664716  0.0239519855  0.005107854  9.876858e-03
## 2017-05-31  0.0068476097  0.0280595699  0.0348104161 -0.022862952  1.401465e-02
## 2017-06-30 -0.0001827862  0.0092240167  0.0029560667  0.029152074  6.354532e-03
## 2017-07-31  0.0033344261  0.0565944492  0.0261876760  0.007481497  2.034579e-02
## 2017-08-31  0.0093690180  0.0232438893 -0.0004482988 -0.027564642  2.913254e-03
## 2017-09-29 -0.0057320002 -0.0004463023  0.0233427714  0.082321854  1.994948e-02
## 2017-10-31  0.0009777005  0.0322785458  0.0166538169  0.005915716  2.329055e-02
## 2017-11-30 -0.0014842186 -0.0038968214  0.0068699108  0.036913382  3.010824e-02
## 2017-12-29  0.0047404432  0.0369251433  0.0133983765 -0.003731305  1.205465e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398391e-05 0.0001042068 0.0000417824 -7.812113e-05 -9.031791e-06
## EEM  1.042068e-04 0.0017547097 0.0010390170  6.437721e-04  6.795442e-04
## EFA  4.178240e-05 0.0010390170 0.0010642370  6.490282e-04  6.975422e-04
## IJS -7.812113e-05 0.0006437721 0.0006490282  1.565448e-03  8.290243e-04
## SPY -9.031791e-06 0.0006795442 0.0006975422  8.290243e-04  7.408304e-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.02347489
# 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.0003874006 0.00925714 0.005815636 0.005684461 0.002330253
rowSums(component_contribution)
## [1] 0.02347489
# 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.097
##  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."))