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: Cpuwhere 2.x hadbackend: 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,SheetBackendandEulerBackendare the capability traits a bound can name; see GPU support for which process accepts which. - Device sampling is
.on::<Metal>()(orCuda,Accelerate) on the process, orwith_backend(Cuda::new(1))with an explicit handle. A configuration the kernels cannot carry samples on the host bit-identically, anddevice_ready()onProcessExtsays so beforehand. - CubeCL is gone. Vulkan and WebGPU targets are no longer served; use
Cudaon NVIDIA andMetalon Apple GPUs. - Fallible sampling is on the trait:
ProcessExt::try_sample()/try_sample_par(m)returnResult<_, DeviceError>for every process (alwaysOkon the host); the inherenttry_sample_parofGbm/Ou/Cir/Fgnmoved there,try_sample_matrixstays 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 byOptionQuote::new) is the one vanilla quote, itspricea present value, and one list may mix maturities, calls and puts.BsmCalibrator,HestonCalibrator,SabrCalibrator,SvjCalibrator,DoubleHestonCalibrator,HkdeCalibrator,CgmysvCalibratorandHscmCalibratorare built bynew(s, r, q, quotes)andLevyCalibratorbynew(model_type, s, r, q, quotes), with one spot and anf64dividend yield. The quotes replace the per-quotec_market,sandkvectors with their singletauandoption_type, and theMarketSliceandMarketOptiontypes (Python'sMarketSlicestays).newpanics unlesssis finite and positive andr,qare finite;calibrateanswers an empty list withInsufficientDataand a strike,tauor price it cannot use withInvalidQuote { index }.calibratetakesOption<Params>, the parameter set the fit returns, sinceCalibrator::InitialGuessis gone: a start is aCgmysvParams,LevyParams,HscmParams,SabrCapletParamsorHullWhiteParamswhere it was a vector, an array or a tuple.with_start(params), or thestartthatnewtakes, replacesset_initial_guessand theparamsandinitial_guessfields, andHestonCalibrator'smle_s,mle_vandmle_rarguments move towith_mle_seed(HestonMleSeed { … }).- Every quant calibrator returns
calibration::Calibrated<Params, D = ()>, whose public fields areparams,loss,converged,iterations,message,max_error,historyanddiagnostics,()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'shistory, recorded per call, where the calibrator hadhistory(); an entry is{ iteration, params, residuals, loss }, andCalibrationHistory::metricreplacesmetric_history.ErrorisQuantErrorwhere it wasanyhow::Error.to_model()takes no arguments, the rates travelling with the pricing query, and neither doesto_short_rate_model():HullWhiteParamscarriesinitial_rateandtheta. CalibrationOptions { max_iterations, tolerance, patience, record_history, loss_metrics, regularization }, passed throughwith_options, replaces the per-calibratormax_iter,max_iters,sd_tolerance,record_historyandloss_metricsarguments, fields and setters;SabrSmileCalibratorkeeps its basin-hopping knobs. A knob a fit cannot read, set away from its default, isErr(QuantError::Unsupported { what }).- 2.6.2's
HestonCalibrationResult::terminationstring is the result'smessage, whichCalibrationResult::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".Calibratedis#[non_exhaustive], so a result is built withCalibrated::newand itswith_*methods, not a struct literal. The reportedrmsecomes from the pricer that was fitted. with_feller_projection(true)replacesset_feller_projection(true); it lowers σ alone to the largest value with σ² ≤ 2κθ at every point the fit evaluates, so the result passesHestonParams::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.SabrCapletParamsis{ sabr, shift }, where 2.6.2 spelled outalpha,beta,nuandrho, andSabrCapletCalibrator::new(forward, tau, strikes, market_vols, start)takes it whole, holding itsβand shift through the fit, where 2.6.2'snew(forward, expiry, beta, strikes, market_vols)tookβand left(α, ν, ρ)toinitial_guess.BlackKarasinskiSwaptionCalibrator,HullWhiteSwaptionCalibrator,G2ppSwaptionCalibratorandSabrCapletCalibratorreportconvergedonly when the spread of the simplex costs falls belowtolerance·(|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 returnfalsewith the best parameters found, where 2.6.2's Hull–White and caplet fits reportedtrueat their cap; the last element of the PythonSabrCapletCalibratortuple 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_derivativereturns the conditional distribution (the h-function), as the other Archimedean copulas do; v2 returned zeros for every input.BB1andBB7are new variants ofCopulaType.
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
RoughBergomiuses 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/Fgnon 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
MultivariateExtjoined the prelude.Instrument,InstrumentExt,PricingEngine,PricingResultandGreeksExtleft the prelude; import them fromstochastic_rs::traits::*.- The
openblas/nalgebralinear-algebra features are gone with the move tofaer; no feature is needed for the multivariate copulas.
Python
- The wheel is CPU-only.
metal,cuda,accelerateandaiarematurinbuild features; a class or function behind one of them raisesValueErrorwith 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 theaifeature. - A panic in a constructor raises
ValueErrorand one insample/sample_parraisesRuntimeError, notpyo3_runtime.PanicException(aBaseException); code that caughtPanicExceptionaround those calls catches the ordinary exception instead. HestonCalibrator.calibratetakes its starting point asinitial_guess=, as the other calibrators do, where 2.6.2 spelled itinitial=; withfull_output=Truethe appended element is the stop reason above.PyHestonraisesValueErrorfor apowother 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.
Last updated on
Benchmarks
Criterion bench numbers — fGN on CPU, Accelerate, Metal and CUDA, the Euler engine on Metal and CUDA, and distribution sampling against rand_distr.
Contributing
How to contribute to stochastic-rs — coding conventions, the SKILL system that automates per-feature recipes, and the per-PR docs/tests/bench rule.