# Load packages

# Core
library(tidyverse)
library(tidyquant)

# time series
library(timetk)

Goal

Simulate future portfolio returns

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

market: “SPY”

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",    
                 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() %>%
    
    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)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AGG        0.25
## 2 EEM        0.25
## 3 EFA        0.2 
## 4 IJS        0.2 
## 5 SPY        0.1

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

portfolio_returns_tbl
## # A tibble: 60 × 2
##    date        returns
##    <date>        <dbl>
##  1 2013-01-31  0.0204 
##  2 2013-02-28 -0.00239
##  3 2013-03-28  0.0121 
##  4 2013-04-30  0.0174 
##  5 2013-05-31 -0.0128 
##  6 2013-06-28 -0.0247 
##  7 2013-07-31  0.0321 
##  8 2013-08-30 -0.0224 
##  9 2013-09-30  0.0511 
## 10 2013-10-31  0.0301 
## # ℹ 50 more rows

5 Simulating growth of a dollar

# Get mean portfolio return
mean_port_return <- mean(portfolio_returns_tbl$returns)
mean_port_return
## [1] 0.005899134
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.0234749
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  6.825768e-03  9.854920e-03  2.072346e-02 -1.467464e-02 -3.002450e-02
##   [6]  3.023531e-05  3.127915e-02  2.889491e-02 -2.136358e-02  2.242999e-02
##  [11] -2.959604e-02 -2.238466e-03  9.140345e-03  3.750546e-02  1.612748e-02
##  [16]  1.491106e-02 -1.993089e-02  4.202779e-02  6.411801e-03  2.981541e-02
##  [21]  3.709379e-02  9.360552e-03  1.298900e-02 -9.622453e-03 -4.889915e-03
##  [26] -1.159919e-02  3.927423e-02  5.308225e-02  1.499218e-02  3.762121e-02
##  [31]  1.398191e-02  5.605343e-02  6.488169e-03  5.405083e-02  1.844223e-03
##  [36]  6.093367e-04 -1.518309e-02 -1.293182e-02 -1.665222e-02 -4.109794e-03
##  [41] -1.960655e-02  3.894946e-02  1.283113e-03  1.991746e-03  4.325887e-02
##  [46]  7.550416e-03  4.556532e-03  7.877773e-03  9.954413e-03 -7.367660e-03
##  [51]  2.712971e-02  9.027330e-03  5.019586e-03  4.612523e-02 -1.389103e-02
##  [56]  1.180359e-02 -1.311299e-02 -1.806112e-03  8.096652e-04  9.881070e-03
##  [61] -1.667421e-04  5.251906e-02  1.105461e-02  1.850156e-02  4.629379e-03
##  [66]  1.387873e-02 -1.133880e-02  5.133948e-03 -4.593598e-02  2.475193e-02
##  [71] -4.323028e-03  4.313542e-02 -8.304947e-03 -1.709583e-02  1.683244e-02
##  [76]  2.545439e-02 -2.283921e-02  7.428997e-03  2.940410e-02  4.498954e-02
##  [81]  1.356693e-02  4.834783e-04  1.727799e-02  5.334797e-03  2.106281e-02
##  [86] -1.406096e-02 -1.485845e-02 -1.460488e-02  1.031339e-02  1.899076e-02
##  [91]  1.436955e-03 -4.037037e-03  1.085777e-02 -3.420728e-03 -1.650030e-02
##  [96]  7.262663e-03  4.376328e-03 -5.240517e-02  3.222013e-02 -4.787796e-03
## [101] -2.021986e-03 -2.011773e-02  4.434024e-02 -2.231658e-02  1.042503e-02
## [106] -2.438676e-02 -2.720467e-02 -2.275188e-02  2.469824e-02  1.190713e-02
## [111]  3.570253e-02 -3.558479e-02  4.377370e-04  1.714464e-02  2.498478e-02
## [116]  9.250028e-03  4.387761e-03 -4.294917e-02  2.453288e-02 -3.551089e-03
# Add a dollar
simulated_returns_add_1 <- tibble(returns = c(1, 1 + simulated_monthly_returns))
simulated_returns_add_1
## # A tibble: 121 × 1
##    returns
##      <dbl>
##  1   1    
##  2   1.01 
##  3   1.01 
##  4   1.02 
##  5   0.985
##  6   0.970
##  7   1.00 
##  8   1.03 
##  9   1.03 
## 10   0.979
## # ℹ 111 more rows
# Calculate the cumulative growth of a dollar
simulated_growth <- simulated_returns_add_1 %>%
    mutate(growth = accumulate(returns, function(x, y) x*y)) %>%
    select(growth)

simulated_growth
## # A tibble: 121 × 1
##    growth
##     <dbl>
##  1  1    
##  2  1.01 
##  3  1.02 
##  4  1.04 
##  5  1.02 
##  6  0.992
##  7  0.992
##  8  1.02 
##  9  1.05 
## 10  1.03 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 8.021939

6 Simulation function

