# Load packages

# Core
library(tidyverse)
library(tidyquant)

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

symbol <- c("NVDA", "SIRI", "AAPL", "MCD")

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

2 Convert prices to returns (monthly)

asset_returns_tbl <- prices %>%
    
    group_by(symbol) %>%
    
    tq_transmute(select = adjusted,
                 mutate_fun = periodReturn,
                 period = "monthly",
                 type = "log") %>%
    slice(-1) %>%
    
    ungroup()

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

symbols <- asset_returns_tbl %>% distinct(symbol) %>% pull()
symbols
## [1] "AAPL" "MCD"  "NVDA" "SIRI"
weight <- c(0.25,0.3,0.3,0.15)
weight
## [1] 0.25 0.30 0.30 0.15
w_tbl <- tibble(symbols, weight)

4 Build a portfolio

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

5 Compute Skewness

portfolio_skew_tidyquant_builtin_percent <- portfolio_returns_tbl %>%
    
    tq_performance             (Ra = returns, 
                   performance_fun = table.Stats) %>%
    select                     (Skewness)

portfolio_skew_tidyquant_builtin_percent
## # A tibble: 1 × 1
##   Skewness
##      <dbl>
## 1    0.518

6 Plot: Skewness Comparison

asset_skewness_tbl <- asset_returns_tbl %>%
    
    group_by         (symbol)            %>%
    summarise(skew = skewness(monthly.returns)) %>%
    ungroup()                           %>%
    
    
    add_row(tibble(symbol = "portfolio",
                   skew  = skewness(portfolio_returns_tbl$returns)))

# Plot Skewness

asset_skewness_tbl %>%
    
    ggplot(aes(x     = symbol, 
               y     = skew,
               color = symbol)) +
    geom_point() +
    
    ggrepel::geom_text_repel(aes(label = symbol),
                             data = asset_skewness_tbl %>%
                                 filter(symbol == "portfolio")) +
    labs(y = "skewness")

Is any asset in your portfolio more likely to return extreme positive returns than your portfolio collectively? Discuss in terms of skewness. You may also refer to the distribution of returns you plotted in Code along 4.

NVDA has a much hihger skew than other stocks in the portfolio. Because of this, NVDA is much more likely than anything else to have extreme positive returns.