| Title: | Stochastic Process Simulation Engine |
|---|---|
| Description: | A modular simulation engine for stochastic processes. Provides exact and approximate simulation methods for Poisson processes, Brownian motion, discrete-time Markov chains, Levy processes (gamma, normal inverse Gaussian, variance-gamma, alpha-stable), Merton jump-diffusion models, Hawkes self-exciting processes, geometric Brownian motion, and Ornstein-Uhlenbeck mean-reverting diffusions. Includes variance reduction techniques (antithetic variates, control variates, importance sampling, stratified sampling), parallel simulation via the 'future' framework, rare-event simulation (cross-entropy and multilevel splitting), path visualization, and summary statistics. Methods are based on Glasserman (2003) <doi:10.1007/978-0-387-21617-1> and Asmussen & Glynn (2007) <doi:10.1007/978-0-387-69033-9>. |
| Authors: | Ayush Kundu [aut, cre] (ORCID: <https://orcid.org/0009-0009-8715-2624>) |
| Maintainer: | Ayush Kundu <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0 |
| Built: | 2026-06-02 08:59:38 UTC |
| Source: | https://github.com/ayush291202/stochsimr |
Runs the same stochastic process under different simulation methods
(e.g., "exact" vs "euler") and compares bias, variance,
and computation time.
compare_methods( sim_fn, methods, n_paths = 1000L, reference_fn = NULL, n_reps = 20L, ... )compare_methods( sim_fn, methods, n_paths = 1000L, reference_fn = NULL, n_reps = 20L, ... )
sim_fn |
A StochSimR simulation function that accepts a
|
methods |
Character vector. Method names to compare. |
n_paths |
Positive integer. Paths per replication. |
reference_fn |
Optional function receiving the argument list and returning the exact expected terminal value, for bias computation. |
n_reps |
Positive integer. Independent replications per method. |
... |
Additional arguments to |
A data frame with one row per method and columns:
method, mean_terminal, sd_terminal, bias,
rmse, time_seconds.
# Compare exact vs Euler for OU (exact E[X_T] = mu for large T) compare_methods(sim_ou, methods = c("exact", "euler"), n_paths = 200, n_reps = 10, T_max = 5, n_steps = 500, theta = 2, mu = 1, sigma = 0.5, x0 = 0)# Compare exact vs Euler for OU (exact E[X_T] = mu for large T) compare_methods(sim_ou, methods = c("exact", "euler"), n_paths = 200, n_reps = 10, T_max = 5, n_steps = 500, theta = 2, mu = 1, sigma = 0.5, x0 = 0)
Test if an Object is a stoch_path
is_stoch_path(x)is_stoch_path(x)
x |
Any R object. |
TRUE if x inherits from class "stoch_path",
FALSE otherwise.
sp <- new_stoch_path(0:5, 1:6, "test", "test") is_stoch_path(sp) # TRUE is_stoch_path(42) # FALSEsp <- new_stoch_path(0:5, 1:6, "test", "test") is_stoch_path(sp) # TRUE is_stoch_path(42) # FALSE
General-purpose Monte Carlo estimator that simulates paths from any StochSimR process, evaluates a target functional, and provides convergence diagnostics via batch means.
mc_estimate(sim_fn, h, n_paths = 10000L, batch_size = 500L, alpha = 0.05, ...)mc_estimate(sim_fn, h, n_paths = 10000L, batch_size = 500L, alpha = 0.05, ...)
sim_fn |
A StochSimR simulation function. |
h |
Functional to evaluate on paths. Receives the values matrix
(rows = time, columns = paths) and returns a numeric vector of length
|
n_paths |
Positive integer. Total Monte Carlo replications. |
batch_size |
Positive integer. Size of each batch for batch-means standard error estimation. |
alpha |
Numeric in (0, 1). Significance level for confidence interval (default 0.05 gives 95% CI). |
... |
Additional arguments passed to |
A list with components:
Numeric. Monte Carlo estimate of .
Numeric. Standard error.
Numeric vector of length 2. Confidence interval.
Numeric. Significance level used.
Integer. Actual number of samples.
Numeric vector. Per-batch means.
Numeric vector. Per-batch variances.
Data frame with columns n, running_mean,
and running_se for monitoring convergence.
Character. "monte_carlo".
# Estimate E[max(B_1, 0)] where B is standard Brownian motion # Exact answer: 1/sqrt(2*pi) ~ 0.3989 h_pos <- function(vals) pmax(vals[nrow(vals), ], 0) mc <- mc_estimate(sim_brownian, h = h_pos, n_paths = 10000, T_max = 1, n_steps = 100) cat("Estimate:", mc$estimate, "+/-", mc$se, "\n")# Estimate E[max(B_1, 0)] where B is standard Brownian motion # Exact answer: 1/sqrt(2*pi) ~ 0.3989 h_pos <- function(vals) pmax(vals[nrow(vals), ], 0) mc <- mc_estimate(sim_brownian, h = h_pos, n_paths = 10000, T_max = 1, n_steps = 100) cat("Estimate:", mc$estimate, "+/-", mc$se, "\n")
Estimates probabilities of rare events using either the cross-entropy method (adaptive importance sampling) or multilevel splitting.
mc_rare_event( sim_fn, indicator, score, n_paths = 5000L, n_iter = 5L, quantile_level = 0.9, method = c("cross_entropy", "splitting"), ... )mc_rare_event( sim_fn, indicator, score, n_paths = 5000L, n_iter = 5L, quantile_level = 0.9, method = c("cross_entropy", "splitting"), ... )
sim_fn |
A StochSimR simulation function. |
indicator |
Indicator function for the rare event. Receives the values
matrix and returns a 0/1 numeric vector of length |
score |
Continuous scoring function used for adaptive thresholding. Higher scores indicate proximity to the rare event. Receives the values matrix and returns a numeric vector. Required for both methods. |
n_paths |
Positive integer. Paths per iteration. |
n_iter |
Positive integer. Number of adaptive iterations. |
quantile_level |
Numeric in (0, 1). Quantile for threshold selection in each iteration (default 0.9). |
method |
Character. |
... |
Additional arguments to |
The cross-entropy method iteratively updates a drift parameter to
maximise the likelihood of the rare event among elite samples (those
exceeding the quantile_level quantile of the score function).
Multilevel splitting maintains a population of particles, discarding those below a threshold and resampling (branching) from survivors. The probability is estimated as the product of survival fractions across levels.
A list with components:
Numeric. Estimated rare-event probability.
Numeric. Standard error (cross-entropy only).
Numeric vector of length 2. 95\ (cross-entropy only).
Numeric. Log-10 of the estimated probability.
List. Per-iteration diagnostic information.
Character. Method used.
Integer. Total paths simulated.
Rubinstein, R. Y. & Kroese, D. P. (2004). The Cross-Entropy Method. Springer.
Cerou, F. & Guyader, A. (2007). Adaptive multilevel splitting for rare event analysis. Stochastic Analysis and Applications, 25(2), 417–443.
# Estimate P(S_T > 200) for GBM indicator_fn <- function(vals) as.numeric(vals[nrow(vals), ] > 200) score_fn <- function(vals) vals[nrow(vals), ] result <- mc_rare_event(sim_gbm, indicator = indicator_fn, score = score_fn, n_paths = 5000, n_iter = 5, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("P(S_T > 200):", result$probability, "\n")# Estimate P(S_T > 200) for GBM indicator_fn <- function(vals) as.numeric(vals[nrow(vals), ] > 200) score_fn <- function(vals) vals[nrow(vals), ] result <- mc_rare_event(sim_gbm, indicator = indicator_fn, score = score_fn, n_paths = 5000, n_iter = 5, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("P(S_T > 200):", result$probability, "\n")
Constructor for the core path object returned by all simulators in StochSimR. Users rarely need to call this directly.
new_stoch_path(times, values, process, method, params = list())new_stoch_path(times, values, process, method, params = list())
times |
Numeric vector of time points (length |
values |
Numeric vector or matrix of path values. If a vector, it is
treated as a single path. If a matrix, each column represents one sample
path and must have |
process |
Character string naming the stochastic process (e.g.,
|
method |
Character string naming the simulation algorithm (e.g.,
|
params |
Named list of process parameters used in the simulation. |
An S3 object of class "stoch_path" with components:
Numeric vector of time points.
Numeric matrix of path values (rows = time, cols = paths).
Character string naming the process.
Character string naming the simulation method.
Named list of parameters.
Integer, number of sample paths.
Integer, number of time points.
sp <- new_stoch_path( times = seq(0, 1, length.out = 11), values = cumsum(rnorm(11)), process = "Custom Process", method = "manual" ) spsp <- new_stoch_path( times = seq(0, 1, length.out = 11), values = cumsum(rnorm(11)), process = "Custom Process", method = "manual" ) sp
Computes comprehensive summary statistics across all simulated paths, including terminal value distribution, extremes, and increment properties.
path_summary(x)path_summary(x)
x |
A |
A data frame with two columns: statistic (character) and
value (numeric). Statistics include number of paths and steps,
terminal value moments and quantiles, path extremes, and increment
statistics.
paths <- sim_brownian(T_max = 1, n_steps = 500, n_paths = 1000) path_summary(paths)paths <- sim_brownian(T_max = 1, n_steps = 500, n_paths = 1000) path_summary(paths)
Displays the sample autocorrelation function (ACF) of path increments, useful for verifying independence structure or detecting serial dependence.
plot_acf_paths(x, path_idx = 1L, lag.max = 40L, title = NULL)plot_acf_paths(x, path_idx = 1L, lag.max = 40L, title = NULL)
x |
A |
path_idx |
Positive integer. Which path to compute ACF for (default 1). |
lag.max |
Positive integer. Maximum lag to display. |
title |
Character or |
A ggplot object.
paths <- sim_ou(T_max = 10, n_steps = 1000, theta = 2, mu = 0, sigma = 1, x0 = 5, n_paths = 1) plot_acf_paths(paths)paths <- sim_ou(T_max = 10, n_steps = 1000, theta = 2, mu = 0, sigma = 1, x0 = 5, n_paths = 1) plot_acf_paths(paths)
Histogram with kernel density overlay of the terminal values of simulated paths.
plot_distribution(x, bins = 50L, title = NULL)plot_distribution(x, bins = 50L, title = NULL)
x |
A |
bins |
Positive integer. Number of histogram bins. |
title |
Character or |
A ggplot object.
paths <- sim_gbm(T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.3, x0 = 100, n_paths = 5000) plot_distribution(paths)paths <- sim_gbm(T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.3, x0 = 100, n_paths = 5000) plot_distribution(paths)
Creates a ggplot2 visualisation of simulated sample paths with optional sample mean overlay and pointwise confidence bands.
plot_paths( x, max_paths = 100L, show_mean = TRUE, show_bands = TRUE, alpha_line = 0.3, title = NULL )plot_paths( x, max_paths = 100L, show_mean = TRUE, show_bands = TRUE, alpha_line = 0.3, title = NULL )
x |
A |
max_paths |
Positive integer. Maximum paths to plot (subsampled
randomly if |
show_mean |
Logical. If |
show_bands |
Logical. If |
alpha_line |
Numeric in (0, 1]. Transparency for individual paths. |
title |
Character or |
A ggplot object.
paths <- sim_brownian(T_max = 1, n_steps = 500, n_paths = 100) plot_paths(paths, max_paths = 50, show_mean = TRUE, show_bands = TRUE)paths <- sim_brownian(T_max = 1, n_steps = 500, n_paths = 100) plot_paths(paths, max_paths = 50, show_mean = TRUE, show_bands = TRUE)
Generates sample paths of standard or drifted Brownian motion (Wiener process).
sim_brownian( T_max = 1, n_steps = 1000L, mu = 0, sigma = 1, x0 = 0, n_paths = 1L, method = c("exact", "bridge") )sim_brownian( T_max = 1, n_steps = 1000L, mu = 0, sigma = 1, x0 = 0, n_paths = 1L, method = c("exact", "bridge") )
T_max |
Positive numeric. End time. |
n_steps |
Positive integer. Number of time steps. |
mu |
Numeric. Drift coefficient (default 0). |
sigma |
Positive numeric. Volatility / diffusion coefficient (default 1). |
x0 |
Numeric. Starting value (default 0). |
n_paths |
Positive integer. Number of independent paths. |
method |
Character. |
With method "exact", increments are drawn as
.
With method "bridge", a coarse skeleton is first simulated exactly,
then intermediate points are filled using the Brownian bridge conditional
distribution.
A new_stoch_path object.
paths <- sim_brownian(T_max = 1, n_steps = 1000, n_paths = 50) plot_paths(paths, show_mean = TRUE, show_bands = TRUE) # Drifted Brownian motion paths_drift <- sim_brownian(T_max = 2, n_steps = 500, mu = 1, sigma = 0.5, n_paths = 30) plot_paths(paths_drift)paths <- sim_brownian(T_max = 1, n_steps = 1000, n_paths = 50) plot_paths(paths, show_mean = TRUE, show_bands = TRUE) # Drifted Brownian motion paths_drift <- sim_brownian(T_max = 2, n_steps = 500, mu = 1, sigma = 0.5, n_paths = 30) plot_paths(paths_drift)
Simulates paths of the geometric Brownian motion (GBM, Black–Scholes model). The exact method uses the log-normal distribution; the Euler method uses Euler–Maruyama discretisation.
sim_gbm( T_max = 1, n_steps = 252L, mu = 0.05, sigma = 0.2, x0 = 100, n_paths = 1L, method = c("exact", "euler") )sim_gbm( T_max = 1, n_steps = 252L, mu = 0.05, sigma = 0.2, x0 = 100, n_paths = 1L, method = c("exact", "euler") )
T_max |
Positive numeric. End time. |
n_steps |
Positive integer. Number of steps. |
mu |
Numeric. Drift rate. |
sigma |
Positive numeric. Volatility. |
x0 |
Positive numeric. Initial value (default 100). |
n_paths |
Positive integer. Number of paths. |
method |
Character. |
The SDE is . With method
"exact", the solution
is used directly.
A new_stoch_path object with positive values.
paths <- sim_gbm(T_max = 1, n_steps = 252, mu = 0.08, sigma = 0.25, x0 = 100, n_paths = 50) plot_paths(paths) plot_distribution(paths)paths <- sim_gbm(T_max = 1, n_steps = 252, mu = 0.08, sigma = 0.25, x0 = 100, n_paths = 50) plot_paths(paths) plot_distribution(paths)
Simulates a univariate Hawkes process with exponential kernel
using Ogata's modified thinning algorithm.
sim_hawkes(T_max = 10, mu = 0.5, alpha = 0.8, beta = 1, n_paths = 1L)sim_hawkes(T_max = 10, mu = 0.5, alpha = 0.8, beta = 1, n_paths = 1L)
T_max |
Positive numeric. End time. |
mu |
Positive numeric. Baseline intensity. |
alpha |
Positive numeric. Excitation magnitude. |
beta |
Positive numeric. Exponential decay rate. The process is
stationary when |
n_paths |
Positive integer. Number of independent paths. |
The conditional intensity is
Simulation uses Ogata's thinning with an adaptive upper bound that is updated after each event.
A new_stoch_path object (counting process on a
regular grid).
Ogata, Y. (1981). On Lewis' simulation method for point processes. IEEE Transactions on Information Theory, 27(1), 23–31.
Hawkes, A. G. (1971). Spectra of some self-exciting and mutually exciting point processes. Biometrika, 58(1), 83–90.
paths <- sim_hawkes(T_max = 50, mu = 0.5, alpha = 0.8, beta = 1.2, n_paths = 10) plot_paths(paths)paths <- sim_hawkes(T_max = 50, mu = 0.5, alpha = 0.8, beta = 1.2, n_paths = 10) plot_paths(paths)
Simulates paths from the Merton (1976) jump-diffusion model, which combines geometric Brownian motion with compound Poisson jumps in log-price.
sim_jump_diffusion( T_max = 1, n_steps = 1000L, mu = 0.05, sigma = 0.2, lambda = 1, mu_j = 0, sigma_j = 0.1, x0 = 1, n_paths = 1L, log_scale = FALSE )sim_jump_diffusion( T_max = 1, n_steps = 1000L, mu = 0.05, sigma = 0.2, lambda = 1, mu_j = 0, sigma_j = 0.1, x0 = 1, n_paths = 1L, log_scale = FALSE )
T_max |
Positive numeric. End time. |
n_steps |
Positive integer. Number of time steps. |
mu |
Numeric. Drift of the diffusion component. |
sigma |
Positive numeric. Volatility of the diffusion component. |
lambda |
Non-negative numeric. Jump intensity (mean jumps per unit time). |
mu_j |
Numeric. Mean of the log-jump size distribution. |
sigma_j |
Positive numeric. Standard deviation of the log-jump size distribution. |
x0 |
Positive numeric. Initial value (default 1). |
n_paths |
Positive integer. Number of paths. |
log_scale |
Logical. If |
The log-price dynamics are
where is a Poisson process with rate , jump sizes
, and
is the compensator.
A new_stoch_path object. Values are prices (or
log-prices if log_scale = TRUE).
Merton, R. C. (1976). Option pricing when underlying stock returns are discontinuous. Journal of Financial Economics, 3(1-2), 125–144.
paths <- sim_jump_diffusion( T_max = 1, n_steps = 1000, mu = 0.05, sigma = 0.2, lambda = 3, mu_j = -0.02, sigma_j = 0.1, n_paths = 30 ) plot_paths(paths)paths <- sim_jump_diffusion( T_max = 1, n_steps = 1000, mu = 0.05, sigma = 0.2, lambda = 3, mu_j = -0.02, sigma_j = 0.1, n_paths = 30 ) plot_paths(paths)
Simulates sample paths from a Levy process. Four families are supported: alpha-stable, gamma subordinator, normal inverse Gaussian (NIG), and variance-gamma.
sim_levy( T_max = 1, n_steps = 500L, type = c("stable", "gamma", "nig", "variance_gamma"), alpha = 1.5, beta = 0, shape = 1, rate = 1, theta = 0, sigma = 1, nu = 0.5, n_paths = 1L )sim_levy( T_max = 1, n_steps = 500L, type = c("stable", "gamma", "nig", "variance_gamma"), alpha = 1.5, beta = 0, shape = 1, rate = 1, theta = 0, sigma = 1, nu = 0.5, n_paths = 1L )
T_max |
Positive numeric. End time. |
n_steps |
Positive integer. Number of time steps. |
type |
Character. One of |
alpha |
Numeric in |
beta |
Numeric in |
shape |
Positive numeric. Shape parameter for |
rate |
Positive numeric. Rate parameter for |
theta |
Numeric. Drift for |
sigma |
Positive numeric. Volatility for |
nu |
Positive numeric. Variance rate for |
n_paths |
Positive integer. Number of paths. |
"stable"Uses the Chambers–Mallows–Stuck algorithm to generate alpha-stable increments.
"gamma"Gamma subordinator with shape shape * dt and
rate rate per increment.
"nig"Normal inverse Gaussian: Brownian motion subordinated by an inverse Gaussian process.
"variance_gamma"Brownian motion subordinated by a gamma
process with drift theta.
A new_stoch_path object.
Chambers, J. M., Mallows, C. L. & Stuck, B. W. (1976). A method for simulating stable random variables. Journal of the American Statistical Association, 71(354), 340–344.
# Gamma subordinator (non-decreasing) paths <- sim_levy(T_max = 5, n_steps = 500, type = "gamma", shape = 2, rate = 1, n_paths = 20) plot_paths(paths) # Variance-Gamma paths_vg <- sim_levy(T_max = 1, n_steps = 500, type = "variance_gamma", theta = -0.1, sigma = 0.3, nu = 0.5, n_paths = 15) plot_paths(paths_vg)# Gamma subordinator (non-decreasing) paths <- sim_levy(T_max = 5, n_steps = 500, type = "gamma", shape = 2, rate = 1, n_paths = 20) plot_paths(paths) # Variance-Gamma paths_vg <- sim_levy(T_max = 1, n_steps = 500, type = "variance_gamma", theta = -0.1, sigma = 0.3, nu = 0.5, n_paths = 15) plot_paths(paths_vg)
Simulates sample paths from a discrete-time Markov chain with a given transition probability matrix.
sim_markov(P, n_steps = 100L, x0 = NULL, n_paths = 1L, states = NULL)sim_markov(P, n_steps = 100L, x0 = NULL, n_paths = 1L, states = NULL)
P |
Numeric matrix. Transition probability matrix where |
n_steps |
Positive integer. Number of transitions. |
x0 |
Integer. Initial state (1-indexed). If |
n_paths |
Positive integer. Number of independent chains. |
states |
Optional character vector of state names (length must equal
|
At each step the next state is sampled from the categorical distribution
defined by the current row of P, using inverse-CDF sampling on
precomputed cumulative row probabilities.
A new_stoch_path object with integer-valued paths.
# Simple 3-state chain P <- matrix(c(0.7, 0.2, 0.1, 0.3, 0.4, 0.3, 0.2, 0.3, 0.5), nrow = 3, byrow = TRUE) paths <- sim_markov(P, n_steps = 200, n_paths = 10) plot_paths(paths) # Check convergence to stationary distribution long_chain <- sim_markov(P, n_steps = 10000, x0 = 1, n_paths = 1) table(long_chain$values) / length(long_chain$values)# Simple 3-state chain P <- matrix(c(0.7, 0.2, 0.1, 0.3, 0.4, 0.3, 0.2, 0.3, 0.5), nrow = 3, byrow = TRUE) paths <- sim_markov(P, n_steps = 200, n_paths = 10) plot_paths(paths) # Check convergence to stationary distribution long_chain <- sim_markov(P, n_steps = 10000, x0 = 1, n_paths = 1) table(long_chain$values) / length(long_chain$values)
Simulates paths from a mean-reverting Ornstein–Uhlenbeck (OU) diffusion
.
sim_ou( T_max = 10, n_steps = 1000L, theta = 1, mu = 0, sigma = 1, x0 = 0, n_paths = 1L, method = c("exact", "euler") )sim_ou( T_max = 10, n_steps = 1000L, theta = 1, mu = 0, sigma = 1, x0 = 0, n_paths = 1L, method = c("exact", "euler") )
T_max |
Positive numeric. End time. |
n_steps |
Positive integer. Number of steps. |
theta |
Positive numeric. Speed of mean reversion. |
mu |
Numeric. Long-run mean level. |
sigma |
Positive numeric. Volatility. |
x0 |
Numeric. Initial value. |
n_paths |
Positive integer. Number of paths. |
method |
Character. |
With method "exact", the conditional distribution
is Gaussian with known mean and variance,
yielding an exact (discretisation-error-free) simulation. The Euler
method introduces weak error.
A new_stoch_path object.
paths <- sim_ou(T_max = 10, n_steps = 1000, theta = 2, mu = 5, sigma = 0.5, x0 = 0, n_paths = 30) plot_paths(paths, show_mean = TRUE, show_bands = TRUE)paths <- sim_ou(T_max = 10, n_steps = 1000, theta = 2, mu = 5, sigma = 0.5, x0 = 0, n_paths = 30) plot_paths(paths, show_mean = TRUE, show_bands = TRUE)
Distributes path simulation across multiple cores using the future framework for cross-platform parallelism.
sim_parallel( sim_fn, n_paths = 1000L, n_workers = NULL, chunk_size = NULL, seed = 42L, ... )sim_parallel( sim_fn, n_paths = 1000L, n_workers = NULL, chunk_size = NULL, seed = 42L, ... )
sim_fn |
Any StochSimR simulation function. |
n_paths |
Positive integer. Total number of paths to simulate. |
n_workers |
Positive integer. Number of parallel workers. Default
|
chunk_size |
Positive integer. Number of paths per chunk. Default
|
seed |
Integer. Base random seed for reproducibility. Worker |
... |
Additional arguments passed to |
The function temporarily sets future::plan(multisession) for
parallel execution and restores the previous plan on exit. Each chunk
is simulated independently with a deterministic seed derived from
seed.
A new_stoch_path object combining all paths.
paths <- sim_parallel(sim_gbm, n_paths = 1000, n_workers = 2, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) plot_paths(paths)paths <- sim_parallel(sim_gbm, n_paths = 1000, n_workers = 2, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) plot_paths(paths)
Generates sample paths of a homogeneous or inhomogeneous Poisson process. Homogeneous processes use exact inter-arrival time simulation; inhomogeneous processes use the Lewis–Shedler thinning algorithm.
sim_poisson( T_max = 1, lambda = 1, lambda_max = NULL, n_paths = 1L, method = c("auto", "exact", "thinning") )sim_poisson( T_max = 1, lambda = 1, lambda_max = NULL, n_paths = 1L, method = c("auto", "exact", "thinning") )
T_max |
Positive numeric. End time of the simulation. |
lambda |
Rate parameter. Either a single positive number (homogeneous
case) or a function of time |
lambda_max |
Positive numeric. Upper bound on |
n_paths |
Positive integer. Number of independent paths to simulate. |
method |
Character string. One of |
For the homogeneous case with rate , inter-arrival times
are i.i.d. .
For the inhomogeneous case with rate function , the
Lewis–Shedler thinning algorithm generates candidates at rate
lambda_max and accepts each with probability
.
A new_stoch_path object containing the counting
process evaluated on a regular time grid.
Lewis, P. A. W. & Shedler, G. S. (1979). Simulation of nonhomogeneous Poisson processes by thinning. Naval Research Logistics Quarterly, 26(3), 403–413.
# Homogeneous Poisson with rate 5 paths <- sim_poisson(T_max = 10, lambda = 5, n_paths = 20) plot_paths(paths) # Inhomogeneous Poisson with sinusoidal rate paths_ih <- sim_poisson( T_max = 10, lambda = function(t) 3 + 2 * sin(2 * pi * t / 5), lambda_max = 5, n_paths = 10 ) plot_paths(paths_ih)# Homogeneous Poisson with rate 5 paths <- sim_poisson(T_max = 10, lambda = 5, n_paths = 20) plot_paths(paths) # Inhomogeneous Poisson with sinusoidal rate paths_ih <- sim_poisson( T_max = 10, lambda = function(t) 3 + 2 * sin(2 * pi * t / 5), lambda_max = 5, n_paths = 10 ) plot_paths(paths_ih)
Reduces variance by pairing each simulation with its "mirror" simulation constructed from negated uniform random numbers. This induces negative correlation between the pair, lowering the variance of the average.
vr_antithetic(sim_fn, h = NULL, n_paths = 1000L, ...)vr_antithetic(sim_fn, h = NULL, n_paths = 1000L, ...)
sim_fn |
A StochSimR simulation function (e.g., |
h |
Function applied to the path values matrix, returning a numeric
vector of length |
n_paths |
Positive integer. Number of antithetic pairs. The total
number of function evaluations is |
... |
Additional arguments passed to |
The implementation works by simulating n_paths paths with a fixed
random seed, then re-simulating with the same seed. For GBM and other
processes driven by Brownian motion, the antithetic path is constructed
by reflecting the log-returns around the drift, which is equivalent to
negating the Brownian increments.
A list with components:
Numeric. Antithetic estimator of .
Numeric. Standard error of the antithetic estimator.
Numeric vector of length 2. 95% confidence interval.
Numeric. Crude Monte Carlo estimate (no VR).
Numeric. Standard error of the crude estimator.
Numeric. Variance reduction ratio (crude variance / antithetic variance).
Character. "antithetic_variates".
Integer. Total samples used.
Glasserman, P. (2003). Monte Carlo Methods in Financial Engineering. Springer. Chapter 4.
h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) result <- vr_antithetic(sim_gbm, h = h_call, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " SE:", result$se, " Reduction:", round(result$reduction_factor, 2), "x\n")h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) result <- vr_antithetic(sim_gbm, h = h_call, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " SE:", result$se, " Reduction:", round(result$reduction_factor, 2), "x\n")
Uses a correlated control variate with known expectation to reduce the variance of a Monte Carlo estimator.
vr_control_variate(sim_fn, h, g, E_g, n_paths = 1000L, ...)vr_control_variate(sim_fn, h, g, E_g, n_paths = 1000L, ...)
sim_fn |
A StochSimR simulation function. |
h |
Target function applied to path values matrix. Returns a numeric
vector of length |
g |
Control variate function applied to path values matrix. Returns a
numeric vector of length |
E_g |
Numeric. Known expectation of |
n_paths |
Positive integer. Number of paths. |
... |
Additional arguments to |
The control variate estimator is
where is the optimal
coefficient. The theoretical variance reduction factor is
.
A list with components:
Numeric. Control variate estimator.
Numeric. Standard error.
Numeric vector of length 2. 95% confidence interval.
Numeric. Optimal control coefficient.
Numeric. Correlation between h and g.
Numeric. Crude MC estimate.
Numeric. Crude MC standard error.
Numeric. Variance reduction ratio.
Character. "control_variate".
Integer. Total samples used.
Glasserman, P. (2003). Monte Carlo Methods in Financial Engineering. Springer. Section 4.1.
# Price European call; control = terminal stock price h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) g_term <- function(vals) vals[nrow(vals), ] E_g_val <- 100 * exp(0.05) result <- vr_control_variate(sim_gbm, h = h_call, g = g_term, E_g = E_g_val, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " Reduction:", round(result$reduction_factor, 2), "x\n")# Price European call; control = terminal stock price h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) g_term <- function(vals) vals[nrow(vals), ] E_g_val <- 100 * exp(0.05) result <- vr_control_variate(sim_gbm, h = h_call, g = g_term, E_g = E_g_val, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " Reduction:", round(result$reduction_factor, 2), "x\n")
Tilts the simulation measure via an exponential change of drift and reweights using the Girsanov likelihood ratio. Particularly useful for rare-event estimation.
vr_importance(sim_fn, h, drift_shift = 0.5, n_paths = 1000L, ...)vr_importance(sim_fn, h, drift_shift = 0.5, n_paths = 1000L, ...)
sim_fn |
A StochSimR simulation function for a process driven by
Brownian motion (e.g., |
h |
Target function applied to path values. Returns a numeric vector. |
drift_shift |
Numeric. Additive shift to the drift parameter
|
n_paths |
Positive integer. Number of paths. |
... |
Additional arguments to |
Under the tilted measure with drift , the
Girsanov likelihood ratio for GBM is
where is the terminal Brownian motion value recovered from the
simulated path.
A list with components:
Numeric. Importance sampling estimator.
Numeric. Standard error.
Numeric vector of length 2. 95% confidence interval.
Numeric. Effective sample size.
Numeric. Crude MC estimate (separate simulation).
Numeric. Crude MC standard error.
Numeric. Variance reduction ratio.
Character. "importance_sampling".
Numeric. The applied drift shift.
Integer. Total samples used.
Glasserman, P. (2003). Monte Carlo Methods in Financial Engineering. Springer. Chapter 4.6.
# Estimate P(S_T > 150) with upward drift tilt h_tail <- function(vals) as.numeric(vals[nrow(vals), ] > 150) result <- vr_importance(sim_gbm, h = h_tail, drift_shift = 0.4, n_paths = 10000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("P(S_T > 150):", result$estimate, " ESS:", round(result$ess), "\n")# Estimate P(S_T > 150) with upward drift tilt h_tail <- function(vals) as.numeric(vals[nrow(vals), ] > 150) result <- vr_importance(sim_gbm, h = h_tail, drift_shift = 0.4, n_paths = 10000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("P(S_T > 150):", result$estimate, " ESS:", round(result$ess), "\n")
Partitions the probability space into strata and allocates samples proportionally, reducing variance by ensuring balanced coverage.
vr_stratified(sim_fn, h, n_strata = 10L, n_paths = 1000L, ...)vr_stratified(sim_fn, h, n_strata = 10L, n_paths = 1000L, ...)
sim_fn |
A StochSimR simulation function. |
h |
Target function applied to path values. Returns a numeric vector. |
n_strata |
Positive integer. Number of strata. |
n_paths |
Positive integer. Total number of paths. |
... |
Additional arguments to |
The stratification is performed by running independent batches (one per stratum) and averaging their means. This is a simple form of stratified sampling that reduces variance when the target function has different behaviour across the strata.
A list with components:
Numeric. Stratified estimator.
Numeric. Standard error.
Numeric vector of length 2. 95% confidence interval.
Numeric vector. Per-stratum means.
Numeric vector. Per-stratum variances.
Numeric. Crude MC estimate.
Numeric. Crude MC standard error.
Numeric. Variance reduction ratio.
Character. "stratified_sampling".
Integer. Number of strata used.
Integer. Total samples used.
Glasserman, P. (2003). Monte Carlo Methods in Financial Engineering. Springer. Section 4.3.
h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) result <- vr_stratified(sim_gbm, h = h_call, n_strata = 10, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " SE:", result$se, "\n")h_call <- function(vals) pmax(vals[nrow(vals), ] - 100, 0) result <- vr_stratified(sim_gbm, h = h_call, n_strata = 10, n_paths = 5000, T_max = 1, n_steps = 252, mu = 0.05, sigma = 0.2, x0 = 100) cat("Estimate:", result$estimate, " SE:", result$se, "\n")