Skip to content

rust-dd/stochastic-rs

Repository files navigation

Build Workflow Crates.io License codecov FOSSA Status

stochastic-rs

A high-performance Rust library for simulating stochastic processes, with first-class bindings. Built for quantitative finance, statistical modeling and synthetic data generation.

Features

  • 85+ stochastic models - 31 diffusions (OU, CIR, GBM, CEV, CKLS, Aït-Sahalia, Pearson, Jacobi, regime-switching, ...), 15 jump processes (Merton, Kou, CGMY, bilateral gamma, ...), 9 stochastic volatility models (Heston, SABR, Bergomi, rough Bergomi, HKDE, ...), 13 interest rate models (Hull-White, HJM, Vasicek, ...), and base processes (fBM, Poisson, LFSM, ...)
  • MLE engine - maximum likelihood estimation for 1-D diffusion models with 6 transition density approximations (Euler, Ozaki, Shoji-Ozaki, Elerian, Kessler, Aït-Sahalia), L-BFGS optimizer via argmin, and 22 built-in process implementations
  • Quant toolbox - option pricing (Fourier, barrier, lookback, Asian, variance swaps, regime-switching), calibration (Heston, SABR, Lévy, SVJ, rough Bergomi), and finite-difference methods
  • Copulas - bivariate, multivariate, and empirical copulas with correlation utilities
  • Statistics - kernel density estimation, fractional OU estimation, and CIR parameter fitting
  • SIMD-optimized - fractional Gaussian noise, fractional Brownian motion, and all probability distributions use wide SIMD for fast sample generation
  • Parallel sampling - sample_par(m) generates m independent paths in parallel via rayon
  • Generic precision - most models support both f32 and f64
  • Python bindings - full stochastic model coverage with numpy integration; all models return numpy arrays (others coming soon)

Installation

Rust

[dependencies]
stochastic-rs = "1.5.0"

Bindings

pip install stochastic-rs

For development builds from source (requires maturin):

pip install maturin
maturin develop --release

OpenBLAS (required for openblas feature)

The openblas feature enables ndarray-linalg for linear algebra operations. It requires a system OpenBLAS installation with LAPACK support.

Linux (Debian/Ubuntu)

sudo apt install libopenblas-dev

Linux (Fedora/RHEL)

sudo dnf install openblas-devel

macOS

brew install openblas
export OPENBLAS_DIR=$(brew --prefix openblas)

Windows

Download prebuilt OpenBLAS from OpenMathLib/OpenBLAS releases (pick the x64.zip), extract it, and install vcpkg:

git clone https://github.com/microsoft/vcpkg C:\vcpkg
C:\vcpkg\bootstrap-vcpkg.bat
$env:VCPKG_ROOT = "C:\vcpkg"

Then copy the prebuilt libopenblas.lib and libopenblas.dll into $VCPKG_ROOT\installed\x64-windows\lib\ and $VCPKG_ROOT\installed\x64-windows\bin\ respectively. The prebuilt release includes LAPACK (the vcpkg openblas port does not).

Build with OpenBLAS

cargo build --features openblas

CUDA native (optional)

Requires NVIDIA CUDA Toolkit (12.x+) and a compatible GPU.

cargo build --features cuda-native

Usage

Rust

use stochastic_rs::stochastic::process::fbm::FBM;
use stochastic_rs::stochastic::volatility::heston::Heston;
use stochastic_rs::stochastic::volatility::HestonPow;
use stochastic_rs::traits::ProcessExt;

fn main() {
    // Fractional Brownian Motion
    let fbm = FBM::new(0.7, 1000, None);
    let path = fbm.sample();

    // Parallel batch sampling
    let paths = fbm.sample_par(1000);

    // Heston stochastic volatility
    let heston = Heston::new(
        Some(100.0),   // s0
        Some(0.04),    // v0
        2.0,           // kappa
        0.04,          // theta
        0.3,           // sigma
        -0.7,          // rho
        0.05,          // mu
        1000,          // n
        None,          // t
        HestonPow::Sqrt,
        Some(false),
    );
    let [price, variance] = heston.sample();
}

