# Load packages

# Core
library(tidyverse)
library(tidyquant)

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

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

prices <- tq_get(x = symbol,
                 get = "stock.prices",
                 from = "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()

3 Assign a weight to each asset

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

4 Build a portfolio

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

5 Compute Standard Deviation

portfolio_sd_tq_builtin_percent <- portfolio_returns_tbl %>%
    tq_performance(Ra = portfolio.returns,
                   performance_fun = table.Stats) %>%
    select(Stdev) %>%
    mutate(tq_sd = round(Stdev, 4))
portfolio_mean_sd_tq_builtin_percent <- mean(portfolio_returns_tbl$portfolio.returns)

Rolling Average

Rolling_sd_tbl <- portfolio_returns_tbl %>%
    tq_mutate(select = portfolio.returns,
              mutate_fun = rollapply,
              width = 24,
              FUN = sd,
              col_rename = "rolling_sd") %>%
    na.omit() %>%
    select(date, rolling_sd)

Rolling_sd_tbl %>%
    ggplot(aes(x = date, y = rolling_sd)) +
    geom_line(color = "Violet") +
    scale_y_continuous(labels = scales::percent_format()) +
    labs(x = NULL,
         y = NULL,
         title = "24 Month Rolling Volatility") +
    theme(plot.title = element_text(hjust = 0.5))

6 Plot

sd_mean_tbl <- asset_returns_tbl %>%
    group_by(symbol) %>%
    tq_performance(Ra = monthly.returns,
                   performance_fun = table.Stats) %>%
    select(Mean = ArithmeticMean, Stdev) %>%
    ungroup() %>% 
        add_row(tibble(symbol = "Portfolio",
                       Mean = portfolio_mean_sd_tq_builtin_percent,
                       Stdev = portfolio_sd_tq_builtin_percent$tq_sd))

sd_mean_tbl %>%
    ggplot(aes(x = Stdev, y = Mean, color = symbol)) +
    geom_point() +
    ggrepel::geom_text_repel(aes(label = symbol))