quantdata.sanos.arbfree#
Make arbfree markets#
This module contains MkArbFree, a utility class
has two main modes:
expiry: fits per expiry an arbitrage-free mid price within the bid-ask spread, and drops any expiries for which this is not possible as it implies actionable arbitrage.This is a pre-processor for any benchmark which attempts to fit arbitrage-free models to otherwise arbitrageable data. It is also a useful tool to detect and handle arbitrage in the data, which is a common issue in WIDB data.
surface: fits a fully arbitrage free surface, on a strike grid which theoretically means that a mid-price fit exists if and only if the resulting fit is within bid/ask spread.This function can become very slow.
The MkArbFree.__call__() function returns an ArbFreePricer class which contains the fit to the market and can also compute option
prices for arbitrary strikes and expiries using the fitted model.
Developer note:
A really diffult day for testing (likely very wrong data) is SPX 2005-11-21.*
- class quantdata.sanos.arbfree.ArbFreePricer(smoothness=None)[source]#
Bases:
PrettyObjectArbitrage-Free Option pricer based on DLV/SANOS.
This class contains the result of
MkArbFree.__call__(). This function call may drop expiries if they have arbitrage which cannot be resolved. To map the expiries stored in this class back to the input expiries, use theinput_indexfield.The class attributes are:
expiries: array(T,)of expiries used. This may be fewer expiries than provided as input.input_index: array of size(T,)which maps each returned expiry to the index of the input expiry it corresponds to. In other wordsoutput_expiries == [ input_expiries[j] for j in input_index ].masks: a list ofTboolean masks by expiry indicating which strikes were considered during the no-arb fit.The mask for expory
jhas the same lengthNjas thestrikes[ input_expiries[j] ].The mask is False for strikes which were dropped because they had zero implied density in the per-expiry fit, and for strikes which were dropped because they had too steep bid-ask slopes at the boundaries. The fit minimizes
max( 0, fit[mask] - ask[mask] ) + max( 0, bid[mask] - fit[mask] ).
strikes: a copy of theTinput strike arrays for the expiries used.bids: a copy of theTarrays of input bids for the expiries used.asks: a copy of theTarrays of input asks for the expiries used.fits1: list ofTper-expiry fitted arbitrage-free prices within bid/ask (where masked) for the inputstrikesused. The elementfit1[j]is a vector of lengthstrikes[j]. Within numerical accuracy we havebids[j][mask[j]] <= fit1[j][mask[j]] <= asks[j][mask[j]].fitsX: list ofTsurface fitted arbitrage-free prices for the inputstrikes.These prices are globally arbitrage-free across the surface, but they are not necessarily within bid/ask spread; they are the closest fit among strikes with
maskTrue.Up to machine precision existence of
fitsXwithin bid/ask spread in the linear casesmoothness=0is equivalent to absence of arbitrage.This field is None if
no_arb_modeis “expiry”.
Besides the pure fits, this class also contains the ingredients of the DLV/SANOS model.
For the “expiry”
no_arb_modethe functionMkArbFree.__call__()will generate internal modelxstrikesaround the provided market strikes. For those strikes it will compute axdensitiesper expiry.xstrikes: an extended strike list with two boundary strikes add. Boundary strikes are widening in time; c.f. https://arxiv.org/pdf/2601.11209 remark 2.7.xdensities: list of densities forxstrikes, per expiry. Up to machine precision, each density is positive, sums to one, intergates to onein the sense that `` xstrikes[t]@xdensities[t] == 1`` and reprices
fits.
run_time_expiry: the time taken for the per-expiry first, in seconds.
For the “surface”
no_arb_modethe functionMkArbFree.__call__()will generate internal modelmstrikesaround the provided market strikes which are a superset of the extendedxstrikegrid. This surface grid is constructed by adding strikes from the next expiry if they are not too close to existing strikes. This is typically a much denser set than the input strikes. Each expiry is guaranteed to have theirxstrikesamong the respective model strikes.These fields are None if
no_arb_modeis not “surface”.mstrikes: the list of internal model strikes per expiry used.mdensities`: the list of densities formstrikes. Up to machine precision, each density is positive, sums to one, intergates to one in the sense that `` mstrikes[t]@mdensities[t] == 1`` and repricesfits. Moreover, the family ofmdensitiesis martingale density, each later density evaluaes a convex function higher than the a previous density.xix_to_mix: a list of arrays which gives for everyxstrike[t]the position inmstrikes[t], i.e.mstrikes[t][xix_to_mix[t]] == xstrikes[t]. The elementxix_to_mix[t]isNoneif no additional strikes were added to expiryt, i.e. the strikes coincide.run_time_surface: the time taken for the surface fit, in seconds.
- price(expiries, strikes, *, and_vols=False, mode=None)[source]#
Price options at
strikeswith expiriesexpiries.Use
modeto chose which pricing kernel to use: “expiry” uses the per-expiry fit which may not be free of arbitrage in time; “surface” uses the full surface fit which is free of arbitrage in time.Nonewill chose the latter if available, otherwise the former.If
and_volsisTruethis function returns call prices and their implied volatilities; ifFalse, it will return only call prices.- Parameters:
The expiry or expiries to price at.
If
expiriesis a float, all strikes are evaluated at that expiry.If
expiriesis a 1D array of shape(N,), thenstrikesmust also be a 1D array of shape(N,), and the function will price each strike at their respective expiry.If
expiriesis a 2D array of shape(M,1), thenstrikesmust be a 2D array of shape(1,N), and the function will price each strike at each expiry, returning an array of shape(M,N).
strikes (
float|ndarray) – The strikes to price at. The shape of this array must be compatible with the shape ofexpiriesas described above.and_vols (
bool) – Whether to return implied volatilities in addition to call prices. IfTrue, the function returns a tuple of (call prices, implied volatilities). IfFalse, it returns only call prices.mode (
str|None) – Which pricing kernel to use: “expiry” uses the per-expiry fit which may not be free of arbitrage in time; “surface” uses the full surface fit which is free of arbitrage in time.Nonewill chose the latter if available, otherwise the former.
- compute_market_fit(expiries, strikes, bids, asks, masks=None, *, and_vols=True)[source]#
Compute standardized fitting error stats
- Returns:
Errors – A dictionary-lik object with the following fields: *
fits: list of fitted prices for the input strikes, per expiry. *fit_vols: list of fitted vols for the input strikes, per expiry. *fit_errs: list of fitting errors for the input strikes, per expiry, where the error is defined as the distance to the bid/ask spread in units of half-spread, i.e.max( 0, fit - ask ) + max( 0, bid - fit) / max( 0.5*(ask-bid), self.min_half_spread ). *pcnt_fit: the percentage of strikes for which the fit is outside the bid/ask spread, i.e.sum( fit_errs > 0 ) / len(fit_errs). *median_fit_err: the median fitting error among strikes for which the fit is outside the bid/ask spread, i.e.median( fit_errs[fit_errs>0.] ). *mean_fit_err: the mean fitting error among strikes for which the fit is outside the bid/ask spread, i.e.mean( fit_errs[fit_errs>0.] ).- Return type:
PrettyObject
- class quantdata.sanos.arbfree.MkArbFree(no_arb_mode='surface', smoothness=None, surface_expiry_linear=True, min_half_spread=0.0001, mid_fit_weight=0.1, min_atm_vol=0.05, min_dlv=None, max_dlv=None, timeout_seconds=300.0, min_strikes_per_expiry=5, min_density=0.0001, min_dC_eps=0.001, _debug_verbose_cvxpy=None, _remove_no_arb_strikes=True, _debug_super_dense=False, _eps_price=1e-06, _eps_density=1e-07, _eps_dens_1=0.0001, _eps_no_arb=0.01)[source]#
Bases:
objectA utility class which generates a “closest” arbitrage free market using the ideas from the paper https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2642630.
Given a market with expiries, strikes, bid and asks this functional: 1) Expands the strike range following https://arxiv.org/pdf/2601.11209 remark 2.7, and drops expiries with too few strikes or with too steep bid-ask slopes at the boundaries. 2) Fits per expiry a linear no-arbitrage mid price within the bid-ask spread. It drops any expiries for which this is not possible as it implies actionable arbitrage. The function
then drops all strikes which have an implied probability density of zero (which means the fitted mid is linear at those strikes).
- The function then fits a fully arbitrage free surface, on a strike grid which theoretically means that a mid-price fit exists if and only if the
resulting fit is within bid/ask spread. The strike grid used is returned as
mstrikes.
See
MkArbFree.__call__()for more details on the input and output of this functional.- min_half_spread: float = 0.0001#
Minimum bid/ask spread. The optimization is weighted by inverse half spread.
- mid_fit_weight: float = 0.1#
Weight for fitting to the mid prices of options, where 1 means mid-price fit only is active, while 0 means to fit only a linear penalty for exceeding bid-ask.
- min_dlv: float | None = None#
Minimum DLV (difference of log-volatilities between consecutive expiries) to consider an expiry as non-degenerate.
- max_dlv: float | None = None#
Maximum DLV (difference of log-volatilities between consecutive expiries) to consider an expiry as non-degenerate.
- timeout_seconds: float | None = 300.0#
Time limit for the optimization solver, in seconds. This is passed to the CVXPY solver options as “time_limit”.
- min_strikes_per_expiry: int = 5#
(expert use only) Minimum strikes per expiry. Expiries with fewer strikes will be dropped.
- min_density: float = 0.0001#
(expert use only) Minimum density value to consider in the optimization. Strikes with lower values will be dropped.
- min_dC_eps: float = 0.001#
(expert use only) Minimum dC/dK slope at the boundaries. Expiries with steeper slopes will be dropped.
- __call__(expiries, strikes, bids, asks, *, vols=None, message_context=None, verbose=<cdxcore.verbose.Context object>)[source]#
Make market data arbitrage-free using ideas from the paper https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2642630.
Given a market with expiries, strikes, bid and asks this functional: 1) Expands the strike range following https://arxiv.org/pdf/2601.11209 remark 2.7, and drops expiries with too few strikes or with too steep bid-ask slopes at the boundaries. 2) Fits per expiry a linear no-arbitrage mid price within the bid-ask spread. It drops any expiries for which this is not possible as it implies actionable arbitrage. The function
then drops all strikes which have an implied probability density of zero (which means the fitted mid is linear at those strikes).
The function then fits a fully arbitrage free surface, on a strike grid which theoretically means that a mid-price fit exists if and only if the resulting fit is within bid/ask spread. The strike grid used is returned as
mstrikes.
This function is usually very fast, but it can get stuck when the overall surface is close to arbitrage in areas which have very little room to adjust.
This function returns a
ArbFreePricerobject which contains the result of the fit, and can be used to price options at arbitrary strikes and expiries using the fitted model.- Parameters:
expiries (:class:``numpy.ndarray`) – Increasing array of expiries (in years).
strikes (list[:class:``numpy.ndarray`]) – List of strike arrays, one per expiry. Each strike array must be strictly increasing and positive, and must have the same shape as the corresponding bid and ask arrays.
bids (list[:class:``numpy.ndarray`]) – List of bid price arrays, one per expiry.
asks (list[:class:``numpy.ndarray`]) – List of ask price arrays, one per expiry.
vols (:class:
numpy.ndarray| float | None, defaultNone) – Volatilities per expiry used whensmoothnessis not None. If left toNone, the function will compute an approximate mid-atm volatility from the provided bid and ask prices per expiry.message_context (str | callable[[], str] | None, default None) – Optional context to prepend to error and warning messages. This can be a string or a callable which returns a string, e.g. a lambda which returns a string with dynamic information such as the current expiry being processed. If None, no context is prepended.
verbose (
Context, defaultContext.all) – Verbose context for logging.
- Returns:
Extended market – See above.
- Return type:
dict
- surface_densities(*, expiries, variances, strikes, asks, bids, masks, xstrikes, xguessed_p=None, force_linear=False, hard_fit=False, message_context=None, verbose=<cdxcore.verbose.Context object>)[source]#
Stand-alone smooth or linear fit to a given surface
- expiry_density(*, expiry, variance, strikes_t, bid_t, ask_t, mask_t, xstrikes_t, force_linear=False, message_context=None, verbose=<cdxcore.verbose.Context object>, end='\\n')[source]#
Fit a single expiry given market and model strikes.
This function will first attempt a soft fit. If that soft fit is within bid/ask for all
strikes_tthe function returns. If this fit is not within bid/ask, then the function attempts a hard fit in the soft fit starting point. It successful, it returns the hard fit. If not successful it returns the soft fit, which is not all within bid/ask.- Parameters:
- expiry: float
Time to expiry in years.
- variancefloat | None
Variance for the expiry, used only if
self.smoothnessis not None. Ifvarianceis zero orNone, the function attempts a linear fit.- strikes_tnp.ndarray
Strikes for the expiry.
- bid_tnp.ndarray
Bid prices for the strikes.
- ask_tnp.ndarray
Ask prices for the strikes.
- xstrikes_tnp.ndarray
Strikes for the density grid. The first and last point should be outside the range of strikes_t, and the rest should include all strikes_t.
- force_linearboo,l, default
False If
True, the function attempts a linear fit even ifself.smoothnessis not None or the variance is positive.- message_contextstr|callable|None, default
None Optional context for error and debug messages. If a string is provided, it is used as a prefix for all messages. If a callable is provided, it is called to generate the message prefix at each call site.
- verboseContext, default
Context.all Verbosity context for logging messages.
end : str, default ``”
- “``
For
verboseoutput: how to end the output. Usingend=''will surpess a line feed.
- Returns:
- Fit
tuple[np.ndarray, np.ndarray, bool] Returns a tuple with:
xdensity: the fitted density on the xstrikes_t gridfit: the fitted call prices on the strikes_t grid
- Fit
- make_extended_strikes(strikes, bids, asks, *, prev_lower=None, prev_upper=None, message_context=None)[source]#
Utility function to generate an increasing range of extended strikes such that outside points are sufficiently far away, c.f. https://arxiv.org/abs/2601.11209 remark 2.7.
Essentially, given strikes $K_1,ldots,K_{n-1}$ and mid-prices $C_1,ldots,C_n$, we want to find $K_0 < K_1$ and $K_{n+1} > K_n$ with call price values equal to intrinsic value such that the boundary conditions $-1 < frac{C_1 - C_0}{K_1 - K_0}$ and $frac{C_{n+1} - C_n}{K_{n+1} - K_n} < 0$ are satisfied.
Lower strike
Let $dC_1 = frac{C_2 - C_1}{K_2 - K_1}$ be the slope of the line connecting the point $(K_1,C_1)$ to the point $(K_2,C_2)$. Then we want to find $K_0$ with $C_0 = 1 - K_0$ such that: $$
-1 <= frac{ C_1 - C_0 }{ K_1 - K_0 } leq dC_1 .
$$ If $dC_1$ is not greater than -1, we drop $K_1$ and proceed. Once $dC_1$ is greater than -1, we can chose any strike below $$
K_0 leq frac{1 - C_1 + K_1 dC_1}{1 + dC_1}
$$ which is positive. If $K_0$ is non-positive, we will drop $K_1$ from the strike list and proceed to the next strike.
The actual strike used is $K’_0 := max{ K_0/2, K_0 - 2 ( K_1 - K_0 ) }$.
The new lower strike will thenn be the minimum of above calculation and
prev_lower, if provided.Upper strike
Let $dC_{n-1} := frac{C_n - C_{n-1}}{K_n - K_{n-1}}$ be the slope of the line connecting the point $(K_{n-1},C_{n-1})$ to the point $(K_n,C_n)$. Then we want to find $K_n$ with $C_n = 0$ such that $$
dC_{n-1} leq frac{ C_{n+1} - C_n }{ K_{n+1} - K_n } leq 0 .
$$ If $dC_{n-1} >= 0$ we drop $K_n$. Once $dC_{n-1}$ is negative, we can chose any strike above $$
K_{n+1} geq K_n - frac{C_n}{dC_{n-1}} .
$$
The actual strike used is $K’_{n+1} := K_n + 2 ( K_{n+1} - K_n )$.
The new upper strike will then be the maximum of above calculation and
prev_upper, if provided.- Parameters:
strikes (
ndarray) – Array of strikes for the expiry, must be strictly increasing and positive.bids (
ndarray) – Array of bid prices for the expiry, must have the same shape as strikes.asks (
ndarray) – Array of ask prices for the expiry, must have the same shape as strikes and be strictly greater than bids.prev_lower (
float|None) – Previous lower strike from the previous expiry, if any. The new lower strike will be the minimum of the calculated lower strike and this value, if provided.prev_upper (
float|None) – Previous upper strike from the previous expiry, if any. The new upper strike will be the maximum of the calculated upper strike and this value, if provided.message_context (
str|None) – Optional callable that returns a string to be used as a header in error messages. This can be used to provide context such as the expiry time and other relevant information.
- Returns:
Extended strikes – A tuple containing the extended
xstrikes, the correspondingmaskto map from input strikes to extended strikes, and an optionalnoticeto be printed to the user in verbose mode.The relation between input strikes, mask, and output “xstrikes” is ```
xstrikes[1:-1] == strikes[mask]
- Return type:
- static atm_volatilities(expiries, strikes, vols, fwdvol_min=0.01)[source]#
Computes ATM vols using linear interpolation in volatilities, with a floor of
fwdvol_min.The forward volatilities will be floored by
fwdvol_min.- Parameters:
expiries (
ndarray) – 1D array of expiries of lengthT.strikes (
list[ndarray] |ndarray) – List ofT1D arrays of strikes or a 2D array of strikes with shape(T,N).vols (
list[ndarray] |ndarray) – List ofT1D arrays of volatilities or a 2D array of volatilities with shape(T,N). For SANOS it is recommended to use ask volatilities.fwdvol_min (
float) – Minimum forward volatility.
- Returns:
Vols – 1D array of
Tvolatilities for each expiry, with forward volatility floored byfwdvol_min.- Return type: