stochastic-rs

Migrating to v3

The breaking changes between v2.6 and v3.0 that most programs hit, grouped by area, with the replacement for each.

v3 updates the sampling and pricing APIs without renaming crates. The changes below are the ones most likely to stop a v2.6 program from compiling, in the order you are likely to hit them.

Every process carries its sampling backend as a type parameter

Gbm<T, S> became Gbm<T, S, B = Cpu> on all 130 processes. Thanks to the default, existing constructors and type names keep working; struct literals and generic bounds change.

  • Struct literals name the handle: backend: Cpu where 2.x had backend: std::marker::PhantomData (or build through the constructor).
  • Generic code over a process spells the third parameter: fn f<T, S, B: HostBackend>(p: &Gbm<T, S, B>). HostBackend, FgnBackend, SheetBackend and EulerBackend are the capability traits a bound can name; see GPU support for which process accepts which.
  • Device sampling is .on::<Metal>() (or Cuda, Accelerate) on the process, or with_backend(Cuda::new(1)) with an explicit handle. A configuration the kernels cannot carry samples on the host bit-identically, and device_ready() on ProcessExt says so beforehand.
  • CubeCL is gone. Vulkan and WebGPU targets are no longer served; use Cuda on NVIDIA and Metal on Apple GPUs.
  • Fallible sampling is on the trait: ProcessExt::try_sample() / try_sample_par(m) return Result<_, DeviceError> for every process (always Ok on the host); the inherent try_sample_par of Gbm / Ou / Cir / Fgn moved there, try_sample_matrix stays inherent.

PricerExt is gone; pricers are models

The bundled-market-data trait (calculate_call_put(), calculate_price(), implied_volatility()) is removed. The struct holds model parameters only, and the query travels as arguments through ModelPricer:

// v2.6: HestonPricer::builder(s, v0, k, r, rho, kappa, theta, sigma)
let p = HestonPricer::builder(100.0, 0.04, 100.0, 0.03, -0.7, 2.0, 0.04, 0.5)
    .tau(0.5).build();
let (call, put) = p.calculate_call_put();

// v3: Heston's λ, 0 by default, is with_vol_risk_premium(lambda)
let params = HestonParams { v0: 0.04, kappa: 2.0, theta: 0.04, sigma: 0.5, rho: -0.7 };
let p = HestonPricer::new(params);
let call = p.price_call(100.0, 100.0, 0.03, 0.0, 0.5);
let put  = p.price_put(100.0, 100.0, 0.03, 0.0, 0.5);

calculate_call_put() becomes price_call and price_put, or price_call_put(s, k, r, q, tau), which returns a CallPut { call, put }, on the four pricers whose one computation yields both legs (HestonPricer, Merton1976Pricer, HestonStochCorrPricer, GbmMalliavinPricer); calculate_price() becomes price_call(...). The affected types: HestonPricer, Merton1976Pricer, SabrPricer (absorbs the old SabrModel), HestonStochCorrPricer (absorbs HscmModel), KirkSpreadPricer, FiniteDifferencePricer (and gained a dividend yield in the PDE drift), GbmMalliavinPricer, SnellEnvelopePricer, BjerksundStensland2002Pricer. Their …Builder types are removed with them; implied_volatility, char_func, forward(), sigma() and price_detailed take the (s, k, r, q, tau) query. KirkSpreadPricer has no pricing trait: its methods are spread_call_put (a CallPut) / spread_call / spread_put with the query (f1, f2, x, r, tau). TimeExt leaves the pricers and stays on the two instruments, EuropeanOption and DigitalOption, which hold a Maturity (Tau(years) or Dates { eval, expiry }): tau() returns an f64 and dcc() a DayCountConvention, where both returned an Option, maturity() replaces eval() and expiration(), and tau_or_from_dates() and calculate_tau_in_years() are gone. HestonPricer::greeks(…, OptionType::Put) now differentiates the put, where v2 always differentiated the call.

Calibrators

The vanilla calibrators take their quotes as a Vec<OptionQuote>, and every quant calibrator returns a Calibrated:

// v2.6
let c = HestonCalibrator::new(None, prices.into(), spots.into(), strikes.into(),
    0.03, Some(0.0), 0.5, OptionType::Call, None, None, None, false);
let fit: HestonCalibrationResult = c.calibrate(None)?;
let model = fit.to_model(0.03, 0.0);

// v3: HestonCalibrator::new(s, r, q, quotes); HestonParams lives in pricing::heston
let quotes = strikes.iter().zip(&prices)
    .map(|(&k, &price)| OptionQuote::new(k, 0.5, price, OptionType::Call))
    .collect::<Vec<_>>();
let fit: Calibrated<HestonParams> = HestonCalibrator::new(100.0, 0.03, 0.0, quotes)
    .with_options(CalibrationOptions::default().with_max_iterations(200))
    .calibrate(None)?;
