# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(dplyr)

Goal

Collect individual returns into a portfolio by assigning a weight to each stock

five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”

from 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")

prices <- tq_get(x   = symbols, 
                 get = "stock.prices",
                 fro = "2012-12-31",
                 to  = "2017-12-31")

2 Convert prices to returns

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"))

3 Assign a weight to each asset

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AGG" "EEM" "EFA" "IJS" "SPY"
# Weights
weights <- c(0.25, 0.25, 0.2, 0.2, 0.1)
weights
## [1] 0.25 0.25 0.20 0.20 0.10
w_tbl <- tibble(symbols, weights)

4 Build a portfolio

# ?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")

5 Calculate Kurtosis

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.488

6 Plot

Distribution of Plot Returns

portfolio_returns_tbl %>%
    ggplot(aes(x = returns)) +
    geom_histogram()

Expected Return Vs Downside Risk

# Transform Data

mean_kurt_tbl <- asset_returns_tbl %>%
    
    # Calculate mean return and kurtosis for assets
    group_by(asset) %>%
    summarise(mean = mean(returns),
              kurt = kurtosis(returns)) %>%
    ungroup() %>%
    
    # Add Portfolio Stats
    add_row(portfolio_returns_tbl %>%
    summarise(mean = mean(returns),
              kurt = kurtosis(returns)) %>%
        mutate(asset = "Portfolio"))

# Plot
mean_kurt_tbl %>%
    
    ggplot(aes(x = kurt, y = mean)) +
    geom_point() +
    ggrepel::geom_label_repel(aes(label = asset, color = asset)) +
    
    # Formatting
    theme(legend.position = "none") +
    scale_y_continuous(labels = scales::percent_format(accuracy = 0.1)) +
    
    # Labeling
    labs(x = "Kurt",
         y = "Expected Returns")

Rolling 24 Month Kurtosis

# Assign a Value for Window
window = 24

# Transform Data : Calculate 24 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,4,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("2016-07-01"), y = 3,
                                    size = 5, color = "red",
                                    label = "Downside risk skyrocketed
         towards the end of 2017")