Análise de Dados Financeiros e Econômicos com o R
EA-UFRGS
05/11/2026
Simulation is the act of creating, artificially, possible paths (behavior) of a system subject to uncertainty (Brooks 2014).
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}\]
Each dot is one random draw; the estimate is 4 × (dots inside the circle) / total.
Source report from Google Deepmind
We always assume that the distribution of the random variables is known (or approximated by):
In R, every distribution has a r function: rnorm(), runif(), rgamma(), rbeta(), …
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}}\]
M only halves the error: accuracy is expensiveEstimate: 3.129 | Monte Carlo error: 0.023 | True value: 3.1416
\(y _i = \alpha + \beta x_i + \epsilon _i\)
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:
Using a loop, create script ADFER-Exercicio-Aula-10-Simulação_1.R
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}\]
ggplot2, create a figure to represent the path of prices over time (use a sequence of dates as the x axis)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.
Using ggplot2, create a single figure with the prices of all stocks
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
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.
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}\]
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
Price an European put option that matures in 100 periods, strike price equal to 90, with 1000 simulations and set.seed(15)
[1] 2.301126
The result is deterministic given the seed. Change the seed (or M) and the last digits will change.
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}\]
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)
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}\]
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\).
Create a figure with ggplot2, showing all possible paths of the simulation.
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\)?
Estimate the original model and save the created (conditional mean, \(\hat{y}_t\)) and the vector of residuals, \(\hat{\epsilon}_t\)
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))
\[y ^* _t = \alpha ^* + \beta ^* _1 x_{1,t} + \beta ^* _2 x_{2,t} + \epsilon _t \]
\[\Theta ^* = \frac{\beta ^* _1 - \beta ^* _2}{\alpha ^*} \]
Repeat steps 2, 3 and 4 M times, saving \(\Theta ^*\) in each case
The final result will be a vector of \(\Theta ^*\). Its standard error is simply the standard deviation of the vector
With package afedR3, load the data from file EX_Ibov_PETR4.csv (afedR3::data_path('EX_Ibov_PETR4.csv'))
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
ADFER - UFRGS