# 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.0062309888 -0.0029353167  0.0366061698  0.052133582  4.992272e-02
## 2013-02-28  0.0058912518 -0.0231055150 -0.0129693901  0.016175505  1.267880e-02
## 2013-03-28  0.0009846966 -0.0102348834  0.0129693901  0.040257950  3.726776e-02
## 2013-04-30  0.0096392318  0.0120848841  0.0489677741  0.001222579  1.902962e-02
## 2013-05-31 -0.0202140245 -0.0494836345 -0.0306556320  0.041976613  2.333576e-02
## 2013-06-28 -0.0157778815 -0.0547281099 -0.0271445692 -0.001403289 -1.343466e-02
## 2013-07-31  0.0026869950  0.0131596226  0.0518602840  0.063541488  5.038593e-02
## 2013-08-30 -0.0082979604 -0.0257057495 -0.0197462111 -0.034743648 -3.045100e-02
## 2013-09-30  0.0111441858  0.0695888320  0.0753385007  0.063873713  3.115583e-02
## 2013-10-31  0.0082920122  0.0408614901  0.0320818466  0.034234070  4.526657e-02
## 2013-11-29 -0.0025098782 -0.0025938709  0.0054493211  0.041661127  2.920706e-02
## 2013-12-31 -0.0055828075 -0.0040748507  0.0215282292  0.012892372  2.559601e-02
## 2014-01-31  0.0152910845 -0.0903227048 -0.0534134224 -0.035775628 -3.588423e-02
## 2014-02-28  0.0037572819  0.0332208430  0.0595051175  0.045257428  4.450991e-02
## 2014-03-31 -0.0014818485  0.0380216248 -0.0046024868  0.013315541  8.261408e-03
## 2014-04-30  0.0081829402  0.0077729142  0.0165293619 -0.023184275  6.927557e-03
## 2014-05-30  0.0117225161  0.0290911879  0.0158285764  0.006205137  2.294118e-02
## 2014-06-30 -0.0005763326  0.0237339251  0.0091652100  0.037718806  2.043455e-02
## 2014-07-31 -0.0025119014  0.0135554632 -0.0263797279 -0.052009395 -1.352850e-02
## 2014-08-29  0.0114308477  0.0279046023  0.0018003989  0.043657823  3.870481e-02
## 2014-09-30 -0.0061675911 -0.0808565822 -0.0395984775 -0.061260465 -1.389262e-02
## 2014-10-31  0.0105847771  0.0140964530 -0.0026547927  0.068874767  2.327815e-02
## 2014-11-28  0.0065490048 -0.0155413204  0.0006252355  0.004773781  2.710130e-02
## 2014-12-31  0.0014746139 -0.0404420932 -0.0407466701  0.025295975 -2.540027e-03
## 2015-01-30  0.0203149434 -0.0068957476  0.0062264210 -0.054628293 -3.007686e-02
## 2015-02-27 -0.0089879255  0.0431362506  0.0614507429  0.056914681  5.468177e-02
## 2015-03-31  0.0037401556 -0.0150863546 -0.0143888272  0.010156550 -1.583021e-02
## 2015-04-30 -0.0032328079  0.0662813686  0.0358164986 -0.018417828  9.786066e-03
## 2015-05-29 -0.0043839202 -0.0419110105  0.0019526917  0.007509932  1.277383e-02
## 2015-06-30 -0.0108253798 -0.0297467767 -0.0316787464  0.004171261 -2.052100e-02
## 2015-07-31  0.0085850554 -0.0651780201  0.0201143002 -0.027375259  2.233789e-02
## 2015-08-31 -0.0033642783 -0.0925125610 -0.0771523012 -0.047268453 -6.288686e-02
## 2015-09-30  0.0080815023 -0.0318246508 -0.0451948664 -0.038464762 -2.584684e-02
## 2015-10-30  0.0006853394  0.0618081961  0.0640259447  0.063589675  8.163503e-02
## 2015-11-30 -0.0038984543 -0.0255603250 -0.0075559415  0.024415567  3.648425e-03
## 2015-12-31 -0.0019186686 -0.0389472195 -0.0235950350 -0.052157414 -1.743371e-02
## 2016-01-29  0.0123300638 -0.0516367575 -0.0567576593 -0.060306538 -5.106862e-02
## 2016-02-29  0.0088315122 -0.0082115386 -0.0339139774  0.020605107 -8.262749e-04
## 2016-03-31  0.0087088881  0.1218790767  0.0637455859  0.089910154  6.509992e-02
## 2016-04-29  0.0025465250  0.0040791550  0.0219751218  0.021044350  3.933700e-03
## 2016-05-31  0.0001354420 -0.0376283922 -0.0008562057  0.004397116  1.686839e-02
## 2016-06-30  0.0191664950  0.0445821604 -0.0244913251  0.008292306  3.470131e-03
## 2016-07-29  0.0054298579  0.0524422525  0.0390001135  0.049348247  3.582171e-02
## 2016-08-31 -0.0021564410  0.0087986314  0.0053269244  0.011261141  1.196801e-03
## 2016-09-30  0.0005159386  0.0248727224  0.0132791048  0.008614677  5.805468e-05
## 2016-10-31 -0.0082050216 -0.0083120145 -0.0224035594 -0.038134764 -1.748902e-02
## 2016-11-30 -0.0259899782 -0.0451617810 -0.0179747621  0.125246607  3.617588e-02
## 2016-12-30  0.0025379523 -0.0025300915  0.0267031820  0.031491486  2.006908e-02
## 2017-01-31  0.0021266209  0.0644314144  0.0323818541 -0.012143782  1.773651e-02
## 2017-02-28  0.0064375887  0.0172578913  0.0118363213  0.013428578  3.853932e-02
## 2017-03-31 -0.0005525514  0.0361891103  0.0318056750 -0.006532835  1.249205e-03
## 2017-04-28  0.0090290430  0.0168663664  0.0239523104  0.005107819  9.877394e-03
## 2017-05-31  0.0068473195  0.0280597646  0.0348100711 -0.022862671  1.401412e-02
## 2017-06-30 -0.0001824934  0.0092239409  0.0029561916  0.029151703  6.354571e-03
## 2017-07-31  0.0033343053  0.0565943781  0.0261877724  0.007481729  2.034592e-02
## 2017-08-31  0.0093689881  0.0232437060 -0.0004483141 -0.027564976  2.913399e-03
## 2017-09-29 -0.0057319725 -0.0004461787  0.0233425840  0.082321631  1.994912e-02
## 2017-10-31  0.0009781270  0.0322784865  0.0166538437  0.005916090  2.329072e-02
## 2017-11-30 -0.0014844552 -0.0038969510  0.0068698864  0.036913200  3.010804e-02
## 2017-12-29  0.0047402246  0.0369253399  0.0133984842 -0.003731107  1.205509e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)
covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398369e-05 0.0001042129 4.178513e-05 -7.812064e-05 -9.030157e-06
## EEM  1.042129e-04 0.0017547108 1.039018e-03  6.437743e-04  6.795433e-04
## EFA  4.178513e-05 0.0010390182 1.064237e-03  6.490288e-04  6.975379e-04
## IJS -7.812064e-05 0.0006437743 6.490288e-04  1.565452e-03  8.290240e-04
## SPY -9.030157e-06 0.0006795433 6.975379e-04  8.290240e-04  7.408259e-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.02347492
# 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.0003874243 0.009257153 0.005815633 0.005684466 0.002330245
rowSums(component_contribution)
## [1] 0.02347492
# 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
## # … with 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."))