# Monte Carlo Simulation in R – Part I

Contributor:
RStudio
Visit: RStudio

Director of Financial Services Practice at RStudio

Jonathan Regenstein demonstrates running and visualizing Monte Carlo portfolio simulations in R with RStudio.

Monte Carlo relies on repeated, random sampling, and we will sample based on two parameters: mean and standard deviation of portfolio returns.

``````+ SPY (S&P500 fund) weighted 25%
+ EFA (a non-US equities fund) weighted 25%
+ IJS (a small-cap value fund) weighted 20%
+ EEM (an emerging-mkts fund) weighted 20%
+ AGG (a bond fund) weighted 10%``````

Before we can simulate that portfolio, we need to calculate the historical portfolio monthly returns, which was covered in this article on Introduction to Portfolio Returns.

I won’t go through the logic again, but the code is here:

``````# This is the package we need for today's post.
library(tidyquant)
library(tidyverse)
library(timetk)
library(broom)

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

prices <-
getSymbols(symbols, src = 'yahoo',
from = "2012-12-31",
to = "2017-12-31",
auto.assign = TRUE, warnings = FALSE) %>%
reduce(merge) %>%
`colnames<-`(symbols)

w <- c(0.25, 0.25, 0.20, 0.20, 0.10)

asset_returns_long <-
prices %>%
to.monthly(indexAt = "lastof", OHLC = FALSE) %>%
tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
gather(asset, returns, -date) %>%
group_by(asset) %>%
mutate(returns = (log(returns) - log(lag(returns)))) %>%
na.omit()

portfolio_returns_tq_rebalanced_monthly <-
asset_returns_long %>%
tq_portfolio(assets_col  = asset,
returns_col = returns,
weights     = w,
col_rename  = "returns",
rebalance_on = "months")``````

We will be working with the data object portfolio_returns_tq_rebalanced_monthly and we first find the mean and standard deviation of returns.

We will name those variables mean_port_return and stddev_port_return.

``````mean_port_return <-
mean(portfolio_returns_tq_rebalanced_monthly\$returns)

stddev_port_return <-
sd(portfolio_returns_tq_rebalanced_monthly\$returns)``````

Then we use the rnorm() function to sample from a distribution with mean equal to mean_port_return and standard deviation equal to stddev_port_return. That is the crucial random sampling that underpins this exercise.

We also must decide how many draws to pull from this distribution, meaning how many monthly returns we will simulate. 120 months is 10 years and that feels like a good amount of time.

``````simulated_monthly_returns <- rnorm(120,
mean_port_return,
stddev_port_return)``````

Have a quick look at the simulated monthly returns.

``head(simulated_monthly_returns)``
``````[1]  0.050944351 -0.017579195  0.008322081  0.007901221  0.016835474
[6] -0.028979050``````
``tail(simulated_monthly_returns)``
``````[1] -0.010568223 -0.033228157 -0.012189181 -0.002823064  0.040136745
[6] -0.001618285``````

Next, we calculate how a dollar would have grown given those random monthly returns. We first add a 1 to each of our monthly returns, because we start with \$1.

``````simulated_returns_add_1 <-
tibble(c(1, 1 + simulated_monthly_returns)) %>%
`colnames<-`("returns")

``````# A tibble: 6 x 1
returns

1   1.00
2   1.05
3   0.982
4   1.01
5   1.01
6   1.02 ``````

In the next post, Jonathan will show us how to convert the data into the cumulative growth of a dollar using several R packages.

Jonathan Regenstein, Director of Financial Services, RStudio.
@jkregenstein  @rstudio. For additional R scripts, see the “Reproducible Finance with R: Code Flows and Shiny Apps for Portfolio Analysis” article.

##### Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from RStudio and is being posted with permission from RStudio. The views expressed in this material are solely those of the author and/or RStudio and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

##### Disclosure: Displaying Symbols on Video

Any stock, options or futures symbols displayed are for illustrative purposes only and are not intended to portray recommendations.