let model = fit.to_model();
  • OptionQuote { strike, tau, price, option_type } (stochastic_rs::quant::OptionQuote, built by OptionQuote::new) is the one vanilla quote, its price a present value, and one list may mix maturities, calls and puts. BsmCalibrator, HestonCalibrator, SabrCalibrator, SvjCalibrator, DoubleHestonCalibrator, HkdeCalibrator, CgmysvCalibrator and HscmCalibrator are built by new(s, r, q, quotes) and LevyCalibrator by new(model_type, s, r, q, quotes), with one spot and an f64 dividend yield. The quotes replace the per-quote c_market, s and k vectors with their single tau and option_type, and the MarketSlice and MarketOption types (Python's MarketSlice stays). new panics unless s is finite and positive and r, q are finite; calibrate answers an empty list with InsufficientData and a strike, tau or price it cannot use with InvalidQuote { index }.
  • calibrate takes Option<Params>, the parameter set the fit returns, since Calibrator::InitialGuess is gone: a start is a CgmysvParams, LevyParams, HscmParams, SabrCapletParams or HullWhiteParams where it was a vector, an array or a tuple. with_start(params), or the start that new takes, replaces set_initial_guess and the params and initial_guess fields, and HestonCalibrator's mle_s, mle_v and mle_r arguments move to with_mle_seed(HestonMleSeed { … }).
  • Every quant calibrator returns calibration::Calibrated<Params, D = ()>, whose public fields are params, loss, converged, iterations, message, max_error, history and diagnostics, () but for the SABR smile's strikes and the Heston SLV fit's inner Heston fit, in place of its own …CalibrationResult. The trail is the result's history, recorded per call, where the calibrator had history(); an entry is { iteration, params, residuals, loss }, and CalibrationHistory::metric replaces metric_history. Error is QuantError where it was anyhow::Error. to_model() takes no arguments, the rates travelling with the pricing query, and neither does to_short_rate_model(): HullWhiteParams carries initial_rate and theta.
  • CalibrationOptions { max_iterations, tolerance, patience, record_history, loss_metrics, regularization }, passed through with_options, replaces the per-calibrator max_iter, max_iters, sd_tolerance, record_history and loss_metrics arguments, fields and setters; SabrSmileCalibrator keeps its basin-hopping knobs. A knob a fit cannot read, set away from its default, is Err(QuantError::Unsupported { what }).
  • 2.6.2's HestonCalibrationResult::termination string is the result's message, which CalibrationResult::message() returns. A Levenberg–Marquardt fit reports one of "converged", "evaluation budget exhausted", "no numerical progress", "solver failed", "flat objective", "not stationary" and "stopped at the bound of <name>", and a Nelder–Mead or rBergomi fit names its cap "iteration cap reached". Calibrated is #[non_exhaustive], so a result is built with Calibrated::new and its with_* methods, not a struct literal. The reported rmse comes from the pricer that was fitted.
  • with_feller_projection(true) replaces set_feller_projection(true); it lowers σ alone to the largest value with σ² ≤ 2κθ at every point the fit evaluates, so the result passes HestonParams::satisfies_feller_condition() exactly, and a surface that violates Feller's condition is fitted on the boundary. projected_with_feller_condition() moves σ alone too; 2.6.2's could stop one ulp outside the condition.
  • SabrCapletParams is { sabr, shift }, where 2.6.2 spelled out alpha, beta, nu and rho, and SabrCapletCalibrator::new(forward, tau, strikes, market_vols, start) takes it whole, holding its β and shift through the fit, where 2.6.2's new(forward, expiry, beta, strikes, market_vols) took β and left (α, ν, ρ) to initial_guess.
  • BlackKarasinskiSwaptionCalibrator, HullWhiteSwaptionCalibrator, G2ppSwaptionCalibrator and SabrCapletCalibrator report converged only when the spread of the simplex costs falls below tolerance·(|f₀| + tolerance), f₀ the start's best cost (CalibrationOptions::tolerance, 1e-10 by default), on a simplex that has contracted with no lower point beside its best vertex. The iteration cap, a "stagnated" or "simplex collapsed" stop, a flat objective or nonfinite simplex costs return false with the best parameters found, where 2.6.2's Hull–White and caplet fits reported true at their cap; the last element of the Python SabrCapletCalibrator tuple follows.

Heston SLV calibration

calibrate_leverage takes a local-volatility Grid2D<f64>, snapshot maturities and a ParticleMethod, and returns Result<ParticleCalibration, QuantError>. Use the result's leverage surface in place of the previously returned bare surface. The particle estimator uses the reference kernel and bandwidth, so recalibration can change existing numerical results.

HestonSlvCalibrator replaces calibrate_from_dupire. Supply spot, rates and the market call grid explicitly; its method is a LeverageMethod selecting particles or the Fokker–Planck solver. HestonSlvPricer reads leverage at each step's start. See Heston SLV calibration for the Rust and Python interfaces.

Optimizers and Rust version

Basin replaces argmin for L-BFGS and Nelder–Mead fits. L-BFGS polishing can produce slightly different estimates because Basin skips curvature updates that fail its numerical threshold. Basin also replaces levenberg-marquardt for least-squares calibration, including SVI, SSVI and the AI surrogate; these fits use trust-region damping, with pivoted QR for the Heston, double Heston, SVJ, HKDE, CGMYSV and surrogate fits and Cholesky for the BSM, SABR, Lévy, SVI and SSVI fits. CGMYSV optimizes in smooth bounded coordinates, as Heston does. The levenberg_marquardt::LeastSquaresProblem implementations on the calibrators are removed; use the Calibrator trait to run a fit.

nalgebra is no longer a direct workspace dependency; it can still appear transitively through dependencies such as gauss-quad. The six calibrators that took c_market, s and k as nalgebra::DVector<f64> (BsmCalibrator, SabrCalibrator, HestonCalibrator, HkdeCalibrator, DoubleHestonCalibrator, SvjCalibrator) take a Vec<OptionQuote> (above). The vectors that remain are ndarray::Array1<f64>: their parameter sets' From conversions, CalibrationHistory::residuals and the weights of HestonCalibrator::with_residual_weights, which replaces set_residual_weights and takes any Into<Array1<f64>>, a Vec<f64> included. DVector::from_vec(v) becomes Array1::from_vec(v) and DVector::from_element(n, x) becomes Array1::from_elem(n, x).

The Levenberg–Marquardt tolerance and patience keep their relative-tolerance and residual-evaluation-budget meanings. Evaluation counts and termination messages can differ between solvers. An exhausted budget, a failed model evaluation or a numerical stall does not count as convergence; the fit returns the best accepted parameters.

The workspace requires Rust 1.89 and declares it in rust-version. Cargo's edition-2024 resolver uses this minimum when selecting dependencies, which can favour older compatible releases during a fresh resolution.

Copulas

  • Clayton::partial_derivative returns the conditional distribution (the h-function), as the other Archimedean copulas do; v2 returned zeros for every input.
  • BB1 and BB7 are new variants of CopulaType.

Growing enums are #[non_exhaustive]

Enums that will keep gaining variants (CopulaType, HazardInterpolation, the scheme and family selectors, …) carry #[non_exhaustive], so a downstream match needs a _ => arm. Closed sets — OptionType, OptionStyle, Moneyness, the day-count conventions — stay exhaustive.

Parameter asserts name the parameter and its value

Constructors that rejected a bad parameter with a bare assert! now panic with a message of the form sigma must satisfy `sigma > 0.0`, got sigma = -0.2. If a test pinned the old message through #[should_panic(expected = …)], update the string. Heston::qe() checks HestonPow::Sqrt, kappa > 0, sigma > 0 and a positive s0 when it switches the scheme, and again when the scheme runs, since the fields stay public. The error convention (invalid parameter → panic; not computable → documented NaN; data-dependent failure → Result) is in design philosophy.

Sampling results that change for a given seed

  • RoughBergomi uses the Bennedsen–Lunde–Pakkanen hybrid scheme (κ = 1) instead of the exact covariance Cholesky path; paths for a fixed seed differ from v2, distributions agree.
  • Fbm / Fgn on a device backend draw their own stream; host and device paths agree in distribution, not bit for bit.

Closed-form values that change

erf, erfc, norm_cdf and ndtri in stochastic_rs_distributions::special are exact to double precision; v2.6 used Abramowitz–Stegun 7.1.26 for erf (1.5e-7 relative) and Acklam's approximation for ndtri (1.15e-9). Closed-form prices, Greeks and implied volatilities move in the seventh significant digit or later, so a test that pinned one to more digits needs re-pinning. The tails no longer cancel: norm_cdf(-10) is 7.6e-24, not 0.

Prelude and hub

  • MultivariateExt joined the prelude.
  • Instrument, InstrumentExt, PricingEngine, PricingResult and GreeksExt left the prelude; import them from stochastic_rs::traits::*.
  • The openblas / nalgebra linear-algebra features are gone with the move to faer; no feature is needed for the multivariate copulas.

Python

  • The wheel is CPU-only. metal, cuda, accelerate and ai are maturin build features; a class or function behind one of them raises ValueError with a rebuild hint when it is called from a build that lacks it.
  • device= on the device-capable classes is the device entry point for the Euler engine.
  • The AI classes (HestonNn, RBergomiNn, OneFactorNn, calibrate_surrogate) are behind the ai feature.
  • A panic in a constructor raises ValueError and one in sample / sample_par raises RuntimeError, not pyo3_runtime.PanicException (a BaseException); code that caught PanicException around those calls catches the ordinary exception instead.
  • HestonCalibrator.calibrate takes its starting point as initial_guess=, as the other calibrators do, where 2.6.2 spelled it initial=; with full_output=True the appended element is the stop reason above. PyHeston raises ValueError for a pow other than "sqrt" or "3/2", where 2.x fell back to the square-root variance.

What is not a breaking change

Widening a process's bound from HostBackend to EulerBackend (a process gaining a device kernel), a new CopulaType variant, a new prelude item, and a new pricer or calibrator: all of these are additive and arrive in minor releases.

Edit on GitHub

Last updated on

On this page