# Load packages
# Core
library(tidyverse)
library(tidyquant)
Visualize and compare skewness of your portfolio and its assets.
Choose your stocks.
from 2012-12-31 to 2017-12-31
# Choose stocks
symbols <- c("MELI", "TTD", "SHOP", "AFL", "NVDA")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
asset_returns_tbl <- prices %>%
# Calculate monthly returns
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
# remane
set_names(c("asset", "date", "returns"))
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
w <- c(0.30,
0.10,
0.20,
0.15,
0.25)
w_tbl <- tibble(symbols, w)
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "months")
portfolio_returns_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2013-01-31 0.0115
## 2 2013-02-28 -0.0116
## 3 2013-03-28 0.0270
## 4 2013-04-30 0.0319
## 5 2013-05-31 0.0327
## 6 2013-06-28 0.000742
## 7 2013-07-31 0.0320
## 8 2013-08-30 -0.0115
## 9 2013-09-30 0.0447
## 10 2013-10-31 0.00912
## # … with 50 more rows
portfolio_skew_tidyquant_builtin_percent <- portfolio_returns_tbl %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Skewness)
# Data transformation: calculate skewness
asset_skewness_tbl <- asset_returns_tbl %>%
group_by(asset) %>%
summarise(skew = skewness(returns)) %>%
ungroup() %>%
# Add portfolio skewness
add_row(tibble(asset = "portfolio",
skew = skewness(portfolio_returns_tbl$returns)))
# Plot skewness
asset_skewness_tbl %>%
ggplot(aes(x = asset, y = skew, color = asset)) +
geom_point() +
ggrepel::geom_text_repel(aes(label = asset),
data = asset_skewness_tbl %>%
filter(asset == "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.
My portfolio overall is highly skewed with a value of over 1 and long tail to the right. NVDA has the highest skewness relative to the rest of my portfolio meaning it is has a long tail to the right and is likely to have extreme positive returns. On the other hand SHOP is moderately skewed with a longer tail to the left relative to my portfolio meaning is is likely to have larger losses.