# Load packages
# Core
library(tidyverse)
library(tidyquant)
Examine how each asset contributes to portfolio standard deviation. This is to ensure that our risk is not concentrated in any one asset.
Choose your stocks from 2012-12-31 to present.
symbols <- c ("AAPL", "NVDA", "F", "WMT", "MU")
prices <- tq_get(x = symbols,
get = "stockprices",
from = "2012-12-31",
to = "2017-12-31")
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"))
# Convert returns to wide format
asset_returns_wide_tbl <- asset_returns_tbl %>%
pivot_wider(
names_from = asset,
values_from = returns
)
# Set portfolio weights (equal weighting)
weights <- rep(1/5, 5)
names(weights) <- c("AAPL", "NVDA", "F", "WMT", "MU")
# Create returns matrix
returns_matrix <- asset_returns_wide_tbl %>%
select(all_of(names(weights))) %>%
as.matrix()
# Calculate covariance matrix
cov_matrix <- cov(returns_matrix)
# Calculate portfolio standard deviation
portfolio_variance <- as.numeric(
t(weights) %*% cov_matrix %*% weights
)
portfolio_sd <- sqrt(portfolio_variance)
# Calculate component contribution
component_contribution <- weights * (cov_matrix %*% weights) / portfolio_sd
# Create contribution table
component_contribution_tbl <- tibble(
asset = names(weights),
weight = weights,
component_contribution = as.numeric(component_contribution),
percent_contribution = as.numeric(component_contribution) / portfolio_sd
)
# Display results
component_contribution_tbl
## # A tibble: 5 × 4
## asset weight component_contribution percent_contribution
## <chr> <dbl> <dbl> <dbl>
## 1 AAPL 0.2 0.00808 0.169
## 2 NVDA 0.2 0.0127 0.265
## 3 F 0.2 0.00618 0.129
## 4 WMT 0.2 0.00302 0.0631
## 5 MU 0.2 0.0178 0.373
# Convert data to long format for plotting
component_contribution_plot_tbl <- component_contribution_tbl %>%
select(asset, weight, percent_contribution) %>%
pivot_longer(
cols = c(weight, percent_contribution),
names_to = "type",
values_to = "value"
)
# Create column chart
ggplot(component_contribution_plot_tbl,
aes(x = asset, y = value, fill = type)) +
geom_col(position = "dodge") +
scale_y_continuous(labels = scales::percent) +
labs(
title = "Component Contribution to Portfolio Volatility",
x = "Asset",
y = "Percentage",
fill = "Measure"
) +
theme_minimal()
Which of the assets in your portfolio the largest contributor to the portfolio volatility? Do you think your portfolio risk is concentrated in any one asset?
The stock with the highest percentage contribution is the largest contributor to portfolio volatility. Since my portfolio has five equally weighted stocks, each stock starts with a 20% weight. If one stock contributes much more than 20% of the total risk, it means that stock has a bigger impact on portfolio volatility. This could mean that some of my portfolio risk is concentrated in that stock.