# 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("TM", "SBUX", "AEO", "BBW")
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 = "quarterly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AEO" "BBW" "SBUX" "TM"
# weights
weights <- c(0.25, 0.25, 0.2, 0.3)
weights
## [1] 0.25 0.25 0.20 0.30
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 4 × 2
## symbols weights
## <chr> <dbl>
## 1 AEO 0.25
## 2 BBW 0.25
## 3 SBUX 0.2
## 4 TM 0.3
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: 20 × 2
## date returns
## <date> <dbl>
## 1 2013-03-28 0.108
## 2 2013-06-28 0.103
## 3 2013-09-30 0.0238
## 4 2013-12-31 0.0187
## 5 2014-03-31 -0.00730
## 6 2014-06-30 0.0916
## 7 2014-09-30 0.0548
## 8 2014-12-31 0.136
## 9 2015-03-31 0.112
## 10 2015-06-30 -0.0356
## 11 2015-09-30 -0.00379
## 12 2015-12-31 -0.0806
## 13 2016-03-31 -0.00559
## 14 2016-06-30 -0.0278
## 15 2016-09-30 0.00508
## 16 2016-12-30 0.0425
## 17 2017-03-31 -0.142
## 18 2017-06-30 -0.00367
## 19 2017-09-29 0.0345
## 20 2017-12-29 0.108
portfolio_kurt_tidyquant_builtin_percent <- portfolio_returns_tbl %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Kurtosis)
portfolio_kurt_tidyquant_builtin_percent
## # A tibble: 1 × 1
## Kurtosis
## <dbl>
## 1 -0.118
# Assign a value for window
window = 12
# Transform data: calculate 12 month rolling kurtosis
rolling_kurt_tbl <- portfolio_returns_tbl %>%
tq_mutate(select = returns,
mutate_fun = rollapply,
width = window,
FUN = kurtosis,
col_rename = "kurt") %>%
na.omit() %>%
select(-returns)
# Plot
rolling_kurt_tbl %>%
ggplot(aes(x = date, y = kurt)) +
geom_line(color = "cornflowerblue") +
# Formatting
scale_y_continuous(breaks = seq(-1,2,0.5)) +
scale_x_date(breaks = scales::pretty_breaks(n = 7)) +
theme(plot.title = element_text(hjust = 0.5)) +
# Labeling
labs(x = NULL,
y = "Kurtosis",
title = paste0("Rolling ", window," Month Kurtosis")) +
annotate(geom = "text", x = as.Date("2017-01-01"),
y = 1,
size = 5,
color = "red",
label = str_glue("Downside risk shows an overall
increase from 2016-2018."))
Has the downside risk of your portfolio increased or decreased over time? Explain using the plot you created. You may also refer to the skewness of the returns distribution you plotted in previous assignment.
The downside risk of my portfolio has an overall increase from 2016-2018, with a few months where it plateaus.