# 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.0062311926 -0.0029353999  0.0366062698  0.052133346  4.992308e-02
## 2013-02-28  0.0058915620 -0.0231053950 -0.0129693922  0.016175396  1.267807e-02
## 2013-03-28  0.0009844680 -0.0102349089  0.0129693922  0.040258337  3.726807e-02
## 2013-04-30  0.0096391372  0.0120843648  0.0489677817  0.001222295  1.903008e-02
## 2013-05-31 -0.0202135319 -0.0494831030 -0.0306554141  0.041976213  2.333541e-02
## 2013-06-28 -0.0157783118 -0.0547284409 -0.0271446360 -0.001403290 -1.343500e-02
## 2013-07-31  0.0026875880  0.0131598108  0.0518603709  0.063541692  5.038616e-02
## 2013-08-30 -0.0082982190 -0.0257058733 -0.0197462980 -0.034743363 -3.045123e-02
## 2013-09-30  0.0111445437  0.0695889778  0.0753385007  0.063873430  3.115617e-02
## 2013-10-31  0.0082916286  0.0408611647  0.0320816277  0.034234073  4.526666e-02
## 2013-11-29 -0.0025100732 -0.0025941891  0.0054496983  0.041660963  2.920676e-02
## 2013-12-31 -0.0055833754 -0.0040741852  0.0215280708  0.012892396  2.559621e-02
## 2014-01-31  0.0152918839 -0.0903225241 -0.0534131976 -0.035775465 -3.588454e-02
## 2014-02-28  0.0037569263  0.0332203074  0.0595049505  0.045257656  4.451041e-02
## 2014-03-31 -0.0014818573  0.0380219842 -0.0046026026  0.013315236  8.261305e-03
## 2014-04-30  0.0081839040  0.0077726777  0.0165294199 -0.023184299  6.927368e-03
## 2014-05-30  0.0117214732  0.0290909599  0.0158284266  0.006205302  2.294127e-02
## 2014-06-30 -0.0005757341  0.0237340696  0.0091652299  0.037718885  2.043454e-02
## 2014-07-31 -0.0025121136  0.0135555467 -0.0263796551 -0.052009557 -1.352841e-02
## 2014-08-29  0.0114310679  0.0279047091  0.0018003039  0.043657827  3.870462e-02
## 2014-09-30 -0.0061679402 -0.0808566890 -0.0395981671 -0.061260322 -1.389244e-02
## 2014-10-31  0.0105846395  0.0140964530 -0.0026549510  0.068874624  2.327789e-02
## 2014-11-28  0.0065493559 -0.0155413204  0.0006253941  0.004773860  2.710130e-02
## 2014-12-31  0.0014747100 -0.0404419724 -0.0407468287  0.025295898 -2.539942e-03
## 2015-01-30  0.0203154948 -0.0068957467  0.0062265852 -0.054628216 -3.007704e-02
## 2015-02-27 -0.0089889384  0.0431361290  0.0614505787  0.056914681  5.468212e-02
## 2015-03-31  0.0037405952 -0.0150863546 -0.0143888272  0.010156398 -1.583013e-02
## 2015-04-30 -0.0032328217  0.0662813686  0.0358164986 -0.018417676  9.785637e-03
## 2015-05-29 -0.0043837170 -0.0419110105  0.0019526917  0.007509721  1.277425e-02
## 2015-06-30 -0.0108256141 -0.0297466579 -0.0316787464  0.004171549 -2.052134e-02
## 2015-07-31  0.0085847607 -0.0651780755  0.0201143765 -0.027375551  2.233798e-02
## 2015-08-31 -0.0033640373 -0.0925124157 -0.0771523775 -0.047268237 -6.288659e-02
## 2015-09-30  0.0080814639 -0.0318249314 -0.0451949311 -0.038464356 -2.584702e-02
## 2015-10-30  0.0006855854  0.0618082004  0.0640259285  0.063589509  8.163469e-02
## 2015-11-30 -0.0038981858 -0.0255603267 -0.0075556977  0.024415169  3.648338e-03
## 2015-12-31 -0.0019192217 -0.0389471503 -0.0235951354 -0.052157113 -1.743338e-02
## 2016-01-29  0.0123300189 -0.0516369092 -0.0567578984 -0.060306770 -5.106871e-02
## 2016-02-29  0.0088313198 -0.0082114634 -0.0339138008  0.020605281 -8.261809e-04
## 2016-03-31  0.0087093580  0.1218790178  0.0637455859  0.089910304  6.510026e-02
## 2016-04-29  0.0025460805  0.0040792904  0.0219752057  0.021044191  3.933117e-03
## 2016-05-31  0.0001355689 -0.0376284622 -0.0008562266  0.004396887  1.686872e-02
## 2016-06-30  0.0191668473  0.0445822638 -0.0244913881  0.008292535  3.470050e-03
## 2016-07-29  0.0054297239  0.0524423143  0.0390001135  0.049348244  3.582163e-02
## 2016-08-31 -0.0021566404  0.0087983786  0.0053268421  0.011261140  1.197118e-03
## 2016-09-30  0.0005160925  0.0248730027  0.0132791871  0.008614605  5.781623e-05
## 2016-10-31 -0.0082051509 -0.0083122303 -0.0224037254 -0.038134764 -1.748910e-02
## 2016-11-30 -0.0259900675 -0.0451616881 -0.0179744481  0.125246299  3.617611e-02
## 2016-12-30  0.0025384292 -0.0025300265  0.0267030340  0.031491858  2.006916e-02
## 2017-01-31  0.0021258274  0.0644314713  0.0323818541 -0.012143733  1.773650e-02
## 2017-02-28  0.0064382233  0.0172577695  0.0118362426  0.013428467  3.853918e-02
## 2017-03-31 -0.0005530170  0.0361889948  0.0318058872 -0.006533198  1.249130e-03
## 2017-04-28  0.0090295199  0.0168663683  0.0239520280  0.005107994  9.877179e-03
## 2017-05-31  0.0068472999  0.0280599886  0.0348103459 -0.022862434  1.401426e-02
## 2017-06-30 -0.0001827013  0.0092237211  0.0029558685  0.029151717  6.354781e-03
## 2017-07-31  0.0033345293  0.0565944875  0.0261878299  0.007481667  2.034572e-02
## 2017-08-31  0.0093690314  0.0232437060 -0.0004482268 -0.027565040  2.913399e-03
## 2017-09-29 -0.0057320286 -0.0004461787  0.0233428412  0.082322018  1.994925e-02
## 2017-10-31  0.0009777077  0.0322784865  0.0166537060  0.005916103  2.329065e-02
## 2017-11-30 -0.0014839913 -0.0038969510  0.0068696192  0.036913076  3.010792e-02
## 2017-12-29  0.0047404255  0.0369254109  0.0133986185 -0.003731106  1.205508e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398568e-05 0.0001042116 4.178371e-05 -7.811936e-05 -9.030653e-06
## EEM  1.042116e-04 0.0017547101 1.039016e-03  6.437751e-04  6.795436e-04
## EFA  4.178371e-05 0.0010390161 1.064236e-03  6.490284e-04  6.975400e-04
## IJS -7.811936e-05 0.0006437751 6.490284e-04  1.565449e-03  8.290247e-04
## SPY -9.030653e-06 0.0006795436 6.975400e-04  8.290247e-04  7.408288e-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.0003874256 0.009257147 0.005815628 0.005684467 0.002330249
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.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
## # … 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."))