Bindings

All models return numpy arrays. Use dtype="f32" or dtype="f64" (default) to control precision.

import stochastic_rs as sr

# Basic processes
fbm = sr.PyFBM(0.7, 1000)
path = fbm.sample()           # shape (1000,)
paths = fbm.sample_par(500)   # shape (500, 1000)

# Stochastic volatility
heston = sr.PyHeston(mu=0.05, kappa=2.0, theta=0.04, sigma=0.3, rho=-0.7, n=1000)
price, variance = heston.sample()

# Models with callable parameters
hw = sr.PyHullWhite(theta=lambda t: 0.04 + 0.01*t, alpha=0.1, sigma=0.02, n=1000)
rates = hw.sample()

# Jump processes with custom jump distributions
import numpy as np
merton = sr.PyMerton(
    alpha=0.05, sigma=0.2, lambda_=3.0, theta=0.01,
    distribution=lambda: np.random.normal(0, 0.1),
    n=1000,
)
log_prices = merton.sample()

Benchmarks

FGN CPU vs CUDA native (sample, sample_par, sample_cuda_native)

cuda-native backend: cudarc + cuFFT + fused Philox RNG kernel (no .cu files, no nvcc).

cargo bench --features cuda-native --bench fgn_cuda_native

Environment: NVIDIA GPU, CUDA 12.x, Rust nightly, --release with LTO.

Single path (sample vs sample_cuda_native(1), f32, H=0.7):

n CPU sample CUDA sample_cuda_native(1) Speedup
1,024 8.1 us 46 us 0.18x
4,096 35 us 84 us 0.42x
16,384 147 us 110 us 1.3x
65,536 850 us 227 us 3.7x

Batch (sample_par(m) vs sample_cuda_native(m), f32, H=0.7):

n, m CPU sample_par(m) CUDA sample_cuda_native(m) Speedup
4,096, 32 147 us 117 us 1.3x
4,096, 512 1.78 ms 2.37 ms 0.75x
65,536, 128 12.6 ms 10.5 ms 1.2x
65,536, 1024 102 ms 93 ms 1.1x

CUDA wins for large n (>= 16k) and is competitive at n=65k batches. CPU rayon parallelism dominates for medium n due to zero transfer overhead.

Distribution Sampling (All Built-in Distributions)

Measured with:

cargo bench --bench dist_multicore

Configuration in this run:

  • sample_matrix benchmark
  • 1-thread vs 14-thread rayon pools
  • size is mostly 1024 x 1024; heavy discrete samplers use 512 x 512
Distribution Shape 1T (ms) MT (ms) Speedup
Normal 1024 x 1024 1.78 0.34 5.28x
Exp 1024 x 1024 1.73 0.33 5.25x
Uniform 1024 x 1024 0.65 0.13 5.12x
Cauchy 1024 x 1024 6.23 0.90 6.96x
LogNormal 1024 x 1024 5.07 0.81 6.25x
Gamma 1024 x 1024 5.20 0.72 7.19x
ChiSq 1024 x 1024 5.06 1.22 4.14x
StudentT 1024 x 1024 7.89 1.89 4.18x
Beta 1024 x 1024 11.85 1.68 7.04x
Weibull 1024 x 1024 13.17 1.73 7.59x
Pareto 1024 x 1024 5.48 0.80 6.87x
InvGauss 1024 x 1024 2.52 0.44 5.69x
NIG 1024 x 1024 5.93 0.90 6.62x
AlphaStable 1024 x 1024 42.52 5.36 7.94x
Poisson 1024 x 1024 2.28 0.42 5.40x
Geometric 1024 x 1024 2.75 0.44 6.30x
Binomial 512 x 512 4.43 0.70 6.32x
Hypergeo 512 x 512 20.99 2.76 7.60x

Normal single-thread kernel comparison (fill_slice, same run):

  • vs rand_distr + SimdRng: ~1.21x to 1.35x
  • vs rand_distr + rand::rng(): ~4.09x to 4.61x

Roadmap to v2

Turning stochastic-rs into a comprehensive quantitative finance library — a full QuantLib competitor in Rust.

