API reference¶
Author: Artur Sepp / First recorded: 2026-08-16
Reference for stochvolmodels. Software citation: CITATION.cff.
Names listed by stochvolmodels.__all__ are the stable high-level surface. Advanced names are
reachable at the package root outside __all__ and are documented here for research use. Other
historical root names remain lazy and import-compatible but are not the recommended starting point.
The tiers are defined on the
conventions page.
Each section below is named after the page that explains its names. A page that is not written
yet is named in italics. The API contract test resolves every stable name and fails if __all__ or
a stable docstring drifts; scripts/check_docs.py checks that each name sits under its owning page.
Installation and first result¶
Explained in Installation and first result. The installed release string is
stochvolmodels.__version__.
Option chains, notation and conventions¶
Explained in Option chains, notation and conventions.
- class stochvolmodels.OptionSlice(ttm, forward, strikes, optiontypes, id, discfactor=None, discount_rate=None, bid_ivs=None, ask_ivs=None, bid_prices=None, ask_prices=None)¶
container for slice data
- Parameters:
ttm (float)
forward (float)
strikes (ndarray)
optiontypes (ndarray)
id (str)
discfactor (float)
discount_rate (float)
bid_ivs (ndarray | None)
ask_ivs (ndarray | None)
bid_prices (ndarray | None)
ask_prices (ndarray | None)
- class stochvolmodels.OptionChain(ttms, forwards, strikes_ttms, optiontypes_ttms, ids, discfactors=None, discount_rates=None, ticker=None, bid_ivs=None, ask_ivs=None, bid_prices=None, ask_prices=None, forwards0=None)¶
container for chain data note we do not use chain as list of slices here for extensive use of numba we use List[np.ndarray] with per slice data
- Parameters:
ttms (ndarray)
forwards (ndarray)
strikes_ttms (List[ndarray])
optiontypes_ttms (List[ndarray])
ids (ndarray | None)
discfactors (ndarray | None)
discount_rates (ndarray | None)
ticker (str | None)
bid_ivs (List[ndarray] | None)
ask_ivs (List[ndarray] | None)
bid_prices (List[ndarray] | None)
ask_prices (List[ndarray] | None)
forwards0 (ndarray | None)
- compute_model_ivols_from_chain_data(model_prices, forwards=None)¶
invert model prices to Black-Scholes implied volatilities, slice by slice.
The step between a pricer and the calibration objective, which compares model and market in volatility rather than price terms.
- Parameters:
model_prices (List[ndarray])
forwards (ndarray)
- Return type:
List[ndarray]
- get_mid_vols()¶
mid implied volatilities per slice, the average of bid and ask.
- Return type:
List[ndarray]
- get_slice(id)¶
return the OptionSlice with the given id.
- Parameters:
id (str)
- Return type:
- classmethod get_uniform_chain(ttms=array([0.083, 0.25]), ids=array(['1m', '3m'], dtype='<U2'), forwards=array([1., 1.]), strikes=array([0.9, 1., 1.1]), flat_vol=0.2)¶
construct a synthetic chain on a uniform strike grid, with no market quotes.
Used to plot model implied volatilities where no market data is needed. A flat forward vector is broadcast to the requested maturities, which keeps the default unit forward useful when callers provide a custom maturity grid.
- Parameters:
ttms (ndarray)
ids (ndarray)
forwards (ndarray)
strikes (ndarray)
flat_vol (float)
- Return type:
- classmethod to_forward_normalised_strikes(obj)¶
strike and prices to normalized by forwards
- Parameters:
obj (OptionChain)
- Return type:
- class stochvolmodels.OptionType(*values)¶
Option payoff codes accepted by SVM and VanillaOptionPricers.
- class stochvolmodels.VariableType(*values)¶
state variables for log SV model
Log-normal stochastic volatility model with quadratic drift¶
Explained in Log-normal stochastic volatility model with quadratic drift.
- class stochvolmodels.LogSvParams(sigma0=0.2, theta=0.2, kappa1=1.0, kappa2=2.5, beta=-1.0, volvol=1.0, vol_backbone=None, H=0.5, weights=None, nodes=None)¶
Parameters of the log-normal beta SV model with quadratic drift.
The volatility process of Eq. (3.12) under the MMA measure Q is
- dsigma_t = (kappa1 + kappa2 sigma_t)(theta - sigma_t) dt
beta sigma_t dW^(0)_t + epsilon sigma_t dW^(1)_t.
- Parameters:
sigma0 (float)
theta (float)
kappa1 (float)
kappa2 (float | None)
beta (float)
volvol (float)
vol_backbone (Series)
H (float)
weights (ndarray)
nodes (ndarray)
- sigma0¶
Initial volatility sigma_0.
- Type:
float, default 0.2
- theta¶
Mean volatility theta > 0.
- Type:
float, default 0.2
- kappa1¶
Linear mean-reversion rate kappa1 >= 0.
- Type:
float, default 1.0
- kappa2¶
Quadratic mean-reversion rate kappa2 >= 0.
Nonemaps tokappa1 / theta, the pure quadratic drift case. Theorem 3.7 requireskappa2 >= betafor Z_t to be a Q-martingale andkappa2 >= 2 betafor R_t to be a martingale under the inverse measure; neither bound is enforced here.- Type:
Optional[float], default 2.5
- beta¶
Volatility beta, the loading of the volatility on the price Brownian motion. Sign follows the return-volatility correlation.
- Type:
float, default -1.0
- volvol¶
Volatility of residual volatility epsilon > 0.
- Type:
float, default 1.0
- vol_backbone¶
Optional term structure of multiplicative scalings for theta, indexed by time to maturity. See Sec. 6.2.
- Type:
pd.Series, default None
- H¶
Hurst exponent. 0.5 is the article’s dynamics; values below 0.5 select the rough extension noted in Sec. 7.
- Type:
float, default 0.5
- weights¶
Rough-kernel quadrature weights, set by
approximate_kernel().- Type:
np.ndarray, default None
- nodes¶
Rough-kernel quadrature nodes, set by
approximate_kernel().- Type:
np.ndarray, default None
- approximate_kernel(T)¶
set the Markovian approximation nodes and weights of the rough kernel.
Outside the scope of the article, which fixes H = 1/2. The number of nodes is 1 for H in (0.49, 0.5], 2 for H in (0.4, 0.49] and 3 below, following the European quadrature rule; H = 1/2 degenerates to a single node at 1e-3, which reproduces the standard (non-rough) dynamics of Eq. (3.12).
- Parameters:
T (float) – Horizon in years over which the kernel is approximated.
- assert_vol_moments_stability(n_terms=4)¶
print whether all eigenvalues of Lambda^(1,k*) have negative real part.
The regularity condition under Eq. (3.50) that makes the truncation of Eq. (3.51) admissible. Despite the name this asserts nothing; it prints.
- Parameters:
n_terms (int)
- property eta: float¶
exponent eta of the steady-state density of the volatility, Eq. (3.38).
The generalized inverse Gaussian steady state of Eq. (3.38) is G(sigma) = c sigma^(eta - 1) exp{-(q / sigma + b sigma)} with eta = 2 (kappa2 theta - kappa1) / vartheta^2 - 1.
- property gamma: float¶
quadratic mean-reversion rate under the pure quadratic drift, kappa1 / theta.
The case kappa2 = kappa1 / theta identified with Fig. 1 of the article.
- get_qvar_grid(ttm=1.0, n_stdevs=3.0, n=200)¶
spatial grid on [0, .] for the density of the quadratic variance I_tau.
I_t is defined by dI_t = sigma_t^2 dt in Eq. (3.12). Used for Fig. 6(b).
- Parameters:
ttm (float)
n_stdevs (float)
n (int)
- Return type:
ndarray
- get_sigma_grid(ttm=1.0, n_stdevs=3.0, n=200)¶
spatial grid on [0, .] for the density of the volatility sigma_tau.
Half-width scales with sqrt(vartheta^2 ttm), the diffusive spread of Eq. (3.19). Used for Fig. 6(c).
- Parameters:
ttm (float)
n_stdevs (float)
n (int)
- Return type:
ndarray
- get_variable_space_grid(variable_type=VariableType.LOG_RETURN, ttm=1.0, n_stdevs=3, n=200)¶
dispatch to the spatial grid of the state variable selected by variable_type.
- Raises:
NotImplementedError – If variable_type is not one of the three state variables of Eq. (3.34).
- Parameters:
variable_type (VariableType)
ttm (float)
n_stdevs (float)
n (int)
- Return type:
ndarray
- get_vol_backbone_eta(tau)¶
return the backbone scaling eta at the nearest quoted maturity at or beyond tau.
Returns 1.0, the flat-theta case of Eq. (3.12), when no backbone is attached.
- Parameters:
tau (float)
- Return type:
float
- get_vol_backbone_etas(ttms)¶
return
get_vol_backbone_eta()evaluated over an array of maturities.- Parameters:
ttms (ndarray)
- Return type:
ndarray
- get_vol_moments_lambda(n_terms=4)¶
assemble the truncated moment generator Lambda^(1,k*) of Eq. (3.48).
The mean-adjusted volatility Y_t = sigma_t - theta of Eq. (3.32) has moments m_bar^(n)(tau) = E[Y_tau^n] solving the recursion of Eq. (3.50). Truncating at order k* under the closure of Eq. (3.51) gives the finite linear system
d_tau M = Lambda M + Cof Eq. (3.48), whose generator this returns:row 1 (-kappa, -kappa2, 0, …) row n (c(n) theta^2, 2 c(n) theta, c(n) - n kappa, -n kappa2, …)
with c(n) = 0.5 vartheta^2 n (n - 1) from Eq. (3.46).
- Parameters:
n_terms (int, default 4) – Truncation order k*. Fig. 2 compares k* = 4 and k* = 8 against Monte Carlo; k* = 4 matches the first two moments, k* = 8 the first four.
- Returns:
Lower-Hessenberg generator Lambda^(1,k*).
- Return type:
np.ndarray, shape (n_terms, n_terms)
- get_x_grid(ttm=1.0, n_stdevs=3.0, n=200)¶
spatial grid for the density of the log-price X_tau.
Centred on the drift -0.5 sigma_t^2 of Eq. (3.16) with sigma_t the maturity-averaged volatility, and spanning
n_stdevs + 1standard deviations either side. Used for the Fourier inversion illustrated in Fig. 6(a).- Parameters:
ttm (float)
n_stdevs (float)
n (int)
- Return type:
ndarray
- property kappa: float¶
effective mean-reversion rate kappa = kappa1 + kappa2 theta of Eq. (3.32).
The rate at which the mean-adjusted volatility Y_t = sigma_t - theta reverts to zero in the linearised drift, and the diagonal scale of Lambda^(1,k*) in Eq. (3.48).
- print_vol_moments_stability(n_terms=4)¶
print the per-moment diagonal conditions c(n) - n kappa and the spectrum of Lambda.
- Parameters:
n_terms (int)
- Return type:
None
- set_vol_backbone(vol_backbone)¶
attach a term structure of scaling factors for the mean volatility theta.
The article calibrates a single theta; Sec. 6.2 notes that the fit in the ATM region improves with a term structure of theta. The backbone carries that term structure as a multiplicative eta indexed by time to maturity.
- Parameters:
vol_backbone (Series)
- Return type:
None
- property theta2: float¶
square of the mean volatility, theta^2.
- to_dict()¶
return the parameters as a plain dict, including the derived kernel arrays.
- Return type:
Dict[str, Any]
- to_str()¶
return the six model parameters of Eq. (3.12) formatted to two decimals.
- Return type:
str
- property vartheta2: float¶
total instantaneous variance of the volatility process, vartheta^2 = beta^2 + epsilon^2.
Equation (3.13). The diffusion of Eq. (3.19) is v(sigma) = vartheta sigma, so the two Brownian loadings enter the moment ODEs and the affine expansion only through this sum; beta enters separately through the measure-dependent terms of Eq. (4.3).
- class stochvolmodels.LogSVPricer¶
ModelPricer for the log-normal beta SV model of Eq. (3.12).
Prices option chains by Fourier inversion of the affine expansion, simulates the model by the scheme of Eq. (3.59), and calibrates to market implied volatilities under the martingale constraints of Theorem 3.7.
- calibrate_model_params_to_chain(option_chain, params0, params_min=LogSvParams(sigma0=0.1, theta=0.1, kappa1=0.25, kappa2=0.25, beta=-3.0, volvol=0.2, vol_backbone=None, H=0.5, weights=None, nodes=None), params_max=LogSvParams(sigma0=1.5, theta=1.5, kappa1=10.0, kappa2=10.0, beta=3.0, volvol=3.0, vol_backbone=None, H=0.5, weights=None, nodes=None), is_vega_weighted=True, is_unit_ttm_vega=False, model_calibration_type=LogsvModelCalibrationType.PARAMS5, constraints_type=ConstraintsType.UNCONSTRAINT, calibration_engine=CalibrationEngine.ANALYTIC, nb_path=100000, nb_steps=360, seed=10, **kwargs)¶
calibrate model parameters to a chain of market implied volatilities.
Minimizes the weighted mean squared error of Eq. (6.3),
WMSE = sum_n w_n(T, K) (sigma_n^model(T, K) - sigma_n^implied(T, K))^2,
with w_n set to Black-Scholes vega when
is_vega_weightedis True, under the constraints selected byconstraints_type. Sec. 6.2 uses SLSQP;scipy.optimize.minimizeis called with its default choice for the given bounds and constraints here.- Parameters:
option_chain (OptionChain) – Market chain carrying maturities, strikes, option types and mid vols.
params0 (LogSvParams) – Starting point. Under PARAMS4 its kappa1 and kappa2 are held fixed.
params_min (LogSvParams) – Box bounds on the fitted parameters.
params_max (LogSvParams) – Box bounds on the fitted parameters.
is_vega_weighted (bool, default True) – Weight residuals by vega, per Eq. (6.3).
is_unit_ttm_vega (bool, default False) – Normalize vegas within each maturity slice before weighting.
model_calibration_type (LogsvModelCalibrationType, default PARAMS5) – Which parameters are free.
constraints_type (ConstraintsType, default UNCONSTRAINT) – Martingale and moment constraints of Theorem 3.7.
calibration_engine (CalibrationEngine, default ANALYTIC) – Analytic expansion or Monte Carlo inside the objective.
nb_path (int) – Monte Carlo controls, used only for the MC engines. The randoms are drawn once and reused across iterations so the objective is smooth.
nb_steps (int) – Monte Carlo controls, used only for the MC engines. The randoms are drawn once and reused across iterations so the objective is smooth.
seed (int) – Monte Carlo controls, used only for the MC engines. The randoms are drawn once and reused across iterations so the objective is smooth.
- Returns:
Fitted parameters. Compare with Eq. (6.4), which reports sigma0 = 0.41, theta = 0.38, beta = 0.50, epsilon = 3.06 for Bitcoin on 20 June 2023.
- Return type:
- compute_chain_prices_with_vols(option_chain, params, variable_type=VariableType.LOG_RETURN, **kwargs)¶
price chain and compute model vols
- Parameters:
option_chain (OptionChain)
params (ModelParams)
variable_type (VariableType)
- Return type:
Tuple[List[ndarray], List[ndarray]]
- model_mc_price_chain(option_chain, params, is_spot_measure=True, variable_type=VariableType.LOG_RETURN, nb_path=100000, nb_steps=None, **kwargs)¶
price an option chain by Monte Carlo rather than the affine expansion.
Routes to the rough simulator when
use_rough_mcis passed in kwargs, which then also requiresseed; otherwise tologsv_mc_chain_pricer().- Returns:
Model prices and their standard errors, one array per maturity slice.
- Return type:
Tuple[List[np.ndarray], List[np.ndarray]]
- Parameters:
option_chain (OptionChain)
params (LogSvParams)
is_spot_measure (bool)
variable_type (VariableType)
nb_path (int)
nb_steps (int | None)
- price_chain(option_chain, params, is_spot_measure=True, **kwargs)¶
price an option chain, implementing the generic ModelPricer interface.
Delegates to
logsv_chain_pricer(). Withis_spot_measure=Truethe chain is valued under the MMA measure by Eqs. (5.4) and (5.9); with False, under the inverse measure by Eqs. (5.13) and (5.16).- Parameters:
option_chain (OptionChain)
params (LogSvParams)
is_spot_measure (bool)
- Return type:
List[ndarray]
- price_slice(params, ttm, forward, strikes, optiontypes, discfactor=1.0, **kwargs)¶
price single slice_t using model chain pricer return price slices and model implied vols
- Parameters:
params (ModelParams)
ttm (float)
forward (float)
strikes (ndarray)
optiontypes (ndarray)
discfactor (float)
- Return type:
Tuple[ndarray, ndarray]
- price_vanilla(params, ttm, forward, strike, optiontype, discfactor=1.0, **kwargs)¶
price single option using slice_t pricer return price and model implied vol
- Parameters:
params (ModelParams)
ttm (float)
forward (float)
strike (float)
optiontype (str)
discfactor (float)
- Return type:
Tuple[float, float]
Steady-state distribution, moments and expected quadratic variance¶
Explained in Steady-state distribution, moments and expected quadratic variance.
- stochvolmodels.compute_analytic_qvar(params, ttm=1.0, n_terms=4)¶
annualized expected quadratic variance E[(1/tau) int_0^tau sigma_t^2 dt].
Corollary 3.4, Eq. (3.53),
- I_hat_tau = (1/tau) (m_hat^(2)(tau) + 2 theta m_hat^(1)(tau)) + theta^2
O(k*),
where m_hat^(1) and m_hat^(2) are the first two integrated moments returned by
compute_analytic_vol_moments()withis_qvar=True, and O(k*) is the truncation error. This is the model fair value of a continuously monitored variance swap, usable for calibration.- Parameters:
params (LogSvParams) – Model parameters.
ttm (float, default 1.0) – Time to maturity tau in years. At tau = 0 the value collapses to sigma0^2.
n_terms (int, default 4) – Truncation order k*.
- Returns:
Annualized expected quadratic variance.
- Return type:
float
Martingale conditions, measures and positive skews¶
Explained in Martingale conditions, measures and positive skews.
- class stochvolmodels.ConstraintsType(*values)¶
parameter constraints imposed during calibration.
MMA_MARTINGALE imposes kappa2 >= beta, which by Theorem 3.7(1) makes Z_t a martingale under the MMA measure and by Theorem 3.6 makes Q and the inverse measure equivalent. INVERSE_MARTINGALE imposes the stronger kappa2 >= 2 beta of Theorem 3.7(2), needed for R_t to be a martingale under the inverse measure; Sec. 6.2 calibrates Bitcoin under this constraint. The MOMENT4 variants add kappa >= 1.5 vartheta^2, the n = 4 diagonal stability condition c(4) - 4 kappa < 0 of the moment generator in Eq. (3.48), which keeps the fourth moment of the volatility finite.
The moment generating function and its affine expansion¶
Explained in The moment generating function and its affine expansion. These are advanced names.
- class stochvolmodels.ExpansionOrder(*values)¶
truncation order of the affine expansion of the MGF.
FIRST is the leading term E^[1] of Eq. (4.16), carrying A^(0), A^(1), A^(2). SECOND is E^[2] of Eq. (4.24), carrying A^(0) through A^(4); it is the order used for option valuation in Sec. 6 and is the only one Propositions 4.4-4.6 show to reproduce the variances of the state variables.
- stochvolmodels.compute_logsv_a_mgf_grid(ttm, phi_grid, psi_grid, theta_grid, sigma0, theta, kappa1, kappa2, beta, volvol, variable_type=VariableType.LOG_RETURN, expansion_order=ExpansionOrder.SECOND, a_t0=None, is_stiff_solver=False, is_analytic=False, is_spot_measure=True, vol_backbone_eta=1.0, **kwargs)¶
log of the affine expansion of the MGF, over a grid of transform variables.
Solves the coefficient ODEs of Eq. (4.14) over the grid and contracts the result against the powers of the initial mean-adjusted volatility Y = sigma0 - theta to give
log E^[m](tau, Y) = sum_k A^(k)(tau) Y^k,
the exponent of Eq. (4.16) at first order and Eq. (4.24) at second. The exponential is deliberately not taken: the option valuation formulas of Eqs. (5.4), (5.13) and (5.20) consume E^[m] directly, and returning the log saves one exponentiation per grid point.
- Parameters:
ttm (float) – Time to maturity tau in years.
phi_grid (np.ndarray, complex) – Transform grids for Phi, Psi and Theta of Eq. (4.5). Sec. 6.1 uses about 500 points for Phi.
psi_grid (np.ndarray, complex) – Transform grids for Phi, Psi and Theta of Eq. (4.5). Sec. 6.1 uses about 500 points for Phi.
theta_grid (np.ndarray, complex) – Transform grids for Phi, Psi and Theta of Eq. (4.5). Sec. 6.1 uses about 500 points for Phi.
sigma0 (float) – Model parameters of Eq. (3.12).
theta (float) – Model parameters of Eq. (3.12).
kappa1 (float) – Model parameters of Eq. (3.12).
kappa2 (float) – Model parameters of Eq. (3.12).
beta (float) – Model parameters of Eq. (3.12).
volvol (float) – Model parameters of Eq. (3.12).
variable_type (VariableType, default VariableType.LOG_RETURN) – State variable whose transform drives the initial condition.
expansion_order (ExpansionOrder, default ExpansionOrder.SECOND) – Truncation order. SECOND is the order used throughout Sec. 6.
a_t0 (Optional[np.ndarray], default None) – Initial coefficients; None calls
get_init_conditions_a().is_stiff_solver (bool, default False) – Use the BDF solver in the numerical path.
is_analytic (bool, default False) – Take the semi-analytic fixed-point path rather than
solve_ivp.is_spot_measure (bool, default True) – True for the MMA measure (p = 1), False for the inverse measure (p = -1).
vol_backbone_eta (float, default 1.0) – Maturity scaling of theta. Ignored on the analytic path.
- Returns:
a_t1 (np.ndarray, shape (n_grid, n_terms), complex) – Coefficients A(tau) on the grid.
log_mgf (np.ndarray, shape (n_grid,), complex) – log E^[m](tau, Y) on the grid.
- Raises:
NotImplementedError – If expansion_order is ExpansionOrder.ZERO.
- Return type:
Tuple[ndarray, ndarray]
- stochvolmodels.func_a_ode_quadratic_terms(theta, kappa1, kappa2, beta, volvol, phi, psi, is_spot_measure=True, expansion_order=ExpansionOrder.FIRST, vol_backbone_eta=1.0)¶
assemble the matrices M^(k), L^(k)(p) and H^(k)(p) of the coefficient ODEs.
Builds the right-hand side of Eq. (4.14),
A^(k)_tau = A’ M^(k) A + (L^(k)(p))’ A + H^(k)(p),
with entries given by Eq. (4.17) at first order and Eq. (4.25) at second.
- Parameters:
theta (float) – Model parameters of Eq. (3.12). Only the combination vartheta^2 = beta^2 + volvol^2 of Eq. (3.13) enters M^(k); beta enters L^(k) separately through the measure-dependent terms of Eq. (4.3).
kappa1 (float) – Model parameters of Eq. (3.12). Only the combination vartheta^2 = beta^2 + volvol^2 of Eq. (3.13) enters M^(k); beta enters L^(k) separately through the measure-dependent terms of Eq. (4.3).
kappa2 (float) – Model parameters of Eq. (3.12). Only the combination vartheta^2 = beta^2 + volvol^2 of Eq. (3.13) enters M^(k); beta enters L^(k) separately through the measure-dependent terms of Eq. (4.3).
beta (float) – Model parameters of Eq. (3.12). Only the combination vartheta^2 = beta^2 + volvol^2 of Eq. (3.13) enters M^(k); beta enters L^(k) separately through the measure-dependent terms of Eq. (4.3).
volvol (float) – Model parameters of Eq. (3.12). Only the combination vartheta^2 = beta^2 + volvol^2 of Eq. (3.13) enters M^(k); beta enters L^(k) separately through the measure-dependent terms of Eq. (4.3).
phi (np.complex128) – Transform variable Phi conjugate to the log-price X_tau in Eq. (4.5). Theorem 4.2 gives existence for Re(Phi) in (-1, 0) when p = 1 and in (0, 1) when p = -1; option valuation uses Re(Phi) = -1/2 in Eq. (5.4) and Re(Phi) = 1/2 in Eq. (5.13).
psi (np.complex128) – Transform variable Psi conjugate to the quadratic variance I_tau. Theorem 4.3 gives existence for Re(Psi) < 0 when kappa2 > vartheta sqrt(-2 Re Psi).
is_spot_measure (bool, default True) – True selects p = 1, the MMA measure Q, so kappa_2^(p) = kappa2 and lambda^(p) = 0. False selects p = -1, the inverse measure Q~, so kappa_2^(p) = kappa2 - beta and lambda^(p) = beta theta^2, per Eq. (4.3).
expansion_order (ExpansionOrder, default ExpansionOrder.FIRST) – Truncation order, which fixes the dimension n at 3 or 5.
vol_backbone_eta (float, default 1.0) – Multiplicative scaling of the mean volatility theta at this maturity. Not part of the article, which fixes a single theta; 1.0 reproduces Eqs. (4.17) and (4.25) exactly.
- Returns:
M (np.ndarray, shape (n, n, n), complex) – Quadratic forms M^(k), stacked on the leading axis and symmetric in the trailing two. Independent of p (Remark 4.1).
L (np.ndarray, shape (n, n), complex) – Linear terms L^(k)(p).
H (np.ndarray, shape (n,), complex) – Free terms H^(k)(p), proportional to Phi^2 + p Phi - 2 Psi.
- Return type:
Tuple[ndarray, ndarray, ndarray]
- stochvolmodels.func_rhs(t, A0, M, L, H)¶
right-hand side of the coefficient ODE system, Eq. (4.14).
Signature ordered for
scipy.integrate.solve_ivp;tis unused because the system is autonomous in tau.- Parameters:
t (float)
A0 (ndarray)
M (Tuple[ndarray])
L (ndarray)
H (ndarray)
- Return type:
ndarray
- stochvolmodels.func_rhs_jac(t, A0, M, L, H)¶
Jacobian of
func_rhs()with respect to A, for the stiff BDF solver.Signature ordered for
scipy.integrate.solve_ivp;tis unused.- Parameters:
t (float)
A0 (ndarray)
M (Tuple[ndarray])
L (ndarray)
H (ndarray)
- Return type:
ndarray
- stochvolmodels.get_expansion_n(expansion_order=ExpansionOrder.FIRST)¶
number of coefficients A^(k): 3 for the first order, Eq. (4.16), else 5, Eq. (4.24).
- Parameters:
expansion_order (ExpansionOrder)
- Return type:
int
- stochvolmodels.get_init_conditions_a(phi_grid, psi_grid, theta_grid, n_terms, variable_type=VariableType.LOG_RETURN)¶
initial condition A(0) of the coefficient ODEs, over the transform grid.
Equations (4.17) and (4.25) set A(0) = (0, -Theta, 0, …), where Theta is the transform variable conjugate to the mean-adjusted volatility Y_tau. For the log-return and quadratic variance the payoff transform enters through Phi and Psi and Theta is zero, so A(0) vanishes; only VariableType.SIGMA populates the second component with -Theta.
- Returns:
Initial coefficients, one row per transform grid point.
- Return type:
np.ndarray, shape (n_grid, n_terms), complex
- Raises:
NotImplementedError – If variable_type is not one of the three state variables of Eq. (3.34).
- Parameters:
phi_grid (ndarray)
psi_grid (ndarray)
theta_grid (ndarray)
n_terms (int)
variable_type (VariableType)
- stochvolmodels.solve_a_ode_grid(phi_grid, psi_grid, ttm, theta, kappa1, kappa2, beta, volvol, is_spot_measure=True, a_t0=None, is_stiff_solver=False, expansion_order=ExpansionOrder.FIRST, vol_backbone_eta=1.0)¶
apply
solve_ode_for_a()across the transform grid, returning A(tau) per point.- Parameters:
phi_grid (ndarray)
psi_grid (ndarray)
ttm (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
volvol (float)
is_spot_measure (bool)
a_t0 (ndarray | None)
is_stiff_solver (bool)
expansion_order (ExpansionOrder)
vol_backbone_eta (float)
- Return type:
ndarray
- stochvolmodels.solve_analytic_ode_for_a(ttm, theta, kappa1, kappa2, beta, volvol, phi, psi, is_spot_measure, a_t0=None, expansion_order=ExpansionOrder.FIRST, year_days=260)¶
integrate the coefficient ODEs semi-analytically for a single Phi.
Steps on a daily grid, at each step advancing the linear part exactly by eigendecomposition of L and treating the quadratic part A’ M^(k) A by fixed point iteration. This is the cheaper alternative to
solve_ode_for_a()referred to in Sec. 6.1, where the cost of the ODE step is O(P N_max) in Eq. (6.1).- Parameters:
year_days (int, default 260) – Business days per year setting the step count ceil(year_days tau).
ttm (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
volvol (float)
phi (complex128)
psi (complex128)
is_spot_measure (bool)
a_t0 (ndarray | None)
expansion_order (ExpansionOrder)
- Returns:
Coefficient vector A(tau).
- Return type:
np.ndarray, shape (n,), complex
Notes
Does not accept
vol_backbone_eta, so it is fixed at the article’s flat theta. The fixed point runs a fixed 10 iterations with no convergence test.
- stochvolmodels.solve_analytic_ode_for_a0(t_span, theta, kappa1, kappa2, beta, volvol, phi, psi, expansion_order=ExpansionOrder.FIRST)¶
integrate the coefficient ODEs over a time span with a dense solver. Superseded.
Retained for reference;
solve_analytic_ode_for_a()is the faster path.- Parameters:
t_span (Tuple[float, float])
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
volvol (float)
phi (complex128)
psi (complex128)
expansion_order (ExpansionOrder)
- Return type:
ndarray
- stochvolmodels.solve_analytic_ode_grid_phi(phi_grid, psi_grid, ttm, theta, kappa1, kappa2, beta, volvol, is_spot_measure=True, a_t0=None, expansion_order=ExpansionOrder.FIRST)¶
apply
solve_analytic_ode_for_a()across the transform grid.- Parameters:
phi_grid (ndarray)
psi_grid (ndarray)
ttm (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
volvol (float)
is_spot_measure (bool)
a_t0 (ndarray | None)
expansion_order (ExpansionOrder)
- Return type:
ndarray
- stochvolmodels.solve_ode_for_a(ttm, theta, kappa1, kappa2, beta, volvol, phi, psi, is_spot_measure=True, a_t0=None, expansion_order=ExpansionOrder.FIRST, is_stiff_solver=False, dense_output=False, vol_backbone_eta=1.0)¶
integrate the coefficient ODEs of Eq. (4.14) numerically for a single Phi.
- Parameters:
ttm (float) – Time to maturity tau in years.
theta (float) – Model parameters of Eq. (3.12).
kappa1 (float) – Model parameters of Eq. (3.12).
kappa2 (float) – Model parameters of Eq. (3.12).
beta (float) – Model parameters of Eq. (3.12).
volvol (float) – Model parameters of Eq. (3.12).
phi (np.complex128) – Transform variables Phi and Psi of Eq. (4.5).
psi (np.complex128) – Transform variables Phi and Psi of Eq. (4.5).
is_spot_measure (bool, default True) – True for the MMA measure (p = 1), False for the inverse measure (p = -1).
a_t0 (Optional[np.ndarray], default None) – Initial condition A(0). None gives the zero vector, which is A(0) = (0, -Theta, 0, …) of Eq. (4.17) with Theta = 0.
expansion_order (ExpansionOrder, default ExpansionOrder.FIRST) – Truncation order.
is_stiff_solver (bool, default False) – Use the BDF method with an analytic Jacobian rather than the default RK45.
dense_output (bool, default False) – Request a continuous solution from the solver.
vol_backbone_eta (float, default 1.0) – Maturity scaling of theta; 1.0 reproduces the article.
- Returns:
Solver result; the coefficients at tau are
ode_sol.y[:, -1].- Return type:
OdeResult
Notes
Theorem 4.7 gives conditions under which A(tau) stays continuous on [0, tau_0); the solution of a quadratic system can otherwise blow up in finite time, and no check for that is performed here.
Fourier pricing of European options¶
Explained in Fourier pricing of European options. The model
pricers’ price_vanilla, price_slice and price_chain are documented with each pricer; inverse
options are explained in Inverse options and the inverse measure, and options
on quadratic variance in
Expected quadratic variance, variance swaps and QV options. The
functions below are the same callable
objects exported by vanilla_option_pricers; stochvolmodels does not maintain a duplicate
implementation.
Black-Scholes-Merton analytics¶
- stochvolmodels.compute_bsm_vanilla_price(forward, strike, ttm, vol, optiontype='C', discfactor=1.0)¶
Black-Scholes-Merton forward price of a vanilla option.
With s_ttm = vol*sqrt(ttm), d1 = (log(F/K) + 0.5*s_ttm^2)/s_ttm, d2 = d1 - s_ttm:
call: discfactor * (F * N(d1) - K * N(d2)) put: discfactor * (K * N(-d2) - F * N(-d1))
Below the diffusion floor (is_intrinsic) the intrinsic payoff is returned.
- Parameters:
forward (float) – forward price of the underlying, F = spot*exp((r-q)*ttm).
strike (float) – option strike.
ttm (float) – time to maturity, in years.
vol (float) – lognormal volatility.
optiontype (str, default 'C') – one of ‘C’, ‘IC’ (call branch) or ‘P’, ‘IP’ (put branch).
discfactor (float, default 1.0) – discount factor exp(-r*ttm) applied to the forward payoff.
- Returns:
option price.
- Return type:
float
- Raises:
NotImplementedError – if optiontype is not one of ‘C’, ‘P’, ‘IC’, ‘IP’.
- stochvolmodels.compute_bsm_vanilla_slice_prices(ttm, forward, strikes, vols, optiontypes, discfactor=1.0)¶
bsm prices for an aligned slice of strikes, vols, and optiontypes at one expiry.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strikes (np.ndarray) – strikes.
vols (np.ndarray) – lognormal vols, aligned with strikes.
optiontypes (np.ndarray) – per-strike option types, aligned with strikes.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
- Returns:
prices, aligned with strikes.
- Return type:
np.ndarray
- stochvolmodels.compute_bsm_vanilla_delta(ttm, forward, strike, vol, optiontype, discfactor=1.0)¶
bsm forward delta d(price)/d(forward).
delta = discfactor * N(d1) for a call and -discfactor * N(-d1) for a put, with d1 = log(F/K)/s_ttm + 0.5*s_ttm; below the diffusion floor the digital-limit delta (0 or +/-1) is returned. Inverse types return 0 in the delta sign.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strike (float) – option strike.
vol (float) – lognormal volatility.
optiontype (str) – option type.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
- Returns:
forward delta.
- Return type:
float
- Raises:
NotImplementedError – for unsupported optiontype at the intrinsic boundary.
- stochvolmodels.compute_bsm_vanilla_vega(ttm, forward, strike, vol, discfactor=1.0)¶
bsm vega d(price)/d(vol).
vega = discfactor * F * n(d1) * sqrt(ttm) with d1 = log(F/K)/s_ttm + 0.5*s_ttm; zero below the diffusion floor. The default discfactor=1.0 returns the forward (undiscounted) vega, unchanged from prior releases.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strike (float) – option strike.
vol (float) – lognormal volatility.
discfactor (float, default 1.0) – discount factor exp(-r*ttm); 1.0 gives the undiscounted (forward) vega.
- Returns:
vega.
- Return type:
float
- stochvolmodels.compute_bsm_vanilla_gamma(ttm, forward, strike, vol)¶
bsm forward gamma d^2(price)/d(forward)^2, undiscounted.
gamma = n(d1) / (F * s_ttm) with d1 = log(F/K)/s_ttm + 0.5*s_ttm; zero below the diffusion floor.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strike (float) – option strike.
vol (float) – lognormal volatility.
- Returns:
gamma.
- Return type:
float
- stochvolmodels.compute_bsm_vanilla_theta(ttm, forward, strike, vol, optiontype, discfactor=1.0, discount_rate=0.0)¶
bsm theta d(price)/d(ttm) with spot held fixed, sign-flipped to a decay.
theta = -discfactor * F * n(d1) * vol / (2*sqrt(ttm)) -/+ r * discfactor * K * N(+/-d2), the volatility-decay term minus (call) or plus (put) the rate term; zero below the diffusion floor.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strike (float) – option strike.
vol (float) – lognormal volatility.
optiontype (str) – option type.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
discount_rate (float, default 0.0) – continuously-compounded rate r used in the rate term.
- Returns:
theta.
- Return type:
float
- Raises:
NotImplementedError – if optiontype is not one of ‘C’, ‘P’, ‘IC’, ‘IP’.
- stochvolmodels.compute_bsm_strike_from_delta(ttm, forward, delta, vol)¶
invert a bsm forward delta to the strike that produces it, at fixed vol.
strike = F * exp(-s_ttm * (N^{-1}(delta) - 0.5*s_ttm)) with s_ttm = vol*sqrt(ttm). The refined normal quantile retains near-double-precision accuracy in tail delta grids.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
delta (float) – target forward delta; positive for calls, negative for puts.
vol (float) – lognormal volatility.
- Returns:
strike consistent with delta.
- Return type:
float or np.ndarray
- stochvolmodels.infer_bsm_implied_vol(forward, ttm, strike, given_price, discfactor=1.0, optiontype='C', tol=1e-08, vol_lower=0.01, vol_upper=5.0, max_iters=100, is_bounds_to_nan=True)¶
bsm implied vol from a price, by safeguarded Newton (Newton-Raphson with bisection fallback) on the bracket [vol_lower, vol_upper].
Newton uses the analytic discounted vega d(price)/d(vol) = discfactor*F*n(d1)*sqrt(ttm); a step leaving the bracket, or one that fails to reduce the residual, falls back to bisection. For a vanilla in-the-money option the out-of-the-money counterpart is inverted via put-call parity C - P = discfactor*(F - K) for better conditioning; the implied vol is identical for the two by parity. Typical convergence is 5-8 pricer evaluations; terminal accuracy depends on conditioning, the requested tolerance, and floating-point rounding.
- Parameters:
forward (float) – forward price of the underlying.
ttm (float) – time to maturity, in years.
strike (float) – option strike.
given_price (float) – observed option price to invert.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
optiontype (str, default 'C') – ‘C’/’P’ (parity switch applied) or ‘IC’/’IP’ (inverted directly).
tol (float, default 1e-8) – absolute convergence tolerance on the implied vol.
vol_lower (float, default 0.01) – lower bound of the vol search bracket.
vol_upper (float, default 5.0) – upper bound of the vol search bracket.
max_iters (int, default 100) – maximum solver iterations.
is_bounds_to_nan (bool, default True) – if True, return np.nan when the price is not bracketed (rather than a bound).
- Returns:
implied vol, or np.nan if the price is outside the achievable range and is_bounds_to_nan is True.
- Return type:
float
- stochvolmodels.infer_bsm_ivols_from_slice_prices(ttm, forward, discfactor, strikes, optiontypes, model_prices)¶
bsm implied vols for an aligned slice of prices at one expiry.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
discfactor (float) – discount factor exp(-r*ttm).
strikes (np.ndarray) – strikes.
optiontypes (np.ndarray) – per-strike option types, aligned with strikes.
model_prices (np.ndarray) – prices to invert, aligned with strikes.
- Returns:
implied vols, aligned with strikes.
- Return type:
np.ndarray
Absolute-normal Bachelier analytics¶
- stochvolmodels.compute_normal_price(forward, strike, ttm, vol, discfactor=1.0, optiontype='C')¶
Bachelier (normal) forward price of a vanilla option.
- With sdev = vol*sqrt(ttm) and d = (forward - strike) / sdev:
price = discfactor * ((F - K) * N(d) + sdev * n(d)) for a call price = discfactor * ((F - K) * (N(d) - 1) + sdev * n(d)) for a put
- Parameters:
forward (float) – forward price of the underlying.
strike (float) – option strike.
ttm (float) – time to maturity, in years.
vol (float) – annualised absolute normal volatility, in forward/strike units.
discfactor (float, default 1.0) – discount factor exp(-r*ttm) applied to the forward payoff.
optiontype (str, default 'C') – one of ‘C’, ‘IC’ (call branch) or ‘P’, ‘IP’ (put branch).
- Returns:
option price.
- Return type:
float
- Raises:
NotImplementedError – if optiontype is not one of ‘C’, ‘P’, ‘IC’, ‘IP’.
- stochvolmodels.compute_normal_slice_prices(ttm, forward, strikes, vols, optiontypes, discfactor=1.0)¶
normal prices for an aligned slice of strikes, vols, and optiontypes at one expiry.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strikes (np.ndarray) – strikes.
vols (np.ndarray) – annualised absolute normal vols, aligned with strikes.
optiontypes (np.ndarray) – per-strike option types, aligned with strikes.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
- Returns:
prices, aligned with strikes.
- Return type:
np.ndarray
- stochvolmodels.compute_normal_delta(ttm, forward, strike, vol, optiontype, discfactor=1.0)¶
normal (Bachelier) delta d(price)/d(forward).
With d = (forward - strike) / sdev, delta = discfactor * N(d) for a call and delta = -discfactor * N(-d) for a put.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strike (float) – option strike.
vol (float) – annualised absolute normal volatility.
optiontype (str) – ‘C’ or ‘P’.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
- Returns:
normal delta; np.nan for unsupported optiontype.
- Return type:
float
- stochvolmodels.compute_normal_delta_to_strike(ttm, forward, delta, vol)¶
invert a normal delta to the strike that produces it, at fixed vol.
Using strike = forward - sdev * N^{-1}(delta) with sdev = vol*sqrt(ttm); the put branch uses N^{-1}(1 + delta) = -N^{-1}(abs(delta)) by quantile symmetry.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
delta (float) – target normal delta; positive for calls, negative for puts.
vol (float) – annualised absolute normal volatility.
- Returns:
strike consistent with delta.
- Return type:
float or np.ndarray
- stochvolmodels.compute_normal_slice_vegas(ttm, forward, strikes, vols, optiontypes=None)¶
normal vegas for an aligned slice of strikes and vols.
Derivative of the normal price with respect to the absolute vol: vega = n(d) * sqrt(ttm) with d = (forward - strikes) / sdev (undiscounted; multiply by discfactor for d(price)/d(vol)).
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
strikes (np.ndarray) – strikes.
vols (np.ndarray) – annualised absolute normal vols, aligned with strikes.
optiontypes (np.ndarray, optional) – unused; vega is optiontype-independent. Kept for signature symmetry.
- Returns:
normal vegas, aligned with strikes.
- Return type:
np.ndarray
- stochvolmodels.infer_normal_implied_vol(forward, ttm, strike, given_price, discfactor=1.0, optiontype='C', tol=1e-08, vol_lower=1e-08, vol_upper=10000.0, max_iters=100, is_bounds_to_nan=True)¶
absolute normal implied vol from a price, by safeguarded Newton (Newton-Raphson with bisection fallback) on the bracket [vol_lower, vol_upper].
Newton uses the analytic normal vega d(price)/d(vol) = discfactor*n(d)*sqrt(ttm); a step leaving the bracket, or one that fails to reduce the residual, falls back to bisection. For a vanilla in-the-money option the out-of-the-money counterpart is inverted via put-call parity C - P = discfactor*(F - K) for better conditioning; the implied vol is identical for the two by parity. Terminal accuracy depends on conditioning, the requested tolerance, and floating-point rounding.
- Parameters:
forward (float) – forward price of the underlying.
ttm (float) – time to maturity, in years.
strike (float) – option strike.
given_price (float) – observed option price to invert.
discfactor (float, default 1.0) – discount factor exp(-r*ttm).
optiontype (str, default 'C') – ‘C’/’P’ (parity switch applied) or ‘IC’/’IP’ (inverted directly).
tol (float, default 1e-8) – absolute convergence tolerance on the implied vol.
vol_lower (float, default 1e-8) – lower bound of the absolute-vol search bracket.
vol_upper (float, default 1e4) – upper bound of the absolute-vol search bracket.
max_iters (int, default 100) – maximum solver iterations.
is_bounds_to_nan (bool, default True) – if True, return np.nan when the price is not bracketed (rather than a bound).
- Returns:
absolute normal implied vol, or np.nan if the price is outside the achievable range and is_bounds_to_nan is True.
- Return type:
float
- stochvolmodels.infer_normal_ivols_from_slice_prices(ttm, forward, discfactor, strikes, optiontypes, model_prices)¶
absolute normal implied vols for an aligned slice of prices at one expiry.
Alias of infer_normal_ivols_from_model_slice_prices with the discfactor-first argument order used by the chain-level helpers.
- Parameters:
ttm (float) – time to maturity, in years.
forward (float) – forward price of the underlying.
discfactor (float) – discount factor exp(-r*ttm).
strikes (np.ndarray) – strikes.
optiontypes (np.ndarray) – per-strike option types, aligned with strikes.
model_prices (np.ndarray) – prices to invert, aligned with strikes.
- Returns:
absolute normal implied vols, aligned with strikes.
- Return type:
np.ndarray
Monte Carlo simulation schemes¶
Explained in Monte Carlo simulation schemes. These are advanced names: they draw the random numbers once from a seeded local generator and reuse them across valuations.
- stochvolmodels.get_randoms_for_chain_valuation(ttms, nb_path=100000, nb_steps_per_year=360, seed=10)¶
Draw fixed random normals for Monte Carlo chain valuation.
A local legacy NumPy generator owns the seed, so repeated calls replay the same arrays without mutating NumPy’s process-global random state.
- Parameters:
ttms (ndarray)
nb_path (int)
nb_steps_per_year (int)
seed (int)
- Return type:
Tuple[List[ndarray], List[ndarray], List[ndarray]]
- stochvolmodels.get_randoms_for_rough_vol_chain_valuation(ttms, nb_path=100000, nb_steps_per_year=360, seed=10)¶
draw the Brownian increments for the rough-kernel chain valuation.
Returns the two increment arrays and the per-maturity time grids, so that the same randoms are reused across calibration iterations.
- Parameters:
ttms (ndarray)
nb_path (int)
nb_steps_per_year (int)
seed (int)
- Return type:
Tuple[ndarray, ndarray, List[ndarray]]
- stochvolmodels.logsv_mc_chain_pricer_fixed_randoms(ttms, forwards, discfactors, strikes_ttms, optiontypes_ttms, W0s, W1s, dts, v0, theta, kappa1, kappa2, beta, volvol, vol_backbone_etas, is_spot_measure=True, variable_type=VariableType.LOG_RETURN)¶
chain valuation using fixed randoms
- Parameters:
ttms (ndarray)
forwards (ndarray)
discfactors (ndarray)
strikes_ttms (Tuple[ndarray, ...])
optiontypes_ttms (Tuple[ndarray, ...])
W0s (Tuple[ndarray, ...])
W1s (Tuple[ndarray, ...])
dts (Tuple[ndarray, ...])
v0 (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
volvol (float)
vol_backbone_etas (ndarray)
is_spot_measure (bool)
variable_type (VariableType)
- Return type:
Tuple[List[ndarray], List[ndarray]]
- stochvolmodels.rough_logsv_mc_chain_pricer_fixed_randoms(ttms, forwards, discfactors, strikes_ttms, optiontypes_ttms, Z0, Z1, sigma0, theta, kappa1, kappa2, beta, orthog_vol, weights, nodes, timegrids, variable_type=VariableType.LOG_RETURN, debug=False)¶
Price a rough-LogSV option chain using caller-supplied Gaussian draws.
This experimental routine preserves identical random inputs across parameter evaluations, which is useful for calibration diagnostics.
- Parameters:
ttms (ndarray)
forwards (ndarray)
discfactors (ndarray)
strikes_ttms (Tuple[ndarray, ...])
optiontypes_ttms (Tuple[ndarray, ...])
Z0 (ndarray)
Z1 (ndarray)
sigma0 (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (float)
orthog_vol (float)
weights (ndarray)
nodes (ndarray)
timegrids (List[ndarray])
variable_type (VariableType)
debug (bool)
- Return type:
Tuple[List[ndarray], List[ndarray]]
Calibration to implied volatilities¶
Explained in Calibration to implied volatilities. ConstraintsType is
explained with the martingale conditions above.
- class stochvolmodels.LogsvModelCalibrationType(*values)¶
which model parameters the calibration solves for.
PARAMS4 is the setup of Sec. 6.2, where kappa1 and kappa2 are estimated beforehand from the volatility autocorrelation and held fixed; the article reports kappa1 = 2.21 and kappa2 = 2.18 for Bitcoin.
- class stochvolmodels.CalibrationEngine(*values)¶
how model implied volatilities are produced inside the calibration objective.
ANALYTIC uses the affine expansion of Sec. 4; MC and ROUGH_MC use simulation with randoms fixed across the optimizer’s iterations.
- exception stochvolmodels.CalibrationError¶
Raised when an optimizer cannot produce a usable calibration result.
The Heston model as a benchmark¶
Explained in The Heston model as a benchmark.
- class stochvolmodels.HestonParams(v0=0.04, theta=0.04, kappa=4.0, rho=-0.5, volvol=0.4)¶
parameters of the Heston model.
Variance follows dv = kappa (theta - v) dt + volvol sqrt(v) dW, with rho the return-variance correlation. The Feller condition 2 kappa theta >= volvol^2 keeps the variance away from zero; it is exposed as a calibration constraint rather than enforced here.
- Parameters:
v0 (float)
theta (float)
kappa (float)
rho (float)
volvol (float)
- class stochvolmodels.HestonPricer¶
ModelPricer for the Heston model, valued by Fourier inversion of the analytic MGF.
- calibrate_model_params_to_chain(option_chain, params0=None, is_vega_weighted=True, is_unit_ttm_vega=False, **kwargs)¶
implementation of model calibration interface fit: (theta, kappa, rho, volvol) v0 is inferred using atm_vol and approximation (todo)
- Parameters:
option_chain (OptionChain)
params0 (HestonParams)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
- Return type:
- compute_chain_prices_with_vols(option_chain, params, variable_type=VariableType.LOG_RETURN, **kwargs)¶
price chain and compute model vols
- Parameters:
option_chain (OptionChain)
params (ModelParams)
variable_type (VariableType)
- Return type:
Tuple[List[ndarray], List[ndarray]]
- model_mc_price_chain(option_chain, params, nb_path=100000, variable_type=VariableType.LOG_RETURN, **kwargs)¶
implementation of usinf wrapper for heston_mc_chain_pricer
- Parameters:
option_chain (OptionChain)
params (HestonParams)
nb_path (int)
variable_type (VariableType)
- Return type:
(numba.typed.typedlist.List[numpy.ndarray], numba.typed.typedlist.List[numpy.ndarray])
- price_chain(option_chain, params, **kwargs)¶
implementation of generic method price_chain using heston wrapper for heston chain
- Parameters:
option_chain (OptionChain)
params (HestonParams)
- Return type:
ndarray
- price_slice(params, ttm, forward, strikes, optiontypes, discfactor=1.0, **kwargs)¶
price single slice_t using model chain pricer return price slices and model implied vols
- Parameters:
params (ModelParams)
ttm (float)
forward (float)
strikes (ndarray)
optiontypes (ndarray)
discfactor (float)
- Return type:
Tuple[ndarray, ndarray]
- price_vanilla(params, ttm, forward, strike, optiontype, discfactor=1.0, **kwargs)¶
price single option using slice_t pricer return price and model implied vol
- Parameters:
params (ModelParams)
ttm (float)
forward (float)
strike (float)
optiontype (str)
discfactor (float)
- Return type:
Tuple[float, float]
Jump-diffusion with clustered jumps¶
Explained in Jump-diffusion with clustered jumps. These are advanced names.
- class stochvolmodels.HawkesJDParams(mu=0.0, sigma=0.45, shift_p=0.06, mean_p=0.03, shift_m=-0.06, mean_m=-0.03, lambda_p=6.55, theta_p=6.55, kappa_p=22.29, beta1_p=76.0, beta2_p=-67.58, lambda_m=8.5, theta_m=8.5, kappa_m=29.0, beta1_m=104.55, beta2_m=-109.6, risk_premia_gamma=None)¶
parameters of 2-factor Hawkes Jump Diffusion annualized params, close for BTC on daily frequency
- Parameters:
mu (float)
sigma (float)
shift_p (float)
mean_p (float)
shift_m (float)
mean_m (float)
lambda_p (float)
theta_p (float)
kappa_p (float)
beta1_p (float)
beta2_p (float)
lambda_m (float)
theta_m (float)
kappa_m (float)
beta1_m (float)
beta2_m (float)
risk_premia_gamma (float)
- property exp_jump_m: float¶
expected negative jump size, shift_m + mean_m.
- property exp_jump_p: float¶
expected positive jump size, shift_p + mean_p for a shifted exponential.
- property jump1_cond: float¶
stationarity margin of the positive-jump intensity.
Returns kappa_p - beta1_p E[J_p] - beta2_p E[J_m]. The intensity is stationary while this is positive: decay must outpace the excitation contributed by both jump streams. Used as a calibration constraint, not enforced on construction.
- property jump2_cond: float¶
stationarity margin of the negative-jump intensity, the mirror of jump1_cond.
- property jumps_var_m: float¶
second moment of the negative jump size, shift_m^2 + mean_m^2.
- property jumps_var_p: float¶
second moment of the positive jump size, shift_p^2 + mean_p^2.
- print()¶
print the parameters, for interactive inspection.
- Return type:
None
- to_dict()¶
return the parameters as a plain dict.
- Return type:
Dict[str, Any]
- class stochvolmodels.HawkesJDPricer¶
ModelPricer for the Hawkes jump-diffusion model.
- calibrate_model_params_to_chain(option_chain, params0, is_vega_weighted=True, is_unit_ttm_vega=False, **kwargs)¶
implementation of model calibration interface fit: sigma, mean_p, mean_m, theta_p, theta_m, kappa, (=kappa_p, kappa_m), beta_p (=beta1_p, beta2_p), beta_m (=beta1_m, beta2_m) use fixed shift_p, shift_m, lambda_p, lambda_m
- Parameters:
option_chain (OptionChain)
params0 (HawkesJDParams)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
- Return type:
- model_mc_price_chain(option_chain, params, nb_path=100000, **kwargs)¶
price an option chain by Monte Carlo rather than the analytic solution.
- Parameters:
option_chain (OptionChain)
params (HawkesJDParams)
nb_path (int)
- Return type:
(numba.typed.typedlist.List[numpy.ndarray], numba.typed.typedlist.List[numpy.ndarray])
- price_chain(option_chain, params, is_spot_measure=True, **kwargs)¶
implementation of generic method price_chain using log sv wrapper
- Parameters:
option_chain (OptionChain)
params (HawkesJDParams)
is_spot_measure (bool)
- Return type:
List[ndarray]
Gaussian-mixture and Student-t smiles¶
Explained in Gaussian-mixture and Student-t smiles.
- class stochvolmodels.GmmParams(gmm_weights, gmm_mus, gmm_vols, ttm)¶
parameters of a Gaussian mixture model for terminal log-returns.
The terminal density is a weighted sum of normals, one per state, each with its own drift and volatility. Weights sum to one and the mixture must reprice the forward, which are the two equality constraints imposed during calibration.
- Parameters:
gmm_weights (ndarray)
gmm_mus (ndarray)
gmm_vols (ndarray)
ttm (float)
- compute_pdf(x)¶
aggregate mixture density on a log-return grid.
- Parameters:
x (ndarray)
- compute_state_pdfs(x)¶
per-state densities and their weighted aggregate on a log-return grid.
- Parameters:
x (ndarray)
- Return type:
Tuple[ndarray, ndarray]
- get_get_avg_vol()¶
weight-averaged volatility, sqrt(sum w_i vol_i^2).
- Return type:
float
- sort_by_mus()¶
order the mixture states by drift, so fitted states stay comparable across slices.
- class stochvolmodels.GmmPricer¶
ModelPricer valuing options as a weighted sum of Black-Scholes prices.
- calibrate_model_params_to_chain(option_chain, is_vega_weighted=True, is_unit_ttm_vega=False, n_mixtures=4, **kwargs)¶
model params are fitted per slice need to splic chain to slices
- Parameters:
option_chain (OptionChain)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
n_mixtures (int)
- Return type:
List[str, GmmParams]
- calibrate_model_params_to_chain_slice(option_chain, params0=None, is_vega_weighted=True, is_unit_ttm_vega=False, n_mixtures=4, **kwargs)¶
implementation of model calibration interface fit: GmmParams nb: always use option_chain with one slice because we need martingale condition per slice
- Parameters:
option_chain (OptionChain)
params0 (GmmParams)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
n_mixtures (int)
- Return type:
- model_mc_price_chain(option_chain, params, nb_path=100000, variable_type=VariableType.LOG_RETURN, **kwargs)¶
price an option chain by Monte Carlo rather than the analytic solution.
- Parameters:
option_chain (OptionChain)
params (GmmParams)
nb_path (int)
variable_type (VariableType)
- Return type:
(numba.typed.typedlist.List[numpy.ndarray], numba.typed.typedlist.List[numpy.ndarray])
- price_chain(option_chain, params, **kwargs)¶
implementation of generic method price_chain using heston wrapper for heston chain
- Parameters:
option_chain (OptionChain)
params (GmmParams)
- Return type:
ndarray
- class stochvolmodels.TdistParams(drift, vol, nu, ttm)¶
parameters of the Student-t model: volatility, drift and degrees of freedom nu.
The centered arithmetic-return shock is Student-t with nu > 2 and variance
vol**2 * ttm. The terminal asset is the positive part of spot times one plus drift times maturity plus that shock, so the floor creates an atom at zero.- Parameters:
drift (float)
vol (float)
nu (float)
ttm (float)
- class stochvolmodels.TdistPricer¶
ModelPricer valuing options under a Student-t terminal distribution.
- calibrate_model_params_to_chain(option_chain, is_vega_weighted=True, is_unit_ttm_vega=False, **kwargs)¶
model params are fitted per slice need to splic chain to slices
- Parameters:
option_chain (OptionChain)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
- Return type:
List[str, TdistParams]
- calibrate_model_params_to_chain_slice(option_chain, params0=None, is_vega_weighted=True, is_unit_ttm_vega=False, **kwargs)¶
implementation of model calibration interface fit: TdistParams nb: always use option_chain with one slice because we need martingale condition per slice
- Parameters:
option_chain (OptionChain)
params0 (TdistParams)
is_vega_weighted (bool)
is_unit_ttm_vega (bool)
- Return type:
- model_mc_price_chain(option_chain, params, nb_path=100000, variable_type=VariableType.LOG_RETURN, **kwargs)¶
price an option chain by Monte Carlo rather than the analytic solution.
- Parameters:
option_chain (OptionChain)
params (TdistParams)
nb_path (int)
variable_type (VariableType)
- Return type:
(numba.typed.typedlist.List[numpy.ndarray], numba.typed.typedlist.List[numpy.ndarray])
- price_chain(option_chain, params, **kwargs)¶
Price all chain slices through the legacy closed-form Student-t kernel.
- Parameters:
option_chain (OptionChain)
params (TdistParams)
- Return type:
ndarray
Stochastic volatility for factor HJM rates¶
Explained in Stochastic volatility for factor HJM rates, with
the case study USD swaptions and SOFR futures options. These
names are reached by deep imports from the experimental stochvolmodels.pricers.factor_hjm package.
- class stochvolmodels.pricers.factor_hjm.rate_factor_basis.NelsonSiegel(meanrev, key_terms)¶
Nelson-Siegel basis of Sec. 2.3.
Three main factors with basis [1, exp(-lambda tau), tau exp(-lambda tau)], interpreted as level, slope and curvature, and the auxiliary basis generated by the spectrum of Eq. (24).
key_termsfixes the tenors at which the basis is estimated, per Sec. 7.4.- Parameters:
meanrev (float)
key_terms (ndarray)
- annuity(t, ts_sw, x, y, ccy, m=0)¶
annuity of a swap schedule, the numeraire of the measure Q^A in Sec. 3.1.
- Parameters:
t (float)
ts_sw (ndarray)
x (ndarray)
y (ndarray)
ccy (str)
m (int)
- Return type:
ndarray
- bond(t, T, x, y, ccy, m=0)¶
zero-coupon bond price of Eq. (15) given the factor state.
- Parameters:
t (float)
T (float)
x (ndarray)
y (ndarray)
ccy (str)
m (int)
- Return type:
ndarray
- swap_rate(t, ts_sw, x, y, ccy)¶
par swap rate of Eq. (28), the floating leg over the annuity.
- Parameters:
t (float)
ts_sw (ndarray)
x (ndarray)
y (ndarray)
ccy (str)
- Return type:
(<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)
- class stochvolmodels.pricers.factor_hjm.rate_logsv_params.MultiFactRateLogSvParams(sigma0, theta, kappa1, kappa2, beta, volvol, A, R, basis, ccy, vol_interpolation='DIRECT', q=None)¶
Implementation of model params class for multi-factor model
- Parameters:
sigma0 (float)
theta (float)
kappa1 (float)
kappa2 (float)
beta (TermStructure)
volvol (TermStructure)
A (ndarray)
R (ndarray)
basis (NelsonSiegel | CheyettePEND)
ccy (str)
vol_interpolation (str)
q (float)
- check_QA_kappa2(expiry, tenor)¶
check the quadratic mean-reversion bound under the annuity measure.
The regularity condition on the moments of the SV driver; the measure change of Theorem 3.1 shifts the quadratic coefficient, so the bound must be verified in the transformed parameters rather than the original ones.
- Parameters:
expiry (float)
tenor (float)
- Return type:
bool
- check_QT_kappa2(t_start, t_end=None)¶
check the quadratic mean-reversion bound under the T-forward measure.
- Parameters:
t_start (float)
t_end (float)
- Return type:
bool
- reduce(ids)¶
restrict the term structure or parameter set to a subset of tenors.
- Parameters:
ids (List[str])
- transform_QA_params(expiry, tenor, t_grid, x0=None, y0=None)¶
Calculate a, kappa_0, kappa_1, kappa_2, beta, volvol under Q^A for multi-factor model at times t_grid
- Parameters:
expiry (float)
tenor (float)
t_grid (ndarray)
x0 (ndarray)
y0 (ndarray)
- Return type:
Tuple[ndarray, …]
- update_params(idx, A_idx=None, beta_idx=None, volvol_idx=None, kappa1=None, kappa2=None, sigma0=None)¶
return a copy with the given parameters replaced.
- Parameters:
idx (int)
A_idx (ndarray)
beta_idx (ndarray)
volvol_idx (float)
kappa1 (float)
kappa2 (float)
sigma0 (float)
- stochvolmodels.pricers.factor_hjm.rate_logsv_pricer.logsv_chain_de_pricer(params, t_grid, ttms, forwards, strikes_ttms, optiontypes_ttms, is_stiff_solver=False, underlying_type=UnderlyingType.SWAP, is_analytic=False, is_spot_measure=True, expansion_order=ExpansionOrder.SECOND, vol_scaler=None, do_control_variate=False, x0=None, y0=None, **kwargs)¶
price an option chain by double-exponential quadrature of the inversion integral.
Sec. 7.2, Eqs. (121) and (122).
- Parameters:
params (MultiFactRateLogSvParams)
t_grid (ndarray)
ttms (ndarray)
forwards (List[ndarray])
strikes_ttms (List[List[ndarray]])
optiontypes_ttms (List[ndarray])
is_stiff_solver (bool)
underlying_type (UnderlyingType)
is_analytic (bool)
is_spot_measure (bool)
expansion_order (ExpansionOrder)
vol_scaler (float)
x0 (ndarray)
y0 (ndarray)
- Return type:
Tuple[List[ndarray], List[ndarray]]
- stochvolmodels.pricers.factor_hjm.factor_hjm_pricer.calc_mc_vols(basis_type, params, ttm, tenors, forwards, strikes_ttms, optiontypes, is_annuity_measure, nb_path, x0=None, y0=None, sigma0=None, I0=None, seed=None, x_in_delta_space=False)¶
invert simulated option prices to Black or normal implied volatilities.
- Parameters:
basis_type (str)
params (MultiFactRateLogSvParams)
ttm (float)
tenors (ndarray)
forwards (List[ndarray])
strikes_ttms (List[List[ndarray]])
optiontypes (ndarray)
is_annuity_measure (bool)
nb_path (int)
x0 (ndarray)
y0 (ndarray)
sigma0 (ndarray)
I0 (ndarray)
seed (int)
x_in_delta_space (bool)
- Return type:
(numba.typed.typedlist.List[numpy.ndarray], numba.typed.typedlist.List[numpy.ndarray])
Provisional and experimental surfaces¶
The software design page says which of these surfaces have no article yet, and why.
The following direct-module APIs ship in the wheel but are intentionally absent from the stable
package-root __all__. They support the repository’s volatility-book analytics and may be refined
after validation across additional model implementations:
stochvolmodels.data.model_paths.ModelPathsis the validated path payload.stochvolmodels.models.PathModelandTransformModeldescribe independent dynamic capabilities.stochvolmodels.models.logsv.LogSvModelandstochvolmodels.models.tgarch.TgarchModelare the first path implementations.stochvolmodels.models.TerminalDistributionModelandTerminalSmileModeldescribe one-maturity laws and smiles separately from path models. Implementations arestochvolmodels.pricers.tdist_pricer.TdistTerminalModel,stochvolmodels.pricers.gmm_pricer.GmmTerminalModel, andstochvolmodels.models.inverse_gamma_normal.InverseGammaNormalTerminalModel.stochvolmodels.products.payoffsprovidesEuropeanOptionPayoffandIntegratedVarianceOptionPayoff.stochvolmodels.valuationprovides raw and self-normalized path valuation with explicit measure, likelihood-weight, recentering, standard-error, and ESS policies.stochvolmodels.models.regime_logsv,stochvolmodels.models.regime_logsv_simulation, andstochvolmodels.pricers.regime_switch_logsv_pricerprovide the provisional regime-switching LogSV equilibrium, transform, Fourier, and independent Monte Carlo stack.
Student-t and GMM validate the terminal boundary without being made into artificial path models. Root aliases and protocol stabilization are deferred until the same contracts have been exercised by another dynamic model.
The deep modules stochvolmodels.pricers.rough_logsv and stochvolmodels.pricers.factor_hjm are
experimental research surfaces that may evolve between minor releases; the second is explained in
Stochastic volatility for factor HJM rates. The removed
stochvolmodels.pricers.analytic.bsm and stochvolmodels.pricers.analytic.bachelier paths are not
compatibility facades in 2.0.
OHLC volatility estimation¶
OHLC estimators operate only on price-bar data and have no market-data-provider dependency.
Statistical estimators used with stochastic-volatility models.
- class stochvolmodels.estimation.ForecastHorizon(label, periods)¶
Number of observation periods represented by a named forecast horizon.
- Parameters:
label (str) – Human-readable horizon label, such as
"1d"or"1m".periods (int) – Strictly positive number of input observation periods in the horizon.
- class stochvolmodels.estimation.OhlcEstimatorType(*values)¶
Supported estimators of per-bar variance from OHLC observations.
- class stochvolmodels.estimation.VolForecastComparison(model, benchmark_model, horizon, n_obs, volatility_rmse_gain, volatility_mae_gain, absolute_volatility_bias_gain, variance_mse_gain, variance_qlike_gain)¶
Loss reductions versus one benchmark on exactly the same observations.
Positive gains indicate that the forecast has a lower loss than the benchmark. Bias is compared in absolute value.
- Parameters:
model (VolatilityForecastModel)
benchmark_model (VolatilityForecastModel)
horizon (ForecastHorizon)
n_obs (int)
volatility_rmse_gain (float)
volatility_mae_gain (float)
absolute_volatility_bias_gain (float)
variance_mse_gain (float)
variance_qlike_gain (float)
- class stochvolmodels.estimation.VolForecastConfig(feature_names=(), forecast_space='volatility', ewma_decay=0.94)¶
Model feature and quotation conventions.
- Parameters:
feature_names (tuple[str, ...]) – Ordered features consumed by the selected model. The expanding mean uses no features, persistence and EWMA use one, HAR uses three, and pooled OHLC NNLS uses one or more.
forecast_space (Literal['volatility', 'variance']) – Units shared by the target and selected features. HAR is defined in annualised variance and pooled OHLC NNLS in annualised volatility.
ewma_decay (float) – Weight on the preceding EWMA state. The default
0.94is fixed; any tuning must be performed inside the caller’s training window.
- class stochvolmodels.estimation.VolForecastEvaluation(model, horizon, n_obs, volatility_rmse, volatility_mae, volatility_bias, variance_mse, variance_qlike)¶
Common-sample forecast losses for one model and horizon.
- Parameters:
model (VolatilityForecastModel)
horizon (ForecastHorizon)
n_obs (int)
volatility_rmse (float)
volatility_mae (float)
volatility_bias (float)
variance_mse (float)
variance_qlike (float)
- class stochvolmodels.estimation.VolForecastFit(model, config, intercept, coefficients, training_start, training_end, n_obs, target_name, residual_sum_squares, ewma_state=None)¶
Immutable fitted state and diagnostics for one forecast model.
- Parameters:
model (VolatilityForecastModel)
config (VolForecastConfig)
intercept (float)
coefficients (tuple[float, ...])
training_start (Timestamp)
training_end (Timestamp)
n_obs (int)
target_name (str | None)
residual_sum_squares (float)
ewma_state (float | None)
- coefficient_series()¶
Return a new labelled coefficient series.
- Return type:
Series
- class stochvolmodels.estimation.VolForecastPrediction(model, forecast_space, origins, predicted_values, origin_name=None, origin_frequency=None)¶
Immutable forecasts indexed by their information times.
- Parameters:
model (VolatilityForecastModel)
forecast_space (Literal['volatility', 'variance'])
origins (tuple[Timestamp, ...])
predicted_values (tuple[float, ...])
origin_name (str | None)
origin_frequency (str | None)
- to_frame()¶
Return annualised predicted variance and volatility in decimal units.
- Return type:
DataFrame
- to_series()¶
Return forecasts in their fitted space as a new series.
- Return type:
Series
- class stochvolmodels.estimation.VolForecastResult(model, config, horizon, annualization_factor, min_train_size, refit_every, window, origins, target_starts, target_ends, predicted_variances, predicted_volatilities, realized_variances, realized_volatilities, refit_ids, training_starts, training_ends, training_n_obs, fits, refit_origins, origin_name=None, origin_frequency=None)¶
Immutable per-origin forecasts and per-refit diagnostics.
- Parameters:
model (VolatilityForecastModel)
config (VolForecastConfig)
horizon (ForecastHorizon)
annualization_factor (float)
min_train_size (int)
refit_every (int)
window (int | None)
origins (tuple[Timestamp, ...])
target_starts (tuple[Timestamp | None, ...])
target_ends (tuple[Timestamp | None, ...])
predicted_variances (tuple[float, ...])
predicted_volatilities (tuple[float, ...])
realized_variances (tuple[float, ...])
realized_volatilities (tuple[float, ...])
refit_ids (tuple[int | None, ...])
training_starts (tuple[Timestamp | None, ...])
training_ends (tuple[Timestamp | None, ...])
training_n_obs (tuple[int | None, ...])
fits (tuple[VolForecastFit, ...])
refit_origins (tuple[Timestamp, ...])
origin_name (str | None)
origin_frequency (str | None)
- fit_diagnostics()¶
Return one row of parameters and diagnostics per refit.
- Return type:
DataFrame
- to_frame()¶
Return forecasts, realized targets, and active-fit metadata.
- Return type:
DataFrame
- class stochvolmodels.estimation.VolatilityForecastModel(*values)¶
Initial point-in-time volatility forecast model family.
- stochvolmodels.estimation.build_volatility_features(per_period_variances, adjusted_returns=None, windows=(1, 5, 21), lags=(1,), annualization_factor=252.0, feature_space='volatility')¶
Build annualised current, lagged, mean, LWMA and leverage features.
Every feature at time
tuses observations at or beforet. Current estimator values represent the one-period window; additional rolling means and linearly weighted moving averages are produced for windows greater than one. Linear weights increase from one for the oldest observation to the window length for the most recent observation.- Parameters:
per_period_variances (DataFrame) – Non-negative per-period variance measures on a unique, increasing
DatetimeIndex. Columns identify the estimators.adjusted_returns (Series | None) – Optional adjusted close-to-close log returns on exactly the same index. Their negative part is included as a non-negative leverage feature.
windows (Sequence[int]) – Positive, unique rolling windows. A window of one is represented by the current feature and is not duplicated as a rolling feature.
lags (Sequence[int]) – Positive, unique lags added for every variance measure. May be empty.
annualization_factor (float) – Strictly positive number of input periods per year.
feature_space (Literal['volatility', 'variance']) –
"volatility"returns square roots of annualised variance features;"variance"keeps them in annualised variance units.
- Returns:
Point-in-time numerical feature panel on the input index.
- Return type:
pandas.DataFrame
- stochvolmodels.estimation.compare_volatility_forecasts(result, benchmark, variance_floor=1e-12)¶
Compare two forecasts on their exact common set of valid origins.
- Parameters:
result (VolForecastResult)
benchmark (VolForecastResult)
variance_floor (float)
- Return type:
- stochvolmodels.estimation.estimate_hf_ohlc_vol(ohlc_data, ohlc_estimator_type=OhlcEstimatorType.PARKINSON, annualization_factor=None, is_exclude_weekends=False, agg_freq='B')¶
Estimate annualised volatility from OHLC bars.
The estimator is evaluated per input bar. Variances are then averaged to
agg_freqbefore annualisation.- Parameters:
ohlc_data (DataFrame) – Price bars with lower-case
open,high,lowandclosecolumns.ohlc_estimator_type (OhlcEstimatorType) – Estimator applied to each bar.
annualization_factor (float | None) – Periods per year. If omitted, infer it from the output index.
is_exclude_weekends (bool) – Remove Saturdays and Sundays from the returned series.
agg_freq (str | None) – Pandas frequency used to average per-bar variances.
Nonekeeps the input frequency.
- Returns:
Annualised volatility at the aggregation frequency.
- Return type:
pandas.Series
- stochvolmodels.estimation.estimate_ohlc_var(ohlc_data, ohlc_estimator_type=OhlcEstimatorType.PARKINSON, min_size=2)¶
Estimate per-bar variance from open, high, low and close prices.
- Parameters:
ohlc_data (DataFrame) – Price bars with lower-case
open,high,lowandclosecolumns.ohlc_estimator_type (OhlcEstimatorType) – Estimator applied to each bar.
min_size (int) – Minimum number of rows required. Shorter inputs return
numpy.nan.
- Returns:
Per-bar variance in log-price units, or
numpy.nanfor insufficient data.- Return type:
pandas.Series or float
- stochvolmodels.estimation.estimate_ohlc_variances(ohlc_data, ohlc_estimator_types=None, min_size=2)¶
Estimate a consistently named panel of per-bar OHLC variances.
- Parameters:
ohlc_data (DataFrame) – Price bars with lower-case
open,high,lowandclosecolumns.ohlc_estimator_types (Sequence[OhlcEstimatorType] | None) – Ordered estimators to include.
Noneincludes every supported estimator.min_size (int) – Minimum number of rows required by each estimator.
- Returns:
Per-bar variances in log-price units. Columns use lower-case estimator names.
- Return type:
pandas.DataFrame
- stochvolmodels.estimation.evaluate_volatility_forecast(result, variance_floor=1e-12)¶
Evaluate one forecast on rows with complete predictions and targets.
QLIKE uses
r - log(r) - 1with the ratio of realized to predicted annualised variance. The caller-supplied positive floor is applied only for this mathematically positive-domain loss.- Parameters:
result (VolForecastResult)
variance_floor (float)
- Return type:
- stochvolmodels.estimation.fit_volatility_forecaster(features, target, model, config=None)¶
Fit one volatility forecast model on an already eligible training window.
Missing rows are removed by complete-case selection over the target and the model’s requested features. The caller remains responsible for supplying only targets whose complete forecast intervals are observable at the fit time; horizon-aware purging belongs to the walk-forward layer.
- Parameters:
features (DataFrame) – Point-in-time annualised volatility or variance features.
target (Series) – Non-negative annualised target in the same units as
forecast_space.model (VolatilityForecastModel) – Model family to fit.
config (VolForecastConfig | None) – Feature names, forecast units, and fixed EWMA decay.
- Returns:
Immutable fitted parameters and training diagnostics.
- Return type:
- stochvolmodels.estimation.make_forward_variance_target(per_period_variance, horizon, annualization_factor)¶
Build annualised variance observed strictly after each forecast origin.
For an origin at position
tand a horizon ofhperiods, the target isannualization_factor * mean(v[t + 1], ..., v[t + h]).The series is indexed by the information time
t. The finalhrows are missing because their complete forward intervals are not yet observable.- Parameters:
per_period_variance (Series) – Non-negative variance observations on a unique, increasing datetime index. Values are expressed in per-period log-return variance units.
horizon (ForecastHorizon) – Named number of future observation periods included in each target.
annualization_factor (float) – Strictly positive number of input periods per year.
- Returns:
Annualised forward variance indexed by forecast origin.
- Return type:
pandas.Series
- stochvolmodels.estimation.make_forward_volatility_target(per_period_variance, horizon, annualization_factor)¶
Build annualised volatility observed strictly after each forecast origin.
Variance is averaged over the complete forward interval and annualised before taking its square root. The timestamp and missing-value conventions are the same as for
make_forward_variance_target().- Parameters:
per_period_variance (Series) – Non-negative variance observations on a unique, increasing datetime index.
horizon (ForecastHorizon) – Named number of future observation periods included in each target.
annualization_factor (float) – Strictly positive number of input periods per year.
- Returns:
Annualised forward volatility in decimal units, indexed by forecast origin.
- Return type:
pandas.Series
- stochvolmodels.estimation.predict_volatility_forecaster(fit, features)¶
Predict from one immutable fit and return variance and volatility views.
EWMA prediction rows must be strictly after the fitted training window and are processed in order. Each forecast incorporates the selected feature at that information time. Other models can be evaluated in or out of sample. Every model’s numerical prediction is floored at zero.
- Parameters:
fit (VolForecastFit)
features (DataFrame)
- Return type:
- stochvolmodels.estimation.walk_forward_volatility_forecast(features, per_period_variance, horizon, model, config=None, annualization_factor=252.0, min_train_size=504, refit_every=21, window=None)¶
Run one horizon-aware, point-in-time volatility forecast.
At forecast origin position
t, the latest eligible training target origin ist - horizon.periods. This guarantees that every variance observation in a training target has completed byt.window=Noneuses all eligible target-origin rows; an integer retains only that many rows before complete-case filtering. Model parameters are refreshed on a fixed observation schedule.- Parameters:
features (DataFrame) – Point-in-time features indexed by completed observation time.
per_period_variance (Series) – Non-negative per-observation variance proxy on exactly the same index.
horizon (ForecastHorizon) – Number of strictly future observations in every realized target.
model (VolatilityForecastModel) – Forecast model fitted separately for this horizon.
config (VolForecastConfig | None) – Model feature names and forecast units.
annualization_factor (float) – Positive number of input observations per year.
min_train_size (int) – Minimum complete observations required at every refit.
refit_every (int) – Number of forecast-origin observations between parameter refits.
window (int | None) – Optional rolling count of eligible target-origin rows.
Nonemeans an expanding estimation window.
- Returns:
Immutable forecasts, realized targets, and per-refit diagnostics.
- Return type:
Approximate LogSV smile utilities¶
Explained in Approximate log-normal SV smile fitter. The
provider-independent utilities under stochvolmodels.fitters support initialization,
diagnostics, and synthetic grids. They are separate from the full transform-based
LogSVPricer.calibrate_model_params_to_chain calibration.
Provider-independent volatility-model fitting utilities.
- stochvolmodels.fitters.calc_logsv_atm_fit(log_strikes, mid_vols, strike_step=0.3)¶
Estimate local ATM LogSV parameters for optimization initialization.
- Parameters:
log_strikes (ndarray)
mid_vols (ndarray)
strike_step (float)
- Return type:
dict[str, float]
- stochvolmodels.fitters.calc_logsv_ivols(log_strikes, sigma0, beta, volvol, is_quadratic=True)¶
Evaluate the approximate zero-mean-reversion LogSV implied-volatility smile.
- Parameters:
log_strikes (float | ndarray)
sigma0 (float)
beta (float)
volvol (float)
is_quadratic (bool)
- Return type:
float | ndarray
- stochvolmodels.fitters.calc_logsv_ivols_partials(log_strikes, sigma0, beta, volvol, eps=0.01, mult=1.0, is_analytic=False)¶
Return smile level and its first two log-strike derivatives.
- Parameters:
log_strikes (ndarray)
sigma0 (float)
beta (float)
volvol (float)
eps (float)
mult (float)
is_analytic (bool)
- Return type:
tuple[ndarray, ndarray, ndarray]
- stochvolmodels.fitters.calc_logsv_pdf(ttm, sigma0, beta, volvol, log_strikes=None, is_norm=False, cut=6.0, is_analytic=False)¶
Compute the approximate LogSV risk-neutral density over log-strike.
When
is_normis true, the returned values are discrete probability masses on a uniformly spaced grid and therefore sum to one.- Parameters:
ttm (float)
sigma0 (float)
beta (float)
volvol (float)
log_strikes (ndarray | None)
is_norm (bool)
cut (float)
is_analytic (bool)
- Return type:
Series
- stochvolmodels.fitters.calc_logsv_pdf_core(ttm, sigma0, beta, volvol, log_strikes=None, is_norm=False, cut=6.0, is_analytic=False)¶
Compute the approximate LogSV density without optional grid normalization.
- Parameters:
ttm (float)
sigma0 (float)
beta (float)
volvol (float)
log_strikes (ndarray | None)
is_norm (bool)
cut (float)
is_analytic (bool)
- Return type:
Series
- stochvolmodels.fitters.fit_logsv_ivols(log_strikes, mid_vols, ttm, is_vega_weights=True)¶
Fit the approximate zero-mean-reversion LogSV implied-volatility smile.
- Parameters:
log_strikes (ndarray)
mid_vols (ndarray)
ttm (float)
is_vega_weights (bool)
- Return type:
dict[str, float]
- stochvolmodels.fitters.generate_grid_option_prices_from_slice(vols, given_log_strikes, log_strike_grid, p0_ref, ttm, vol_addon=None)¶
Fit a LogSV smile and produce undiscounted put/call prices on a grid.
- Parameters:
vols (Series)
given_log_strikes (ndarray)
log_strike_grid (ndarray)
p0_ref (float)
ttm (float)
vol_addon (float | None)
- Return type:
tuple[Series, Series]
- stochvolmodels.fitters.get_pdf_delta_space(forward, ttm, sigma0, beta, volvol, deltas=None, is_remap_to_straddle_delta=True, is_analytic=True)¶
Evaluate the approximate LogSV density on a Black-delta grid.
- Parameters:
forward (float)
ttm (float)
sigma0 (float)
beta (float)
volvol (float)
deltas (ndarray | None)
is_remap_to_straddle_delta (bool)
is_analytic (bool)
- Return type:
Series
- stochvolmodels.fitters.get_vols_delta_space(forward, ttm, sigma0, beta, volvol, deltas=None, is_remap_to_str_delta=True)¶
Evaluate the approximate LogSV smile on a Black-delta grid.
- Parameters:
forward (float)
ttm (float)
sigma0 (float)
beta (float)
volvol (float)
deltas (ndarray | None)
is_remap_to_str_delta (bool)
- Return type:
Series
- stochvolmodels.fitters.infer_strikes_from_deltas(deltas, forward, ttm, sigma0, beta, volvol)¶
Invert Black forward deltas under the approximate LogSV smile.
Positive values denote call deltas and negative values denote put deltas. The root search operates in log-moneyness and ignores regions where the local quadratic smile approximation is non-positive.
- Raises:
ValueError – If inputs are invalid or no positive-volatility root brackets a delta.
- Parameters:
deltas (ndarray)
forward (float)
ttm (float)
sigma0 (float)
beta (float)
volvol (float)
- Return type:
Series
Local resource and output paths¶
stochvolmodels.local_path reads the ignored package-adjacent settings.yaml. Its getters return
absolute, separator-terminated strings for compatibility with the wider qis ecosystem.
Resolve machine-local resource and output directories.
The optional settings.yaml next to this module follows the same two-key
configuration used by the maintainer’s other packages. It is deliberately
ignored by Git and excluded from distributions because it contains
machine-specific absolute paths. A source checkout without the file uses
resources and outputs under the repository root.
Example
Provider subdirectories follow the established QIS-style path convention:
from stochvolmodels import local_path as lp
local_path = f"{lp.get_resource_path()}bbg_vols\"
- stochvolmodels.local_path.get_local_resource_path()¶
Compatibility alias for
get_resource_path().- Return type:
str
- stochvolmodels.local_path.get_output_path()¶
Create and return the output root with a trailing separator.
- Return type:
str
- stochvolmodels.local_path.get_resource_path()¶
Return the configured input-data root with a trailing separator.
- Return type:
str
Parameter maps¶
Each field of the parameter classes, and each keyword of the LogSV calibration, is explained on one page.
LogSvParams fields¶
Field |
Default |
Meaning |
Explained in |
|---|---|---|---|
|
|
Initial volatility |
|
|
|
Mean volatility |
|
|
|
Linear mean-reversion rate |
|
|
|
Quadratic mean-reversion rate; |
|
|
|
Volatility beta |
|
|
|
Volatility of residual volatility |
|
|
|
Term structure of multiplicative scalings of |
|
|
|
Hurst exponent; values below 0.5 select the experimental rough extension |
|
|
|
Rough-kernel quadrature weights, set by |
|
|
|
Rough-kernel quadrature nodes, set by |
HestonParams fields¶
Field |
Default |
Meaning |
Explained in |
|---|---|---|---|
|
|
Initial variance |
|
|
|
Long-run variance |
|
|
|
Mean-reversion rate of the variance |
|
|
|
Correlation of the variance and price shocks |
|
|
|
Volatility of the variance |
LogSVPricer.calibrate_model_params_to_chain keywords¶
Keyword |
Default |
Meaning |
Explained in |
|---|---|---|---|
|
required |
Market chain with bid and ask implied volatilities |
|
|
required |
Starting parameters; fixed fields stay at these values |
|
|
lower box bounds |
Lower bounds of the fitted parameters |
|
|
upper box bounds |
Upper bounds of the fitted parameters |
|
|
|
Weight implied-volatility residuals by vega |
|
|
|
Compute the vegas at unit maturity |
|
|
|
Which parameters are free |
|
|
|
Martingale and moment constraints |
|
|
|
Transform pricer or Monte Carlo inside the objective |
|
|
|
Monte Carlo paths, for the Monte Carlo engines |
|
|
|
Monte Carlo time steps per year, for the Monte Carlo engines |
|
|
|
Seed of the fixed random numbers, for the Monte Carlo engines |