# Load packages
# Load packages
library(tidyverse)
library(tidyquant)
library(moments)
library(ggrepel)
library(scales)
library(stringr)

Goal

Visualize and examine changes in the underlying trend in the downside risk of your portfolio in terms of kurtosis.

Choose your stocks.

from 2012-12-31 to present

1 Import stock prices

symbols <- c("AAPL", "MSFT", "GOOG", "AMZN", "TSLA", "NFLX")

prices <- tq_get(
  x    = symbols,
  get  = "stock.prices",
  from = "2012-12-31",
  to   = Sys.Date()
)

2 Convert prices to returns (monthly)

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

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

weights <- c(0.10, 0.15, 0.20, 0.20, 0.20, 0.15)

4 Build a portfolio

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

5 Compute kurtosis

window <- 24

rolling_kurt_tbl <- portfolio_returns_tbl %>%
  tq_mutate(select = returns,
            mutate_fun = rollapply,
            width = window,
            FUN = kurtosis,
            col_rename = "kurt") %>%
  na.omit() %>%
  select(date, kurt)

6 Plot: Rolling kurtosis

rolling_kurt_tbl %>%
  ggplot(aes(x = date, y = kurt)) +
  geom_line(color = "cornflowerblue") +
  scale_y_continuous(breaks = seq(-1, 10, 0.5)) +
  scale_x_date(breaks = scales::pretty_breaks(n = 8)) +
  labs(
    x = NULL,
    y = "Kurtosis",
    title = paste0("Rolling ", window, "-Month Kurtosis of Portfolio Returns")
  ) +
  theme(plot.title = element_text(hjust = 0.5)) +
  annotate(
    "text",
    x = as.Date("2022-01-01"),
    y = 6,
    label = str_glue("Downside risk\nspiked post-2020"),
    size = 5,
    color = "red"
  )

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 the previous assignment.

Based off the rolling kurtosis plot, my portfolio’s downside risk has increased overall, especially in recent years. The spike in kurtosis after 2020 shows more frequent extreme returns, suggesting a higher chance of larger losses. In the previous assignment, the portfolio showed a negative skew return distribution, which shows in the kurtosis calculation.