# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(moments)

Goal

Visualize and compare skewness of your portfolio and its assets.

Choose your stocks.

from 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c("META", "NVDA", "JPM", "DIS", "BA")

prices <- tq_get(
  x    = symbols,
  get  = "stock.prices",
  from = "2012-12-31",
  to   = "2017-12-31"
)

2 Convert prices to returns (monthly)

returns_tbl <- prices %>%
  group_by(symbol) %>%
  tq_transmute(
    select     = adjusted,
    mutate_fun = periodReturn,
    period     = "monthly",
    type       = "log"
  ) %>%
  slice(-1) %>%
  rename(returns = monthly.returns)

3 Assign a weight to each asset (change the weigting scheme)

weights <- c(0.3, 0.2, 0.2, 0.2, 0.1)  # Custom weights

w_tbl <- tibble(
  symbol  = symbols,
  weights = weights
)

4 Build a portfolio

portfolio_returns_tbl <- returns_tbl %>%
  tq_portfolio(
    assets_col   = symbol,
    returns_col  = returns,
    weights      = w_tbl,
    col_rename   = "portfolio.returns",
    rebalance_on = "months"
  )

5 Compute Skewness

# 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)

6 Plot: Skewness Comparison

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.