# Load packages
# Core
library(tidyverse)
library(tidyquant)

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

        to   = "2017-12-31"
        

## 1 Import stock prices

# Choose stocks

symbols <- c("AAPL", "NVDA", "ADBE", "AVGO", "AMD")

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

2 Convert prices to returns (monthly)

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

# period_returns = c("yearly", "quarterly", "monthly", "weekly")

3 Assign a weight to each asset

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AAPL" "ADBE" "AMD"  "AVGO" "NVDA"
# 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)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AAPL       0.25
## 2 ADBE       0.25
## 3 AMD        0.2 
## 4 AVGO       0.2 
## 5 NVDA       0.1

4 Build a portfolio

portfolio_returns_rebalanced_monthly_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col   = asset,
                 returns_col  = returns,
                 weights      = w_tbl,
                 col_rename   = "returns",
                 rebalance_on = "months")

portfolio_returns_rebalanced_monthly_tbl
## # A tibble: 60 × 2
##    date        returns
##    <date>        <dbl>
##  1 2013-01-31  0.00258
##  2 2013-02-28 -0.0105 
##  3 2013-03-28  0.0430 
##  4 2013-04-30  0.0127 
##  5 2013-05-31  0.102  
##  6 2013-06-28 -0.0162 
##  7 2013-07-31  0.0255 
##  8 2013-08-30 -0.00421
##  9 2013-09-30  0.0858 
## 10 2013-10-31  0.0156 
## # ℹ 50 more rows
# write_rds(portfolio_returns_rebalanced_monthly_tbl,
#           "00_data/Ch03_portfolio_returns_rebalanced_monthly_tbl.rds")

5 Compute kurtosis

6 Plot: Rolling kurtosis

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.