# 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
symbols <- c("UPS", "FDX", "MSFT")
prices <- tq_get(x = symbols,
get = "stock.prices",
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"))
## asset date returns
## "asset" "date" "returns"
# symbols
symbols <- asset_returns_tbl %>% distinct(symbol) %>% pull()
# weights
weights <- c(0.5, 0.3, 0.2)
weights
## [1] 0.5 0.3 0.2
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 3 × 2
## symbols weights
## <chr> <dbl>
## 1 FDX 0.5
## 2 MSFT 0.3
## 3 UPS 0.2
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = symbol,
returns_col = monthly.returns,
weights = w_tbl,
rebalance_on = "months",
col_rename = "returns")
portfolio_returns_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2013-01-31 0.0732
## 2 2013-02-28 0.0353
## 3 2013-03-28 -0.0185
## 4 2013-04-30 0.0218
## 5 2013-05-31 0.0318
## 6 2013-06-28 0.0105
## 7 2013-07-31 0.0126
## 8 2013-08-30 0.0214
## 9 2013-09-30 0.0432
## 10 2013-10-31 0.102
## # … with 50 more rows
portfolio_skew_tiddyquant_builtin_percent <- portfolio_returns_tbl %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Skewness)
portfolio_skew_tiddyquant_builtin_percent
## # A tibble: 1 × 1
## Skewness
## <dbl>
## 1 -0.179
# Data Transfermation: Calculate Skewness
asset_skewness_tbl <- asset_returns_tbl %>%
group_by(symbol) %>%
summarize(skew = skewness(monthly.returns)) %>%
ungroup() %>%
## Add portfolio skewness
add_row(tibble(symbol = "portfolio",
skew = skewness(portfolio_returns_tbl$returns)))
asset_skewness_tbl
## # A tibble: 4 × 2
## symbol skew
## <chr> <dbl>
## 1 FDX -0.0655
## 2 MSFT 0.0825
## 3 UPS -0.628
## 4 portfolio -0.179
# plot sknewness
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.
I have one stock that has a positive skewness. That stock is Microsoft. This means that there is a higher chance that the returns will fall the the positive side of the spectrum.