# Load packages
# Core
library(tidyverse)
library(tidyquant)
Visualize and compare skewness of your portfolio and its assets.
Choose your stocks.
from 2019-12-31 to 2024-12-31
symbols <- c("F", "RIVN", "LCID", "TM", "HMC")
# Using tq_get() ----
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2019-12-31",
to = "2024-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.25,
0.25,
0.20,
0.20,
0.10)
w_tbl <- tibble(symbols, w)
# ?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalance_on = "months",
col_rename = "returns")
portfolio_returns_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2020-01-31 -0.0354
## 2 2020-02-28 -0.0646
## 3 2020-03-31 -0.129
## 4 2020-04-30 0.0332
## 5 2020-05-29 0.0506
## 6 2020-06-30 0.0114
## 7 2020-07-31 0.00363
## 8 2020-08-31 0.0305
## 9 2020-09-30 -0.0219
## 10 2020-10-30 0.0324
## # ℹ 50 more rows
portfolio_returns_tbl %>%
tq_performance(Ra = returns,
Rb = NULL,
performance_fun = table.Stats) %>%
select(Skewness)
## # A tibble: 1 × 1
## Skewness
## <dbl>
## 1 -0.378
asset_returns_skew_tbl <- asset_returns_tbl %>%
# skewness for each asset
group_by(asset) %>%
summarise(skew = skewness(returns)) %>%
ungroup() %>%
# skewness of portfolio
add_row(tibble(asset = "Portfolio",
skew = skewness(portfolio_returns_tbl$returns)))
asset_returns_skew_tbl %>%
ggplot(aes(asset, skew, color = asset)) +
geom_point() +
# Add label for portfolio
ggrepel::geom_text_repel(aes(label = asset),
data = asset_returns_skew_tbl %>%
filter(asset == "Portfolio"),
size = 5,
show.legend = FALSE) +
labs(y = "skewness")
window <- 24
port_rolling_sd_tbl <- portfolio_returns_tbl %>%
tq_mutate(select = returns,
mutate_fun = rollapply,
width = window,
FUN = skewness,
col_rename = "rolling_skew") %>%
select(date, rolling_skew) %>%
na.omit()
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.
Concidering Skweness LCID is most likely to give excess returns to your
portfolio, but this also comes with a heavier risk.