Simulação com o R

Análise de Dados Financeiros e Econômicos com o R

Marcelo S. Perlin

EA-UFRGS

05/11/2026

Concepts

Introduction

Simulation is the act of creating, artificially, possible paths (behavior) of a system subject to uncertainty (Brooks 2014).

  • Any system of stochastic (random) equations can be simulated with code (and R)
  • Applications of simulation in empirical problems (including Finance) are widespread

Calculating pi

Estimating a deterministic quantity with random draws (Monte Carlo):

\[P(\text{point inside the circle}) = \frac{\pi}{4} \quad \Rightarrow \quad \hat{\pi} = 4 \times \frac{\text{hits}}{M}\]

Calculating pi - animation

Each dot is one random draw; the estimate is 4 × (dots inside the circle) / total.

Simulating behavior in nature

AI learning from Simulations

Source report from Google Deepmind

Applications in Finance:

  • Pricing derivative contracts (options, swaps, …)
  • Finding moments and probabilities of complex systems of equations (e.g. payments system)
  • Project analysis (NPV & IRR) under uncertainty
  • Econometrics (bootstrap and pricing models)
  • Performance analysis of a trading strategy

A (biased) set of examples in applied research

Steps for a simulation

  1. Define or estimate a mathematical structure of the data generating process;
  1. Simulate the system of equations a reasonable amount of times and save the measure of interest at the end of each simulation;
  1. Repeat steps 1 and 2 many times;

Simulating with R

Random sampling in R

We always assume that the distribution of the random variables is known (or approximated by):

  • Symmetric: Uniform, Normal, Student’s t, Beta, etc
  • Positive: exponential, Gamma, Weibull, etc
  • Many more

In R, every distribution has a r function: rnorm(), runif(), rgamma(), rbeta(), …

Random sampling in R - Examples

How many simulations are enough?

Each simulation result is an estimate: it changes if you change the seed. Its precision is measured by the Monte Carlo standard error:

\[SE(\hat{\theta}) = \frac{SD\left(\hat{\theta}_i\right)}{\sqrt{M}}\]

  • Quadrupling M only halves the error: accuracy is expensive
  • The estimate is ~95% within \(\pm 1.96 \times SE\) of the true value
  • Always report the estimate and its Monte Carlo error

Convergence in practice

Estimate: 3.129 | Monte Carlo error: 0.023 | True value: 3.1416

A simple regression model

\(y _i = \alpha + \beta x_i + \epsilon _i\)

Simulated data (points) and the fitted regression line

A simple stochastic process in Finance

The discrete Random Walk Model

\[\begin{eqnarray} P_t&=&P_{t-1} \exp (R_t) \\ R_t &=& C + \epsilon _t \\ \epsilon _t &\sim& N\left(0,\sigma ^2 \right) \end{eqnarray}\]

where \(P_t\) is the price of the contract, \(R_t\) is the return (daily, monthly, ..)

A bit of math shows that:

  • Since \(E(R_t)=C\), you cannot predict \(P_{t+1}\)
  • Since \(\sigma(R_t)=\sigma(\epsilon _t)\), variance (uncertainty) per period is constant and increases with forecasting horizon

Exercise 1 - Creating a Random Walk

  1. Using a loop, create script ADFER-Exercicio-Aula-10-Simulação_1.R

  2. Within the script, simulate 100 prices of the following random walk model (use set.seed(1)). Note that P_0 = 100 is the first element of the vector, so you only need to simulate 99 returns:

\[\begin{eqnarray} R_t &=& 0.005 + \epsilon _t \\ \epsilon _t &\sim& N \left(0, \sigma ^2 \right) \\ P_t&=&P_{t-1} \exp (R_t) \\ P_0 &=& 100 \\ \sigma &=& 0.015 \end{eqnarray}\]

  1. With ggplot2, create a figure to represent the path of prices over time (use a sequence of dates as the x axis)

Exercise 2 - Simulating many random walks

  1. Based on previous exercise, create 1000 vectors of prices with the same random walk model with 100 time periods and save it in a tibble in the long format.

  2. Using ggplot2, create a single figure with the prices of all stocks

Applications

Pricing European Options with Simulation

A call option of the European type is a financial contract where the payoff is a function of the spot price:

\[\begin{equation} Payoff^C _T = \max(0 , P_T - K) \end{equation}\]

\(Payoff^C _T\) - Payoff (payment) of call option

\(P_T\) - Price of underlying asset in maturity (\(T\))

\(K\) - Strike price of contract

Pricing the option with simulation

We can calculate the price (Expected payoff) of this call option by simulating stock prices and calculating the simulated payoff at the expiration date

\[C = \frac{E\left[Payoff_T\right]}{(1+r)^T}\]

