# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(readr)

# Time series
library(lubridate)
library(tibbletime)

# modeling
library(broom)

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.0062307623 -0.0029356245  0.0366060144  0.052133270  4.992310e-02
## 2013-02-28  0.0058909604 -0.0231052881 -0.0129691407  0.016175479  1.267819e-02
## 2013-03-28  0.0009849670 -0.0102348823  0.0129691407  0.040257954  3.726772e-02
## 2013-04-30  0.0096394227  0.0120847681  0.0489678724  0.001222476  1.903020e-02
## 2013-05-31 -0.0202139531 -0.0494834238 -0.0306554809  0.041976250  2.333507e-02
## 2013-06-28 -0.0157787222 -0.0547283206 -0.0271443862 -0.001402448 -1.343376e-02
## 2013-07-31  0.0026882154  0.0131597481  0.0518601009  0.063541122  5.038568e-02
## 2013-08-30 -0.0082980901 -0.0257055209 -0.0197462111 -0.034743628 -3.045122e-02
## 2013-09-30  0.0111441460  0.0695886881  0.0753385007  0.063873965  3.115583e-02
## 2013-10-31  0.0082914569  0.0408611647  0.0320817670  0.034233976  4.526688e-02
## 2013-11-29 -0.0025098306 -0.0025939579  0.0054494799  0.041660956  2.920646e-02
## 2013-12-31 -0.0055825309 -0.0040744164  0.0215281500  0.012892228  2.559650e-02
## 2014-01-31  0.0152908231 -0.0903225876 -0.0534134224 -0.035775465 -3.588473e-02
## 2014-02-28  0.0037571563  0.0332203709  0.0595052522  0.045257349  4.451050e-02
## 2014-03-31 -0.0014813249  0.0380218659 -0.0046024668  0.013315604  8.261115e-03
## 2014-04-30  0.0081828412  0.0077726786  0.0165292071 -0.023184194  6.927657e-03
## 2014-05-30  0.0117218062  0.0290913053  0.0158284266  0.006205219  2.294127e-02
## 2014-06-30 -0.0005756089  0.0237339251  0.0091653598  0.037718645  2.043472e-02
## 2014-07-31 -0.0025119466  0.0135555730 -0.0263799374 -0.052009462 -1.352887e-02
## 2014-08-29  0.0114307101  0.0279045993  0.0018006655  0.043658049  3.870463e-02
## 2014-09-30 -0.0061678681 -0.0808568916 -0.0395984554 -0.061260481 -1.389218e-02
## 2014-10-31  0.0105842002  0.0140965415 -0.0026548718  0.068874783  2.327789e-02
## 2014-11-28  0.0065492195 -0.0155412062  0.0006253941  0.004773702  2.710121e-02
## 2014-12-31  0.0014752450 -0.0404424252 -0.0407469113  0.025295667 -2.539852e-03
## 2015-01-30  0.0203150047 -0.0068950811  0.0062264420 -0.054627742 -3.007703e-02
## 2015-02-27 -0.0089877203  0.0431357998  0.0614508044  0.056914571  5.468203e-02
## 2015-03-31  0.0037399849 -0.0150863268 -0.0143886902  0.010156416 -1.583047e-02
## 2015-04-30 -0.0032334528  0.0662813466  0.0358165883 -0.018417983  9.786062e-03
## 2015-05-29 -0.0043833152 -0.0419108998  0.0019524651  0.007509799  1.277409e-02
## 2015-06-30 -0.0108258112 -0.0297466579 -0.0316788826  0.004171683 -2.052117e-02
## 2015-07-31  0.0085848613 -0.0651782024  0.0201144364 -0.027375314  2.233806e-02
## 2015-08-31 -0.0033633317 -0.0925123584 -0.0771525278 -0.047268367 -6.288676e-02
## 2015-09-30  0.0080813420 -0.0318250055 -0.0451946398 -0.038464691 -2.584720e-02
## 2015-10-30  0.0006848667  0.0618083440  0.0640259447  0.063589680  8.163496e-02
## 2015-11-30 -0.0038978777 -0.0255603267 -0.0075558600  0.024415032  3.648672e-03
## 2015-12-31 -0.0019189943 -0.0389472583 -0.0235950539 -0.052156893 -1.743371e-02
## 2016-01-29  0.0123298929 -0.0516366494 -0.0567577218 -0.060306852 -5.106888e-02
## 2016-02-29  0.0088316341 -0.0082115386 -0.0339139774  0.020605045 -8.262692e-04
## 2016-03-31  0.0087086377  0.1218789414  0.0637456716  0.089910461  6.510061e-02
## 2016-04-29  0.0025466696  0.0040792904  0.0219750361  0.021044135  3.933281e-03
## 2016-05-31  0.0001354598 -0.0376284972 -0.0008560588  0.004397308  1.686839e-02
## 2016-06-30  0.0191664946  0.0445826336 -0.0244913860  0.008292172  3.469889e-03
## 2016-07-29  0.0054298629  0.0524418843  0.0390001102  0.049348446  3.582164e-02
## 2016-08-31 -0.0021562543  0.0087984739  0.0053267594  0.011261014  1.196957e-03
## 2016-09-30  0.0005157024  0.0248730027  0.0132792682  0.008614676  5.813243e-05
## 2016-10-31 -0.0082050291 -0.0083122303 -0.0224036405 -0.038134908 -1.748918e-02
## 2016-11-30 -0.0259896423 -0.0451618825 -0.0179746142  0.125246616  3.617611e-02
## 2016-12-30  0.0025382796 -0.0025299621  0.0267031163  0.031491803  2.006916e-02
## 2017-01-31  0.0021259462  0.0644312358  0.0323816324 -0.012143969  1.773650e-02
## 2017-02-28  0.0064378769  0.0172581350  0.0118366182  0.013428750  3.853918e-02
## 2017-03-31 -0.0005524671  0.0361888793  0.0318054412 -0.006533023  1.249064e-03
## 2017-04-28  0.0090291028  0.0168664838  0.0239523867  0.005107583  9.877395e-03
## 2017-05-31  0.0068471877  0.0280599886  0.0348101970 -0.022862434  1.401426e-02
## 2017-06-30 -0.0001826335  0.0092236117  0.0029557968  0.029151717  6.354708e-03
## 2017-07-31  0.0033343847  0.0565945969  0.0261880937  0.007481434  2.034565e-02
## 2017-08-31  0.0093691142  0.0232438828 -0.0004483665 -0.027564568  2.913333e-03
## 2017-09-29 -0.0057323650 -0.0004462544  0.0233425840  0.082321779  1.994932e-02
## 2017-10-31  0.0009780212  0.0322782876  0.0166538437  0.005915986  2.329072e-02
## 2017-11-30 -0.0014837741 -0.0038967549  0.0068700031  0.036913192  3.010823e-02
## 2017-12-29  0.0047401173  0.0369252417  0.0133981208 -0.003731106  1.205483e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398284e-05 0.0001042103 4.178444e-05 -7.811798e-05 -9.030269e-06
## EEM  1.042103e-04 0.0017547095 1.039017e-03  6.437721e-04  6.795429e-04
## EFA  4.178444e-05 0.0010390166 1.064237e-03  6.490290e-04  6.975419e-04
## IJS -7.811798e-05 0.0006437721 6.490290e-04  1.565449e-03  8.290253e-04
## SPY -9.030269e-06 0.0006795429 6.975419e-04  8.290253e-04  7.408300e-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.0003874195 0.009257138 0.005815636 0.005684466 0.002330252
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
## # … 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."))