Items are ordered by dependency: each tier builds on the one above it. Independent modules (stats, factors) can be done in parallel at any time.

Tier 0 — Foundations (no roadmap dependencies, builds on done modules)

  • Cash flow engine (quant::cashflows) ← calendar ✓, curves ✓
    • Fixed-rate coupon, floating-rate coupon (IBOR, OIS), CMS coupon
    • Leg abstraction — ordered sequence of cash flows with notional schedule
    • Amortizing and accreting notionals
    • Cash flow NPV, accrued interest
  • Trinomial tree & lattice framework (quant::lattice)
    • General trinomial / binomial tree
    • Hull-White, Black-Karasinski, G2++ tree engines

Tier 1 — Instruments (depends on: cash flow engine)

  • Interest rate swaps (quant::instruments) ← cashflows, curves ✓
    • Vanilla IRS (fixed vs floating)
    • Overnight Indexed Swap (OIS)
    • Basis swap and cross-currency basis swap
    • NPV, fair rate, DV01 / BPV
  • Fixed-income instruments (quant::instruments) ← cashflows, curves ✓
    • Fixed-rate bond — dirty/clean price, YTM, duration (Macaulay, modified), convexity
    • Floating-rate bond / FRN
    • Zero-coupon bond pricing from yield curve
    • Amortizing bond, inflation-linked bond
    • Z-spread, ASW spread, OAS

Tier 2 — Advanced instruments & framework (depends on: Tier 1)

  • Caps, floors & swaptions (quant::instruments) ← IRS, lattice
    • Cap / Floor / Collar pricing (Black, Bachelier, SABR)
    • European and Bermudan swaptions
    • Hull-White / G2++ tree-based engines
    • Short-rate model calibration to swaption / cap vols
  • Market data framework (quant::market) ← IRS, fixed-income (rate helpers)
    • Quote / Handle / Observable abstraction for reactive repricing
    • Rate index objects (SOFR, EURIBOR, TONAR) with fixing history
    • FRA and money market instrument helpers
    • Rate helpers for curve bootstrapping
  • Credit models (quant::credit) ← fixed-income (CDS cash flows)
    • Merton structural model
    • Reduced-form / intensity-based models
    • CDS pricing (ISDA standard) and hazard rate bootstrapping
    • Default probability term structure
    • Credit migration matrices
  • Risk metrics (quant::risk) ← instruments (Greeks, bucket DV01)
    • Value at Risk — parametric, historical simulation, Monte Carlo
    • CVaR / Expected Shortfall
    • Stress testing and scenario analysis framework
    • Drawdown metrics, Sharpe, Sortino, Information Ratio, Calmar
    • Instrument-level Greeks — bump-and-reprice, bucket DV01, scenario engine

Tier 3 — Complex products (depends on: Tier 2)

  • Exotic derivatives (quant::pricing) ← lattice, pricing ✓, optionally swaptions
    • Bermudan options (LSM and PDE)
    • Basket and rainbow options
    • Cliquet / ratchet options
    • Auto-callable structures
    • Digital / binary options (cash-or-nothing, asset-or-nothing)
    • Chooser, compound, spread options
  • Inflation (quant::inflation) ← fixed-income, cashflows
    • Zero-coupon and year-on-year inflation term structures
    • CPI / RPI / HICP index objects
    • Inflation-linked swaps and bonds

Independent — Stats & quant modules (no tier dependencies)

  • Realized volatility & microstructure noise (stats::realized)
    • Realized variance, bipower variation, kernel-based RV
    • Realized semivariance, realized skewness and kurtosis
    • HAR (Heterogeneous Autoregressive) model
    • Noise-robust estimators — pre-averaging, two-scale RV
  • Econometrics (stats::econometrics)
    • Cointegration — Johansen test, Engle-Granger two-step
    • Granger causality
    • Hidden Markov Models for regime detection
    • Changepoint detection
  • Bayesian inference & filtering (stats::filtering)
    • Particle filters for general state-space models
    • Unscented Kalman Filter
    • MCMC samplers (Metropolis-Hastings, HMC) for calibration
  • Factor models & statistical arbitrage (quant::factors)
    • PCA-based factor models
    • Cross-sectional regression (Fama-MacBeth)
    • Covariance shrinkage (Ledoit-Wolf)
    • Pairs trading / stat arb framework
  • Market microstructure (quant::microstructure) ← order_book ✓, hawkes ✓
    • Almgren-Chriss optimal execution
    • Market impact models (Kyle, transient impact)
    • Bid-ask spread models