where \(r\) is the discount rate per period. With continuous compounding, \(C = e^{-rT} E\left[Payoff_T\right]\).

Note

The simulated prices use a zero drift (\(C = 0\)), i.e. we are assuming the risk-neutral measure.

Exercise 3 - Pricing a Call option

Consider the following RW model

\[\begin{eqnarray} R_t &=& 0 + \epsilon _t \\ \epsilon _t &\sim& N\left(0, \sigma ^2 \right) \\ P_t&=&P_{t-1} \exp (R_t) \\ P_0 &=& 100 \\ \sigma &=& 0.015 \end{eqnarray}\]

  1. Calculate the price of the call option with maturity in 100 periods, strike price equal to 110, yield rate equal to 5% for the whole time period. Use set.seed(10) and 1000 simulations

  2. Price an European put option that matures in 100 periods, strike price equal to 90, with 1000 simulations and set.seed(15)

Solution - Pricing the call option

set.seed(10)

M <- 1000; nT <- 100
P_0 <- 100; sigma <- 0.015
K <- 110; r <- 0.05

R <- matrix(rnorm(M*nT, 0, sigma), M, nT)
P_T <- P_0 * exp(rowSums(R))
C <- mean(pmax(P_T - K, 0))/(1 + r)
C
[1] 2.301126

The result is deterministic given the seed. Change the seed (or M) and the last digits will change.

Exercise 4 - Simulating Ibovespa

Consider the following RW model:

\[\begin{eqnarray} R_t &=& C + \epsilon _t \\ \epsilon _t &\sim& N\left(0, \sigma^2 \right) \\ P_t&=&P_{t-1} \exp (R_t) \\ \end{eqnarray}\]

  1. Use package yfR (Perlin 2023) to download daily data for Ibovespa (^BVSP) in the last 3 years (Sys.Date() - 365*3), e.g. with yfR::yf_get(tickers = "^BVSP", first_date = Sys.Date() - 365*3)

  2. Estimate parameters \(C\) and \(\sigma\) for the Ibovespa index as:

\[\begin{eqnarray} R_t &=& log(\frac{P_t}{P_{t-1}}) \\ C &=& E(R_t) \\ \sigma &=& SD(R_T) \end{eqnarray}\]

  1. Using the parameters from the estimation, simulate the prices of Ibovespa for the next 100 days. TIP: Use the last available price as \(P_0\).

  2. Create a figure with ggplot2, showing all possible paths of the simulation.

Bootstrap

Bootstrapping standard errors

One of the outputs of a linear regression is the standard error of each coefficient.

Consider a scenario where we are interested in a transformation of the parameters, such as:

\[\begin{eqnarray} y_t &=& \alpha + \beta _1 x_{1,t} + \beta _2 x_{2,t} + \epsilon _t \\ \Theta &=& \frac{\beta _1 - \beta _2}{\alpha} \end{eqnarray}\]

How to find the standard error of \(\Theta\)?

Bootstrapping standard errors

  1. Estimate the original model and save the created (conditional mean, \(\hat{y}_t\)) and the vector of residuals, \(\hat{\epsilon}_t\)

  2. Create a second variable \(y^*\) given by:

\[\begin{equation} y^*_t = \hat{y}_t + \epsilon ^* _t \end{equation}\]

where \(\epsilon ^* _t\) is a resampled vector of \(\hat{\epsilon}_t\) (same size, with replacement: sample(res, replace = TRUE))

  1. Estimate the econometric model:

\[y ^* _t = \alpha ^* + \beta ^* _1 x_{1,t} + \beta ^* _2 x_{2,t} + \epsilon _t \]

  1. Calculate:

\[\Theta ^* = \frac{\beta ^* _1 - \beta ^* _2}{\alpha ^*} \]

  1. Repeat steps 2, 3 and 4 M times, saving \(\Theta ^*\) in each case

  2. The final result will be a vector of \(\Theta ^*\). Its standard error is simply the standard deviation of the vector

Exercise 5 - Bootstrapping standard errors

  1. With package afedR3, load the data from file EX_Ibov_PETR4.csv (afedR3::data_path('EX_Ibov_PETR4.csv'))

  2. Estimate the market model for PETR4:

\[\begin{equation} R_t = \alpha + \beta R_{t,M} + \epsilon _t \end{equation}\]

where \(R_{t,M}\) is the return of Ibovespa

  1. Using the bootstrap procedure described earlier, calculate the standard error of \(\frac{\alpha}{\beta}\) with 1000 simulations

Referências

Brooks, Chris. 2014. Introductory Econometrics for Finance. Cambridge university press.
Perlin, Marcelo. 2023. yfR: Downloads and Organizes Financial Data from Yahoo Finance. https://github.com/ropensci/yfR.