simulate_accumulation <- function(initial_value,N, mean_return, sd_return) {
    # Add a dollar
simulated_returns_add_1 <- tibble(returns = c(initial_value, 1 + rnorm(N, mean_return, sd_return )))


# Calculate the cumulative growth of a dollar
simulated_growth <- simulated_returns_add_1 %>%
    mutate(growth = accumulate(returns, function(x, y) x*y)) %>%
    select(growth)

return(simulated_growth)
    
}

simulate_accumulation(initial_value = 100, N = 240, mean_return = 0.005, sd_return = 0.01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   314.
## 2   315.
## 3   319.
## 4   320.
## 5   323.
## 6   320.
if (!dir.exists("../00_scripts")) 
    dir.create("../00_scripts", recursive = TRUE)
    
dump (list = c("simulate_accumulation"),
      file = "../00_scripts/simulate_accumulation")

7 Running multiple simulations

# Create a vector of 1s as starting point
sims <- 100
starts <- rep (1, sims) %>%
    set_names(paste0("sim", 1:sims))
starts
##   sim1   sim2   sim3   sim4   sim5   sim6   sim7   sim8   sim9  sim10  sim11 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim12  sim13  sim14  sim15  sim16  sim17  sim18  sim19  sim20  sim21  sim22 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim23  sim24  sim25  sim26  sim27  sim28  sim29  sim30  sim31  sim32  sim33 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim34  sim35  sim36  sim37  sim38  sim39  sim40  sim41  sim42  sim43  sim44 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim45  sim46  sim47  sim48  sim49  sim50  sim51  sim52  sim53  sim54  sim55 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim56  sim57  sim58  sim59  sim60  sim61  sim62  sim63  sim64  sim65  sim66 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim67  sim68  sim69  sim70  sim71  sim72  sim73  sim74  sim75  sim76  sim77 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim78  sim79  sim80  sim81  sim82  sim83  sim84  sim85  sim86  sim87  sim88 
##      1      1      1      1      1      1      1      1      1      1      1 
##  sim89  sim90  sim91  sim92  sim93  sim94  sim95  sim96  sim97  sim98  sim99 
##      1      1      1      1      1      1      1      1      1      1      1 
## sim100 
##      1
# Simulate
# for reproducible research
set.seed (800)
monte_carlo_sim_51 <- starts %>%
    # Simulate 
    map_dfc (.x = .,
             .f = ~simulate_accumulation (initial_value = .x, N = 120, mean_return = mean_port_return, sd_return = stddev_port_return)) %>%
    
    # Add column month
    mutate(month = 1:nrow(.)) %>%
    select(month, everything()) %>%
    
    # Rearrange column names
    set_names(c("month", names(starts))) %>%
    
    # Transform to long form
    pivot_longer(cols= -month, names_to = "sim", values_to = "growth")

monte_carlo_sim_51
## # A tibble: 12,100 × 3
##    month sim   growth
##    <int> <chr>  <dbl>
##  1     1 sim1       1
##  2     1 sim2       1
##  3     1 sim3       1
##  4     1 sim4       1
##  5     1 sim5       1
##  6     1 sim6       1
##  7     1 sim7       1
##  8     1 sim8       1
##  9     1 sim9       1
## 10     1 sim10      1
## # ℹ 12,090 more rows
# Find quantiles
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
ungroup() %>%
    pull(growth) %>%

quantile(probs = c(0, 0.25, 0.5, 0.75, 1)) %>%
            round(2) 
##   0%  25%  50%  75% 100% 
## 1.16 1.76 2.06 2.39 3.37

8 Visualizing simulations with ggplot

monte_carlo_sim_51 %>%
    ggplot(aes(x = month, y = growth, color = sim)) +
    geom_line() +
    theme(legend.position = "none") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(plot.subtitle = element_text(hjust = 0.5)) +

labs(title = "Simulations growth of $1 over 120 months",
     subtitle = "Maximum, Median, and Minimum Simulation")

#Line plot with max, median, and min

# Step 1 Summarize data into max, median, and min of last value 
sim_summary <- monte_carlo_sim_51 %>%
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    
    summarise(max = max(growth),
              median = median(growth),
              min= min(growth))
sim_summary
## # A tibble: 1 × 3
##     max median   min
##   <dbl>  <dbl> <dbl>
## 1  3.37   2.06  1.16
# Step 2 Plot 
monte_carlo_sim_51 %>%
    group_by(sim) %>%
    filter(last(growth) == sim_summary$max |
               last(growth) == sim_summary$median |
               last(growth) == sim_summary$min) %>%
    ungroup() 
## # A tibble: 242 × 3
##    month sim   growth
##    <int> <chr>  <dbl>
##  1     1 sim59  1    
##  2     1 sim66  1    
##  3     2 sim59  0.992
##  4     2 sim66  0.980
##  5     3 sim59  1.03 
##  6     3 sim66  1.01 
##  7     4 sim59  1.06 
##  8     4 sim66  1.05 
##  9     5 sim59  1.07 
## 10     5 sim66  1.05 
## # ℹ 232 more rows