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: PrettyObject

Arbitrage-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 the input_index field.

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 words output_expiries == [ input_expiries[j] for j in input_index ].

  • masks: a list of T boolean masks by expiry indicating which strikes were considered during the no-arb fit.

    The mask for expory j has the same length Nj as the strikes[ 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 the T input strike arrays for the expiries used.

  • bids: a copy of the T arrays of input bids for the expiries used.

  • asks: a copy of the T arrays of input asks for the expiries used.

  • fits1: list of T per-expiry fitted arbitrage-free prices within bid/ask (where masked) for the input strikes used. The element fit1[j] is a vector of length strikes[j]. Within numerical accuracy we have bids[j][mask[j]] <= fit1[j][mask[j]] <= asks[j][mask[j]].

  • fitsX: list of T surface fitted arbitrage-free prices for the input strikes.

    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 mask True.

    Up to machine precision existence of fitsX within bid/ask spread in the linear case smoothness=0 is equivalent to absence of arbitrage.

    This field is None if no_arb_mode is “expiry”.

Besides the pure fits, this class also contains the ingredients of the DLV/SANOS model.

  • For the “expiry” no_arb_mode the function MkArbFree.__call__() will generate internal model xstrikes around the provided market strikes. For those strikes it will compute a xdensities per 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 for xstrikes, per expiry. Up to machine precision, each density is positive, sums to one, intergates to one

      in 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_mode the function MkArbFree.__call__() will generate internal model mstrikes around the provided market strikes which are a superset of the extended xstrike grid. 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 their xstrikes among the respective model strikes.

    These fields are None if no_arb_mode is not “surface”.

    • mstrikes: the list of internal model strikes per expiry used.

    • mdensities`: the list of densities for mstrikes. Up to machine precision, each density is positive, sums to one, intergates to one in the sense that `` mstrikes[t]@mdensities[t] == 1`` and reprices fits. Moreover, the family of mdensities is 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 every xstrike[t] the position in mstrikes[t], i.e. mstrikes[t][xix_to_mix[t]] == xstrikes[t]. The element xix_to_mix[t] is None if no additional strikes were added to expiry t, i.e. the strikes coincide.

    • run_time_surface: the time taken for the surface fit, in seconds.

to_dict()[source]#

Return an HDF5-compatible representation of the pricer.

static from_dict(d)[source]#

Reconstruct a pricer serialized by to_dict().

price(expiries, strikes, *, and_vols=False, mode=None)[source]#

Price options at strikes with expiries expiries.

Use mode to 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. None will chose the latter if available, otherwise the former.

If and_vols is True this function returns call prices and their implied volatilities; if False, it will return only call prices.

Parameters:
  • expiries (float | ndarray) –

    The expiry or expiries to price at.

    • If expiries is a float, all strikes are evaluated at that expiry.

    • If expiries is a 1D array of shape (N,), then strikes must also be a 1D array of shape (N,), and the function will price each strike at their respective expiry.

    • If expiries is a 2D array of shape (M,1), then strikes must 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 of expiries as described above.

  • and_vols (bool) – Whether to return implied volatilities in addition to call prices. If True, the function returns a tuple of (call prices, implied volatilities). If False, 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. None will chose the latter if available, otherwise the former.

interpolate_atm_vols(expiries)[source]#

Interpolates the (ATM) variances (not smoothed)

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

property T: int#
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: object

A 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).

  1. 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.

no_arb_mode: str = 'surface'#
smoothness: float | None = None#
surface_expiry_linear: bool = True#
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_atm_vol: float = 0.05#

Minimum ATM vol.

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).

  1. 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 ArbFreePricer object 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, default None) – Volatilities per expiry used when smoothness is not None. If left to None, 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, default Context.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_t the 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.smoothness is not None. If variance is zero or None, 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 if self.smoothness is 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 verbose output: how to end the output. Using end='' will surpess a line feed.

Returns:
Fittuple[np.ndarray, np.ndarray, bool]

Returns a tuple with:

  • xdensity: the fitted density on the xstrikes_t grid

  • fit: the fitted call prices on the strikes_t grid

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 corresponding mask to map from input strikes to extended strikes, and an optional notice to 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:

tuple[np.ndarray, np.ndarray, str|None]

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 length T.

  • strikes (list[ndarray] | ndarray) – List of T 1D arrays of strikes or a 2D array of strikes with shape (T,N).

  • vols (list[ndarray] | ndarray) – List of T 1D 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 T volatilities for each expiry, with forward volatility floored by fwdvol_min.

Return type:

numpy.ndarray