Module contents
Stage 2 of 8Advanced 90 min

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

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. D(T)>0D(T)>0 is today’s price of a unit of currency payable at TT; 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 K1<K2K_1<K_2, the lower-strike call’s payoff dominates the higher-strike call’s. Without costs, call prices must decrease and the vertical spread satisfies

0≤C(K1)−C(K2)≤D(K2−K1).0\le C(K_1)-C(K_2)\le D(K_2-K_1).

The upper bound follows because the spread’s payoff never exceeds K2−K1K_2-K_1; 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 K1<K2<K3K_1<K_2<K_3, let λ=(K3−K2)/(K3−K1)\lambda=(K_3-K_2)/(K_3-K_1). A portfolio long λ\lambda calls at strike K1K_1, long 1−λ1-\lambda at strike K3K_3, and short one at strike K2K_2 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 K1K_1 all calls expire worthless; above K3K_3 the coefficients and weighted strikes cancel. Between K1K_1 and K2K_2 there is an increasing line, and between K2K_2 and K3K_3 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 K1K_1 minus a call at K2K_2 lies between zero and K2−K1K_2-K_1. If its cost were negative, you would buy the portfolio and receive money today. If it exceeded the bond D(K2−K1)D(K_2-K_1), 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 k=log⁡(K/FT)k=\log(K/F_T) and w(k,T)=σimp2(k,T)Tw(k,T)=\sigma_{\rm imp}^2(k,T)T. If the forward is deterministic and the normalized process is a martingale, Jensen implies that calls normalized by DTFTD_TF_T do not decrease with maturity at fixed kk. The normalized Black price increases in ww, so w(k,T)w(k,T) 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 kk, 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 K1=FT1ekK_1=F_{T_1}e^k to K2=FT2ekK_2=F_{T_2}e^k. 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 XT=ST/FTX_T=S_T/F_T and c(k,T)=C(FTek,T)/(DTFT)c(k,T)=C(F_Te^k,T)/(D_TF_T). With deterministic rates and carry, and XX a martingale under a consistent pricing measure, c(k,T)=E[(XT−ek)+]c(k,T)=\E[(X_T-e^k)^+]. The function x↦(x−ek)+x\mapsto(x-e^k)^+ is convex. For T1<T2T_1<T_2, conditional Jensen gives E[(XT2−ek)+∣FT1]≥(XT1−ek)+\E[(X_{T_2}-e^k)^+\mid\mathcal F_{T_1}]\ge (X_{T_1}-e^k)^+; taking expectations yields c(k,T2)≥c(k,T1)c(k,T_2)\ge c(k,T_1). Black is strictly increasing in w>0w>0, so the inequality is equivalent to w(k,T2)≥w(k,T1)w(k,T_2)\ge w(k,T_1) 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

q(K,T)=D(T)−1∂2C∂K2.q(K,T)=D(T)^{-1}\frac{\partial^2 C}{\partial K^2}.

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 hh, and dividing it by h2Dh^2D 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 C=D∫K∞(s−K)q(s) dsC=D\int_K^\infty(s-K)q(s)\,ds. The first derivative is −D Q(ST>K)-D\,Q(S_T>K): the boundary term vanishes because the payoff is zero at s=Ks=K. Differentiating again gives Dq(K)Dq(K) 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 s−=[C(Ki)−C(Ki−1)]/(Ki−Ki−1)s_-= [C(K_i)-C(K_{i-1})]/(K_i-K_{i-1}) and s+=[C(Ki+1)−C(Ki)]/(Ki+1−Ki)s_+=[C(K_{i+1})-C(K_i)]/(K_{i+1}-K_i). A local approximation to the second derivative is 2(s+−s−)/(Ki+1−Ki−1)2(s_+-s_-)/(K_{i+1}-K_{i-1}). 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

g(k)=(1−kw′2w)2−(w′)24(1w+14)+w′′2.g(k)=\left(1-\frac{k w'}{2w}\right)^2 -\frac{(w')^2}{4}\left(\frac1w+\frac14\right)+\frac{w''}{2}.

The density is proportional to gg by a positive factor where w>0w>0. g<0g<0 indicates broken convexity under the model assumptions. In lemma 2.2 of Gatheral and Jacquier, besides g≥0g\ge0 for every kk, the tail condition d+(k)→−∞d_+(k)\to-\infty as k→+∞k\to+\infty appears, with d+=−k/w+w/2d_+=-k/\sqrt w+\sqrt w/2. 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 d2=−k/w−w/2d_2=-k/\sqrt{w}-\sqrt{w}/2 and K=FTekK=F_Te^k, the density associated with the Black slice is

q(K,T)=exp⁡(−d22/2)K2πw(k,T)g(k).q(K,T)=\frac{\exp(-d_2^2/2)}{K\sqrt{2\pi w(k,T)}}g(k).

The prefactor is positive for K,w>0K,w>0: the density’s sign matches that of gg. This identity follows by applying the chain rule twice to Black, remembering that ∂K=K−1∂k\partial_K=K^{-1}\partial_k. The first derivative acts on both KK and w(k)w(k); omitting the latter dependence gives a constant Black density that does not correspond to the smile. The term w′′/2w''/2 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.

InteractiveWhen the density turns negative
  • Curve
  • Control point
Implied smile
Call price
Function g
Risk-neutral density
0.000
Minimum g1.000
Strike at minimum100.0
Butterfly cost0.01984
Synthetic slice with S = F = 100, T = 1 and r = q = 0. Total variance is 0.04 plus a Gaussian bump. Drag the center point or change the slider; the smile, calls, g and density are shown, along with the cost of a width-1 butterfly near the minimum of g. The normal CDF for the price is approximate and the grid is finite.

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.

[ ]Injected violations and densityBrowser
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-3

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

[ ]Provider's historical sampleLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofButterfly and convexity
Prove: Prove call convexity in strike using a butterfly portfolio.
0
K₁ < K₂ < K₃ and λ = (K₃ − K₂)/(K₃ − K₁).

Step 1 of 3. What is the payoff of λ calls at K₁, (1−λ) at K₃ and one short call at K₂?

NumericCost of a butterfly
At equally spaced strikes, calls are quoted without a spread at 15, 9, and 2. You buy one call at each end and sell two in the center. How much do you receive initially?
QuizComparing maturities
Total variance decreases between two maturities at a fixed nominal strike. Is that sufficient to assert calendar arbitrage?
CodeButterfly function
Implement g_function(k,w,dw,d2w) with NumPy broadcasting. Reject nonpositive variance and return the values of g; negative indices indicate a failure on that grid.
def g_function(k,w,dw,d2w):
  raise NotImplementedError()
Shift+Enter to run

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.