# 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

# 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.0062307228 -0.0029351611  0.0366062683  0.052132728  4.992292e-02
## 2013-02-28  0.0058903340 -0.0231052945 -0.0129694920  0.016176052  1.267794e-02
## 2013-03-28  0.0009849996 -0.0102354792  0.0129694920  0.040258030  3.726854e-02
## 2013-04-30  0.0096395843  0.0120850916  0.0489678212  0.001222116  1.902948e-02
## 2013-05-31 -0.0202142209 -0.0494834671 -0.0306557453  0.041976623  2.333564e-02
## 2013-06-28 -0.0157781628 -0.0547284208 -0.0271443858 -0.001402890 -1.343405e-02
## 2013-07-31  0.0026877865  0.0131596687  0.0518601145  0.063541090  5.038561e-02
## 2013-08-30 -0.0082981319 -0.0257056452 -0.0197459878 -0.034743440 -3.045117e-02
## 2013-09-30  0.0111438572  0.0695889871  0.0753384250  0.063873909  3.115588e-02
## 2013-10-31  0.0082916996  0.0408613786  0.0320816706  0.034233954  4.526658e-02
## 2013-11-29 -0.0025092432 -0.0025942093  0.0054496048  0.041661092  2.920693e-02
## 2013-12-31 -0.0055831500 -0.0040742789  0.0215279517  0.012892172  2.559637e-02
## 2014-01-31  0.0152911846 -0.0903229335 -0.0534132452 -0.035775528 -3.588492e-02
## 2014-02-28  0.0037572105  0.0332206934  0.0595051292  0.045257439  4.451045e-02
## 2014-03-31 -0.0014817166  0.0380218576 -0.0046026588  0.013315639  8.261088e-03
## 2014-04-30  0.0081832572  0.0077729803  0.0165295249 -0.023184344  6.927879e-03
## 2014-05-30  0.0117215529  0.0290909612  0.0158284495  0.006205095  2.294088e-02
## 2014-06-30 -0.0005758613  0.0237339705  0.0091653784  0.037718895  2.043519e-02
## 2014-07-31 -0.0025120158  0.0135553791 -0.0263800245 -0.052009486 -1.352921e-02
## 2014-08-29  0.0114308528  0.0279046093  0.0018007060  0.043657784  3.870510e-02
## 2014-09-30 -0.0061673343 -0.0808566610 -0.0395984610 -0.061260610 -1.389249e-02
## 2014-10-31  0.0105841894  0.0140964731 -0.0026549836  0.068875058  2.327794e-02
## 2014-11-28  0.0065492318 -0.0155413094  0.0006254588  0.004773810  2.710122e-02
## 2014-12-31  0.0014752309 -0.0404420753 -0.0407468108  0.025295556 -2.539621e-03
## 2015-01-30  0.0203147784 -0.0068958566  0.0062266082 -0.054628117 -3.007702e-02
## 2015-02-27 -0.0089883400  0.0431361521  0.0614504843  0.056915007  5.468158e-02
## 2015-03-31  0.0037405796 -0.0150862344 -0.0143887809  0.010156202 -1.583005e-02
## 2015-04-30 -0.0032331741  0.0662816348  0.0358165271 -0.018417616  9.785923e-03
## 2015-05-29 -0.0043836631 -0.0419111998  0.0019526300  0.007509872  1.277430e-02
## 2015-06-30 -0.0108256249 -0.0297467198 -0.0316786705  0.004171475 -2.052168e-02
## 2015-07-31  0.0085851282 -0.0651780633  0.0201144512 -0.027375710  2.233829e-02
## 2015-08-31 -0.0033636431 -0.0925124330 -0.0771525852 -0.047268128 -6.288709e-02
## 2015-09-30  0.0080808855 -0.0318249004 -0.0451948477 -0.038464595 -2.584694e-02
## 2015-10-30  0.0006857931  0.0618083383  0.0640260250  0.063589443  8.163489e-02
## 2015-11-30 -0.0038984764 -0.0255606789 -0.0075557898  0.024415465  3.648612e-03
## 2015-12-31 -0.0019190319 -0.0389468317 -0.0235951923 -0.052157126 -1.743342e-02
## 2016-01-29  0.0123303874 -0.0516366464 -0.0567577281 -0.060306518 -5.106891e-02
## 2016-02-29  0.0088315622 -0.0082115117 -0.0339138171  0.020604896 -8.263023e-04
## 2016-03-31  0.0087086818  0.1218789290  0.0637456903  0.089910442  6.510012e-02
## 2016-04-29  0.0025461104  0.0040791611  0.0219749044  0.021044040  3.933750e-03
## 2016-05-31  0.0001352650 -0.0376284923 -0.0008559461  0.004397251  1.686845e-02
## 2016-06-30  0.0191671881  0.0445822247 -0.0244914914  0.008292281  3.469883e-03
## 2016-07-29  0.0054291958  0.0524421864  0.0390002493  0.049348286  3.582168e-02
## 2016-08-31 -0.0021563142  0.0087987068  0.0053269927  0.011261006  1.197111e-03
## 2016-09-30  0.0005160494  0.0248729243  0.0132789601  0.008614745  5.783827e-05
## 2016-10-31 -0.0082047585 -0.0083123775 -0.0224037486 -0.038134827 -1.748917e-02
## 2016-11-30 -0.0259894982 -0.0451615512 -0.0179746195  0.125246673  3.617625e-02
## 2016-12-30  0.0025377923 -0.0025303202  0.0267032300  0.031491692  2.006908e-02
## 2017-01-31  0.0021260169  0.0644314819  0.0323816675 -0.012143972  1.773650e-02
## 2017-02-28  0.0064379832  0.0172579649  0.0118364539  0.013428986  3.853912e-02
## 2017-03-31 -0.0005530493  0.0361890651  0.0318056038 -0.006533415  1.249217e-03
## 2017-04-28  0.0090293346  0.0168663300  0.0239523267  0.005107722  9.877204e-03
## 2017-05-31  0.0068473355  0.0280597379  0.0348101874 -0.022862543  1.401414e-02
## 2017-06-30 -0.0001824948  0.0092239365  0.0029559205  0.029151706  6.354761e-03
## 2017-07-31  0.0033339863  0.0565943231  0.0261877986  0.007481816  2.034595e-02
## 2017-08-31  0.0093694586  0.0232439097 -0.0004481055 -0.027564930  2.913519e-03
## 2017-09-29 -0.0057322919 -0.0004462722  0.0233427009  0.082321460  1.994908e-02
## 2017-10-31  0.0009781554  0.0322785182  0.0166538307  0.005916585  2.329051e-02
## 2017-11-30 -0.0014844651 -0.0038968552  0.0068698020  0.036912945  3.010800e-02
## 2017-12-29  0.0047403831  0.0369254638  0.0133983589 -0.003731152  1.205500e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398354e-05 0.0001042092 4.178287e-05 -7.812061e-05 -9.031108e-06
## EEM  1.042092e-04 0.0017547124 1.039018e-03  6.437744e-04  6.795430e-04
## EFA  4.178287e-05 0.0010390177 1.064237e-03  6.490277e-04  6.975404e-04
## IJS -7.812061e-05 0.0006437744 6.490277e-04  1.565450e-03  8.290259e-04
## SPY -9.031108e-06 0.0006795430 6.975404e-04  8.290259e-04  7.408302e-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.0003874085 0.009257151 0.005815632 0.005684466 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.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."))