# 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.0062315601 -0.0029352045  0.0366063344  0.052133270  4.992271e-02
## 2013-02-28  0.0058918505 -0.0231058279 -0.0129697347  0.016175587  1.267838e-02
## 2013-03-28  0.0009844370 -0.0102345667  0.0129697347  0.040258131  3.726824e-02
## 2013-04-30  0.0096390815  0.0120846536  0.0489676230  0.001222011  1.902973e-02
## 2013-05-31 -0.0202138805 -0.0494834296 -0.0306555699  0.041976703  2.333507e-02
## 2013-06-28 -0.0157782669 -0.0547283273 -0.0271442971 -0.001402992 -1.343410e-02
## 2013-07-31  0.0026878497  0.0131599380  0.0518600140  0.063541395  5.038592e-02
## 2013-08-30 -0.0082978190 -0.0257059377 -0.0197461242 -0.034743555 -3.045123e-02
## 2013-09-30  0.0111435229  0.0695891622  0.0753385829  0.063873984  3.115606e-02
## 2013-10-31  0.0082920800  0.0408611599  0.0320815455  0.034233886  4.526656e-02
## 2013-11-29 -0.0025094682 -0.0025940732  0.0054499160  0.041661123  2.920726e-02
## 2013-12-31 -0.0055834339 -0.0040744164  0.0215277756  0.012892123  2.559571e-02
## 2014-01-31  0.0152922551 -0.0903225241 -0.0534132019 -0.035775378 -3.588444e-02
## 2014-02-28  0.0037558268  0.0332203074  0.0595048974  0.045257424  4.451011e-02
## 2014-03-31 -0.0014808867  0.0380219842 -0.0046023324  0.013315318  8.261597e-03
## 2014-04-30  0.0081831047  0.0077726777  0.0165294367 -0.023184382  6.927468e-03
## 2014-05-30  0.0117214635  0.0290909599  0.0158283493  0.006205467  2.294127e-02
## 2014-06-30 -0.0005762206  0.0237339583  0.0091652849  0.037718724  2.043436e-02
## 2014-07-31 -0.0025115963  0.0135555756 -0.0263797279 -0.052009541 -1.352832e-02
## 2014-08-29  0.0114306241  0.0279047915  0.0018004559  0.043657969  3.870454e-02
## 2014-09-30 -0.0061675319 -0.0808566890 -0.0395983763 -0.061260635 -1.389263e-02
## 2014-10-31  0.0105849725  0.0140964530 -0.0026549510  0.068875095  2.327834e-02
## 2014-11-28  0.0065487042 -0.0155412045  0.0006251760  0.004773544  2.710112e-02
## 2014-12-31  0.0014750008 -0.0404422091 -0.0407465280  0.025295823 -2.539852e-03
## 2015-01-30  0.0203152454 -0.0068957476  0.0062263384 -0.054628062 -3.007703e-02
## 2015-02-27 -0.0089879601  0.0431361342  0.0614506078  0.056914681  5.468186e-02
## 2015-03-31  0.0037399743 -0.0150862381 -0.0143886921  0.010156474 -1.583005e-02
## 2015-04-30 -0.0032328722  0.0662812579  0.0358165742 -0.018417694  9.785643e-03
## 2015-05-29 -0.0043836322 -0.0419108998  0.0019526727  0.007509740  1.277433e-02
## 2015-06-30 -0.0108257314 -0.0297466579 -0.0316789392  0.004171529 -2.052134e-02
## 2015-07-31  0.0085855320 -0.0651782975  0.0201146462 -0.027375530  2.233798e-02
## 2015-08-31 -0.0033649334 -0.0925122633 -0.0771524286 -0.047268316 -6.288677e-02
## 2015-09-30  0.0080817647 -0.0318250055 -0.0451949488 -0.038464612 -2.584693e-02
## 2015-10-30  0.0006853715  0.0618083440  0.0640258032  0.063589685  8.163503e-02
## 2015-11-30 -0.0038982071 -0.0255604653 -0.0075558000  0.024415191  3.648255e-03
## 2015-12-31 -0.0019189172 -0.0389470837 -0.0235950350 -0.052157198 -1.743337e-02
## 2016-01-29  0.0123300564 -0.0516367613 -0.0567579021 -0.060306867 -5.106897e-02
## 2016-02-29  0.0088314706 -0.0082113098 -0.0339138259  0.020605372 -8.262692e-04
## 2016-03-31  0.0087091197  0.1218789238  0.0637455915  0.089910297  6.510035e-02
## 2016-04-29  0.0025461876  0.0040792898  0.0219752075  0.021044348  3.933446e-03
## 2016-05-31  0.0001353850 -0.0376286321 -0.0008560588  0.004397040  1.686856e-02
## 2016-06-30  0.0191668104  0.0445822654 -0.0244915580  0.008292173  3.469969e-03
## 2016-07-29  0.0054296218  0.0524423478  0.0390002822  0.049348651  3.582155e-02
## 2016-08-31 -0.0021561708  0.0087985990  0.0053267594  0.011260870  1.197035e-03
## 2016-09-30  0.0005164227  0.0248727823  0.0132791871  0.008614677  5.805468e-05
## 2016-10-31 -0.0082052751 -0.0083123542 -0.0224035594 -0.038134617 -1.748925e-02
## 2016-11-30 -0.0259900274 -0.0451615642 -0.0179745296  0.125246265  3.617627e-02
## 2016-12-30  0.0025379451 -0.0025301565  0.0267028672  0.031491870  2.006885e-02
## 2017-01-31  0.0021261831  0.0644314794  0.0323817970 -0.012144336  1.773651e-02
## 2017-02-28  0.0064382076  0.0172577716  0.0118364607  0.013429243  3.853918e-02
## 2017-03-31 -0.0005535251  0.0361891145  0.0318056750 -0.006533323  1.249347e-03
## 2017-04-28  0.0090292782  0.0168663683  0.0239523104  0.005108009  9.877254e-03
## 2017-05-31  0.0068475066  0.0280599886  0.0348102689 -0.022862623  1.401419e-02
## 2017-06-30 -0.0001823073  0.0092235023  0.0029557966  0.029151717  6.354781e-03
## 2017-07-31  0.0033340485  0.0565948097  0.0261878997  0.007481543  2.034565e-02
## 2017-08-31  0.0093689703  0.0232436027 -0.0004482966 -0.027564741  2.913399e-03
## 2017-09-29 -0.0057318861 -0.0004462797  0.0233427730  0.082321622  1.994919e-02
## 2017-10-31  0.0009779271  0.0322784897  0.0166537072  0.005916104  2.329065e-02
## 2017-11-30 -0.0014840877 -0.0038968531  0.0068699364  0.036913506  3.010824e-02
## 2017-12-29  0.0047403577  0.0369254109  0.0133983026 -0.003731204  1.205496e-02
# Covariance of asset returns
covariance_matrix <- cov(asset_returns_wide_tbl)

covariance_matrix
##               AGG          EEM          EFA           IJS           SPY
## AGG  7.398478e-05 0.0001042097 4.178137e-05 -7.812117e-05 -9.031399e-06
## EEM  1.042097e-04 0.0017547114 1.039016e-03  6.437755e-04  6.795437e-04
## EFA  4.178137e-05 0.0010390164 1.064235e-03  6.490285e-04  6.975390e-04
## IJS -7.812117e-05 0.0006437755 6.490285e-04  1.565453e-03  8.290261e-04
## SPY -9.031399e-06 0.0006795437 6.975390e-04  8.290261e-04  7.408280e-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.005815624 0.005684474 0.00233025
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."))