Static arbitrage and the risk-neutral density
Formulate static no-arbitrage conditions in prices and total variance, implement a detector that identifies vertical spreads, butterflies, and calendars with arbitrage in quotes, and obtain the risk-neutral density using Breeden-Litzenberger, checking when it ceases to be a density.
After this lesson you can
- State and prove the conditions for vertical spread, butterfly, and calendar arbitrage.
- Implement an arbitrage detector for quotes that accounts for the spread.
- Calculate the risk-neutral density by finite differences and verify that it integrates to one.
- Relate the butterfly condition to Gatheral's g function in total variance.
Before you start
- P03Option chain cleaningImplied forward and discount factorRobust implied volatility inversion
- 28Fundamental theorem of asset pricingRisk-neutral measure
- 03Leibniz integral rule
- 06Second-order convexity condition
- 09Finite differencesOptimal finite-difference step
- 04Probability densityCumulative distribution function
Prices compatible with payoffs
A smile can look smooth and produce impossible prices. Finding this does not require forecasting the index: construct a portfolio whose payoff is known for all terminal values. The relevant condition for a trade is its cost at actually available quotes, not the shape of a mid-price curve.
We work with European calls on the same underlying, maturity, and settlement. is today’s price of a unit of currency payable at ; we assume financing and short selling are possible at the price considered, with no additional costs. The inequalities are necessary under these assumptions. Bid-ask bands and non-simultaneous quotes require a more cautious interpretation.
In the previous lesson you obtained forwards, discounts, and implied volatilities from a chain; here you check whether prices can correspond to compatible payoffs. The representation as a discounted expectation comes from the risk-neutral measure, and numerical estimation introduces finite-difference errors.
For European calls with the same maturity and strikes , the lower-strike call’s payoff dominates the higher-strike call’s. Without costs, call prices must decrease and the vertical spread satisfies
The upper bound follows because the spread’s payoff never exceeds ; buying that maximum as a bond covers the payoff. With bid and ask, an exploitable monotonicity violation requires the higher-strike call’s bid to exceed the lower-strike call’s ask. For the upper bound, compare the lower call’s bid minus the higher call’s ask with the discounted bond cost. Quotes at different times, fees, or execution restrictions can eliminate the apparent opportunity.
For three strikes , let . A portfolio long calls at strike , long at strike , and short one at strike has a nonnegative payoff. A negative cost for that portfolio would imply arbitrage. Its executable cost uses asks for purchases and the bid for the sale. On an uneven grid the weights are not necessarily one half.
To check the payoff, consider four regions. Below all calls expire worthless; above the coefficients and weighted strikes cancel. Between and there is an increasing line, and between and a decreasing line returning to zero. The price inequality therefore follows from the portfolio, not a statistical property of quotes. If only the midpoint violates convexity but the portfolio executed at bid and ask costs money, the observation does not prove arbitrage.
The same argument clarifies the spread bound. The payoff of a call at minus a call at lies between zero and . If its cost were negative, you would buy the portfolio and receive money today. If it exceeded the bond , you would sell the spread and buy the bond: the bond’s payoff covers the short position. With spreads, each trade uses the correct side: buy at the ask and sell at the bid. Equality does not produce a strictly positive initial profit.
For discrete data, convexity is equivalent to nondecreasing slopes between consecutive strikes. Requiring a positive second difference is insufficient when strikes are unevenly spaced. The detector below examines butterflies across three neighboring strikes: finding a cheap portfolio is local evidence, but not finding one does not show that a global selection of prices exists within all bands. That stronger question requires, for example, a feasibility problem with all constraints and prices as variables.
Total variance and calendar
The total variance representation uses and . If the forward is deterministic and the normalized process is a martingale, Jensen implies that calls normalized by do not decrease with maturity at fixed . The normalized Black price increases in , so does not decrease either. Comparing unnormalized calls at a fixed nominal strike does not establish that condition in the presence of carry.
The static arbitrage detector must compare options at common , with consistent discounting and forward. For simultaneous bid-ask quotes, a reversal of the order requires the normalized short-maturity bid to exceed the normalized long-maturity ask. Interpreting this as a strategy requires assumptions about carry, financing, and trading; interpolation between strikes adds assumptions.
In particular, the comparable strike changes from to . If the chain does not quote both strikes, interpolating midpoints can create or erase a violation. A conservative test must propagate bid-ask bands through interpolation and distinguish contracts with different styles or settlement. The laboratory keeps the given forwards and discounts when comparing the synthetic pair; it does not infer an intermediate quote.
To see why normalization matters, write and . With deterministic rates and carry, and a martingale under a consistent pricing measure, . The function is convex. For , conditional Jensen gives ; taking expectations yields . Black is strictly increasing in , so the inequality is equivalent to for interior prices. The result does not carry over without assumptions to random carry or contracts with different payoff rules.
Density and butterfly
For a regular risk-neutral density, Breeden-Litzenberger gives
The risk-neutral density is nonnegative when the call is convex. On a uniform grid, the numerator of the second difference is the cost of a butterfly of width , and dividing it by approximates the density. An irregular grid requires dividing slope differences by the appropriate distance. Mass in a finite window may be less than one because of its tails, not necessarily because of arbitrage.
The derivation starts with . The first derivative is : the boundary term vanishes because the payoff is zero at . Differentiating again gives where a continuous density exists. If the distribution has atoms, the second derivative is interpreted as a measure, and a finite-difference method distributes that mass across nodes.
For discrete data, define and . A local approximation to the second derivative is . Reducing step sizes may improve truncation error, but price noise is amplified approximately as the inverse square of the step. Compare several steps and use a regularized fit that preserves the constraints.
For a positive, smooth total-variance slice, the butterfly condition is expressed by
The density is proportional to by a positive factor where . indicates broken convexity under the model assumptions. In lemma 2.2 of Gatheral and Jacquier, besides for every , the tail condition as appears, with . Evaluating only a grid does not certify the global condition. The relationship between price derivatives and the distribution is due to Breeden and Litzenberger.
More precisely, with and , the density associated with the Black slice is
The prefactor is positive for : the density’s sign matches that of . This identity follows by applying the chain rule twice to Black, remembering that . The first derivative acts on both and ; omitting the latter dependence gives a constant Black density that does not correspond to the smile. The term explains why a very localized deformation can break convexity even though volatility remains positive.
A nonnegative density at the nodes does not suffice to guarantee a distribution: integrated with any atoms and tails, it must have mass one, and its first moment must be compatible with the forward. In a finite window the observed area is only the mass inside that window. Unconstrained extrapolation can add negative mass or change both moments outside the quoted region.
Laboratory: detecting without ignoring the spread
The detector receives sorted strikes and valid bids and asks. Experiments inject one violation of each type into synthetic surfaces and check that the detector finds the constructed index. Another case has non-convex midpoints but a spread compatible with an arbitrage-free curve. These are specific test cases, not a statistical guarantee for every surface.
The monotonicity and vertical indices identify the left endpoint of the pair; the butterfly index identifies its central strike. A monetary tolerance avoids interpreting tiny numerical residuals as profits, but it does not replace fees, available size, or synchronized execution. For calendar, the function’s tolerance is expressed in normalized price, not currency units: do not confuse it with the tolerance in strike tests.
import numpy as np
from scipy.special import ndtr
def call_price(K,S=100.,r=.03,T=1.,sigma=.2):
K=np.asarray(K,float); d1=(np.log(S/K)+(r+.5*sigma*sigma)*T)/(sigma*np.sqrt(T));d2=d1-sigma*np.sqrt(T)
return S*ndtr(d1)-K*np.exp(-r*T)*ndtr(d2)
def detect(K,bid,ask,D=1.,tol=1e-10):
K,bid,ask=[np.asarray(x,float) for x in (K,bid,ask)]
if K.ndim!=1 or bid.shape!=K.shape or ask.shape!=K.shape or len(K)<3 or np.any(~np.isfinite(K)) or np.any(K<=0) or np.any(np.diff(K)<=0) or np.any(~np.isfinite(bid)) or np.any(~np.isfinite(ask)) or np.any(bid<0) or np.any(ask<bid) or not np.isfinite(D) or D<=0:raise ValueError('Rejilla o cotizaciones inválidas')
monotone=np.where(bid[1:]>ask[:-1]+tol)[0]
vertical=np.where(bid[:-1]-ask[1:]>D*np.diff(K)+tol)[0]
w=(K[2:]-K[1:-1])/(K[2:]-K[:-2]);cost=w*ask[:-2]+(1-w)*ask[2:]-bid[1:-1]
butterfly=np.where(cost < -tol)[0]+1
return {'monotonia':monotone,'vertical':vertical,'mariposa':butterfly,'costes':cost}
def calendar(bid_early,ask_late,F1,D1,F2,D2,tol=1e-10):
if not np.all(np.isfinite([F1,D1,F2,D2])) or min(F1,D1,F2,D2)<=0:raise ValueError('Forward y descuento positivos requeridos')
bid_early,ask_late=np.broadcast_arrays(np.asarray(bid_early,float),np.asarray(ask_late,float))
if np.any(~np.isfinite(bid_early)) or np.any(~np.isfinite(ask_late)) or np.any(bid_early<0) or np.any(ask_late<0):raise ValueError('Cotizaciones no válidas')
return bid_early/(D1*F1)>ask_late/(D2*F2)+tol
K=np.array([80.,90,100,110,120]);C=call_price(K);bid=np.maximum(0,C-.05);ask=C+.05;D=np.exp(-.03)
base=detect(K,bid,ask,D);print('base', {k:list(v) for k,v in base.items() if k!='costes'})
assert all(len(base[k])==0 for k in ('monotonia','vertical','mariposa'))
for kind in ['monotonia','vertical','mariposa']:
b=bid.copy();a=ask.copy()
if kind=='monotonia': b[2]=a[1]+1;a[2]=b[2]+.02; expected=1
elif kind=='vertical': b[1]=a[2]+D*(K[2]-K[1])+1;a[1]=b[1]+.02;expected=1
else: b[2]=(a[1]+a[3])/2+1;a[2]=b[2]+.02;expected=2
got=detect(K,b,a,D);print('inyectado',kind,'detectado',expected in got[kind]);assert expected in got[kind]
print('calendario inyectado',bool(calendar(.12,.10,1,1,1,1)));assert calendar(.12,.10,1,1,1,1)
assert not calendar(.10,.12,1,1,1,1)
# Una violación en puntos medios cabe en spreads compatibles con la curva original.
b2=bid.copy();a2=ask.copy();a2[2]=C[2]+2;mid=(a2+b2)/2
print('curvatura centro de mids',mid[1]-2*mid[2]+mid[3],'arbitrajes detectados',len(detect(K,b2,a2,D)['mariposa']))
assert mid[1]-2*mid[2]+mid[3]<0 and len(detect(K,b2,a2,D)['mariposa'])==0
Kgrid=np.linspace(.05,350,7000);Cgrid=call_price(Kgrid);h=Kgrid[1]-Kgrid[0];dens=np.exp(.03)*(Cgrid[:-2]-2*Cgrid[1:-1]+Cgrid[2:])/h**2
print('masa densidad',np.trapezoid(dens,Kgrid[1:-1]),'min densidad',dens.min())
assert abs(np.trapezoid(dens,Kgrid[1:-1])-1)<1e-3This run detected the four injected cases: monotonicity, spread bound, butterfly, and calendar. The control’s midpoint butterfly costs −0.05418, but the bid-ask quotes contain a compatible curve and the detector does not report an executable butterfly. Black density calculated over a wide window integrates to 0.99999999974; a numerical minimum near −1.2e-11 comes from rounding and shows why a tolerance is needed. None of these numbers certifies an arbitrary surface.
A historical snapshot with known limitations
The next local cell retrieves one day from the HistoricalData.net provider’s free sample using range requests to the ZIP, checks its SHA256 against the manifest, and analyzes it without redistributing the file. The sample permits evaluation under its terms; readers download it directly. We select European SPXW with PM settlement, quote date September 15, 2022, and expiry September 30, 2022. The file provides bid and ask but lacks quote times: any anomaly is only a historical candidate, not a simultaneously executable opportunity.
import io,json,urllib.request,zipfile,hashlib
import numpy as np
import pandas as pd
class RemoteZip(io.RawIOBase):
def __init__(self,url):
self.url=url;self.pos=0
with urllib.request.urlopen(urllib.request.Request(url,method='HEAD'),timeout=30) as r:self.n=int(r.headers['Content-Length'])
def seekable(self):return True
def readable(self):return True
def tell(self):return self.pos
def seek(self,off,whence=0):
self.pos=off if whence==0 else self.pos+off if whence==1 else self.n+off
return self.pos
def read(self,n=-1):
if n<0:n=self.n-self.pos
if not n:return b''
end=min(self.n-1,self.pos+n-1);req=urllib.request.Request(self.url,headers={'Range':f'bytes={self.pos}-{end}'})
with urllib.request.urlopen(req,timeout=60) as r:
if r.status!=206:raise RuntimeError('El proveedor no admite petición de rango')
data=r.read()
self.pos+=len(data);return data
url='https://historicaldata.net/file/options_sample_2022H2.zip';name='2022-09-15_options.csv'
with zipfile.ZipFile(RemoteZip(url)) as archive:
manifest=json.loads(archive.read('day_by_date/manifest.json'));data=archive.read('day_by_date/'+name)
expected=next(x['sha256'] for x in manifest['files'] if x['name']==name);actual=hashlib.sha256(data).hexdigest()
if expected!=actual or actual!='054acc61106b15a21a2b166e975a506fb0559b9a8d7ec896817ab5e6eb8c208a':raise RuntimeError('La muestra ha cambiado o no supera el hash')
raw=pd.read_csv(io.BytesIO(data));d=raw[(raw.underlying=='SPXW')&(raw['style']=='E')&(raw.settlement_time=='PM')&(raw.expiration=='2022-09-30')].copy()
d=d[(d.bid>=0)&(d.ask>=d.bid)&(d.ask>0)&(d.volume>=1)&(d.open_interest>=10)]
if d.duplicated(['strike','type']).any():raise ValueError('Contratos duplicados en la selección')
pairs=d.pivot(index='strike',columns='type',values=['bid','ask']).dropna();mid=(pairs['bid']+pairs['ask'])/2
sel=(pairs.index>=3600)&(pairs.index<=4200);strikes=pairs.index.to_numpy()[sel];y=(mid['call']-mid['put']).to_numpy()[sel]
a,slope=np.linalg.lstsq(np.c_[np.ones(len(strikes)),strikes],y,rcond=None)[0];D=-slope;F=a/D
if D<=0 or F<=0:raise ValueError('Paridad estimada no válida')
c=d[(d['type']=='call')&(d.strike.between(3600,4200))].sort_values('strike')
if c.strike.duplicated().any():raise ValueError('Strikes duplicados')
K=c.strike.to_numpy();bid=c.bid.to_numpy();ask=c.ask.to_numpy();w=(K[2:]-K[1:-1])/(K[2:]-K[:-2]);cost=w*ask[:-2]+(1-w)*ask[2:]-bid[1:-1]
print('SHA256',actual,'filas seleccionadas',len(d),'pares',len(strikes),'horas disponibles',int(d.quote_time.notna().sum()))
print('F y D estimados',F,D,'RMSE paridad',np.sqrt(np.mean((y-(a+slope*strikes))**2)))
print('calls',len(c),'candidatos monotonía',int(np.sum(bid[1:]>ask[:-1])),'vertical',int(np.sum(bid[:-1]-ask[1:]>D*np.diff(K))),'mariposa',int(np.sum(cost<0)))npm run lab and open the connection link.In this sample, filtering left 354 contracts and 81 strike pairs in [3600,4200]. Midpoint regression gave F = 3912.07824 and D = 0.999008; parity RMSE was 0.09952. Among 90 calls in that window, no candidates of the three checked types appeared. Missing times, finite selection, and estimated discount prevent concluding the entire chain was arbitrage-free. The sample is historical and does not validate a current daily capture.
The parity fit uses midpoints, so the discount is an estimate, not an error-free rate. The vertical diagnostic depends on that discount. Moreover, the calculation inspects only neighboring pairs and triples of the 90 filtered calls; it does not test portfolios with other strikes, other maturities, or limited quantities. The historical cell reproduces the calculation from the provider’s sample and checks the hash; it does not turn its observations into simultaneous quotes.
Exercises
Step 1 of 3. What is the payoff of λ calls at K₁, (1−λ) at K₃ and one short call at K₂?
def g_function(k,w,dw,d2w):
raise NotImplementedError()Ideas to remember
A price curve must respect inequalities derived from nonnegative payoffs. The spread and quote times qualify any claim of executability; density and the g function are tools sensitive to discretization and tails.