Quality improvements (pre-v2 hardening)

These should be addressed before or alongside Tier 0 work to ensure new modules build on a solid foundation.

  • Stability: replace .unwrap() in core pricingbsm.rs (40+), sabr.rs, heston.rs panic on None tau / optional fields. Switch to Result or validated builder pattern.
  • Missing derives on public typesOrderBook (no Debug/Clone), BSMPricer, BSMPricerBuilder lack standard derives. All public structs need Debug, Clone; enums need Display.
  • Vec<Vec<f64>>Array2<T>portfolio/data.rs, portfolio/momentum.rs, calibration/rbergomi.rs, pricing/dupire.rs, pricing/breeden_litzenberger.rs use nested Vec for numerical data instead of ndarray.
  • Mixed linalg librariescalibration.rs uses nalgebra::DVector while the rest of the codebase uses ndarray. Consolidate to ndarray.
  • Hardcoded day count constantssabr_smile.rs (/365.0), fmvol_regime.rs (/252.0), variance_swap.rs (/252.0). Use DayCountConvention or accept as parameter.
  • Global #![allow(dead_code)]lib.rs suppresses all dead code warnings. Remove and audit.
  • Test coverage gapscalendar/*, bonds/*, curves/*, fx/*, interest/* have zero tests. Add comparison tests against QuantLib / reference implementations.
  • Module documentationcurves/*, bonds/*, calendar/holiday.rs, pricing/dupire.rs and others missing //! doc headers and paper citations.
  • Re-export consistencybonds.rs has no re-exports; stochastic.rs only re-exports traits. Match the pricing.rs / calibration.rs pattern everywhere.
  • Naming conventionsXxxConfig vs XxxParams vs XxxCalibrationConfig; inconsistent abbreviation style (cir_2f vs duffie_kan). Standardize.

Done

  • Advanced Monte Carlo (stochastic::mc)
    • Variance reduction — antithetic variates, control variates, importance sampling, stratified sampling
    • Quasi-Monte Carlo sequences — Sobol, Halton
    • Multi-Level Monte Carlo (MLMC)
    • Longstaff-Schwartz (LSM) for American option pricing
  • Volatility surface (quant::vol_surface)
    • Implied volatility surface construction from market data
    • SVI parameterization (Gatheral) and SSVI
    • Arbitrage-free interpolation and extrapolation
    • Smile and skew analytics
  • Calendar & day count (quant::calendar)
    • Day count conventions — ACT/360, ACT/365, 30/360, ACT/ACT
    • Business day adjustment rules — Following, Modified Following, Preceding
    • Holiday calendars — US, UK, TARGET, Tokyo
    • Schedule generation for coupon and payment dates
  • FX & currencies (quant::fx)
    • ISO 4217 currency definitions and metadata
    • FX quoting and cross-rate conventions
    • FX forward pricing
  • Yield curve construction (quant::curves)
    • Bootstrapping from deposit, FRA, futures, and swap rates
    • Nelson-Siegel / Svensson parameterization
    • Discount factor and forward rate extraction
    • Multi-curve framework (OIS vs SOFR discounting)
    • Interpolation — monotone convex, log-linear, cubic spline
  • Stochastic local volatility (quant::pricing)
    • Heston SLV model — Guyon–Labordère particle calibration of leverage function
    • Combined stochastic + Dupire local vol with mixing factor η

Contributing

Contributions are welcome - bug reports, feature suggestions, or PRs. Open an issue or start a discussion on GitHub.

License

MIT - see LICENSE.

About

stochastic-rs is a Rust library designed for high-performance simulation and analysis of stochastic processes and models in quant finance.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages