# Load packages
# Core
library(tidyverse)
library(tidyquant)
library(moments)
Visualize and compare skewness of your portfolio and its assets.
Choose your stocks.
from 2012-12-31 to 2017-12-31
symbols <- c("META", "NVDA", "JPM", "DIS", "BA")
prices <- tq_get(
x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31"
)
returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(
select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log"
) %>%
slice(-1) %>%
rename(returns = monthly.returns)
weights <- c(0.3, 0.2, 0.2, 0.2, 0.1) # Custom weights
w_tbl <- tibble(
symbol = symbols,
weights = weights
)
portfolio_returns_tbl <- returns_tbl %>%
tq_portfolio(
assets_col = symbol,
returns_col = returns,
weights = w_tbl,
col_rename = "portfolio.returns",
rebalance_on = "months"
)
# Asset skewness
asset_skew_tbl <- returns_tbl %>%
group_by(symbol) %>%
summarise(skewness = skewness(returns)) %>%
ungroup()
# Portfolio skewness
portfolio_skew <- skewness(portfolio_returns_tbl$portfolio.returns)
# Combine
skew_compare_tbl <- asset_skew_tbl %>%
add_row(symbol = "Portfolio", skewness = portfolio_skew)
skew_compare_tbl %>%
ggplot(aes(x = reorder(symbol, skewness), y = skewness, fill = symbol)) +
geom_col(show.legend = FALSE) +
geom_hline(yintercept = 0, linetype = "dashed") +
labs(
title = "Skewness Comparison: Assets vs. Portfolio",
x = "Symbol",
y = "Skewness"
) +
coord_flip() +
theme_minimal()
NVDA has the highest positive skewness, meaning it is more likely to have bigger positive returns than the rest. The portfolio’s skew is lower, showing even returns. NVDA has the highest potential for large gains.