SVI, SSVI and arbitrage-free calibration
Fit SVI by maturity using the quasi-explicit method that reduces the problem to two nonlinear parameters, then move to the SSVI surface and its sufficient no-arbitrage conditions and calibrate with constraints. The result is a continuous surface free of static arbitrage that interpolates and extrapolates in a controlled manner.
After this lesson you can
- Implement SVI fitting by maturity with the quasi-explicit method.
- Impose the SSVI no-arbitrage conditions as calibration constraints.
- Evaluate fit in volatility points weighted by vega or spread.
- Interpolate in maturity without introducing calendar arbitrage.
Before you start
One smile per maturity is not yet a surface
The chain of quotes and Black inversion produces scattered points with different spreads. Fitting a smooth curve helps price between strikes, but a smooth curve can imply negative density. Even if each slice is admissible, two slices can cross over time. In the previous lesson you related these problems to butterflies and calendars. Now we construct parameterizations and check both fit and constraints.
SVI: five parameters with different consequences
The raw SVI parameterization describes total variance at one maturity as a function of :
shifts the curve vertically; scales its wings; tilts its asymmetry; shifts the transition horizontally and smooths its curvature. Do not interpret as the minimum: for that lies at and equals . Both formulas follow by setting to zero. The minimum must be positive to use the previous lesson’s density formula over the whole axis.
In the right wing, ; in the left, . Lee’s moment formula bounds those asymptotic slopes by 2 under no arbitrage for a nonnegative underlying. Respecting the bound is necessary but insufficient for at every strike. Nor is checking the minimum of enough: change the parameters and observe that positive variance can still generate negative density.
Separating linear from nonlinear
With and fixed, define , , and . Then
For each pair , fitting to observed variances is a weighted linear problem. The outer problem searches only : this reduction is the idea behind Zeliade’s quasi-explicit fit. If and are fixed but is not, the square root still depends nonlinearly on : fixing only those two does not make the full problem linear.
We use a conservative constraint that allows the inner problem to be solved by bounded least squares. Write , and require . Then and
Both bases are nonnegative. This choice ensures nonnegative variance and , but is not the full possible SVI domain and does not itself impose absence of butterfly arbitrage. We solve the inner problem with scipy.optimize.lsq_linear and the outer problem with several initializations. The normal equations explain the linear problem, but solving it by factorization avoids squaring its condition number. A local optimum still does not guarantee a global optimum.
SSVI: a family of linked slices
The SSVI surface uses ATM variance , constant correlation , and a positive function :
At the square root equals one and the expression returns exactly . Gatheral and Jacquier provide conditions to avoid calendar arbitrage and sufficient conditions for butterfly arbitrage. Calendar requires nondecreasing and, for ,
When the upper bound is interpreted by continuity as infinity. Two sufficient butterfly conditions are and . They are sufficient conditions, not a complete characterization of all butterfly-free slices.
We choose . Then , satisfying the calendar condition; the butterfly conditions reduce to and . For a finite range of maturities, it is enough to impose them at the largest and keep increasing. This guarantee applies to the stated interval: extending without bound may eventually violate the first inequality.
Arbitrage-free calibration combines fit and constraints. Linear interpolation of between increasing values remains increasing, so the SSVI family preserves the calendar condition over the interval. Linearly interpolating volatility between two arbitrary slices offers no such guarantee. At extreme strikes the formula extrapolates with wings linear in variance: check the limits and do not confuse parametric extrapolation with observed information.
Laboratory: separating fit error from arbitrage
The laboratory fits variance with weights approximating distance in units of half the volatility spread. If , a small variation satisfies ; thus the variance weight is , where is the half-spread in volatility. This approximation fails near zero vega or for wide spreads. For SSVI we directly minimize volatility errors divided by . Vega weighting in prices is another local approximation; it does not turn an illiquid quote into precise data.
import numpy as np
import pandas as pd
from scipy.optimize import lsq_linear, minimize, least_squares
def svi(k,a,b,rho,m,s):
x=k-m
return a+b*(rho*x+np.sqrt(x*x+s*s))
def fit_svi_slice(k,w,weights):
k,w,weights=map(lambda x:np.asarray(x,float),(k,w,weights))
if np.any(weights<=0) or np.any(w<=0): raise ValueError('Pesos y varianzas positivas requeridas')
def inner(z):
m,s=z; y=(k-m)/s; root=np.sqrt(1+y*y)
X=np.column_stack([np.ones(len(k)),root+y,root-y]); sw=np.sqrt(weights)
fit=lsq_linear(X*sw[:,None],w*sw,bounds=(1e-12,np.inf),tol=1e-11)
if not fit.success: raise RuntimeError('Falló el ajuste interior')
return fit.x,np.sum(weights*([email protected])**2)
fits=[minimize(lambda z:inner(z)[1],[m,s],method='L-BFGS-B',bounds=[(-1,1),(.01,2)])
for m in (-.2,0,.2) for s in (.08,.3)]
opt=min(fits,key=lambda f:f.fun); (a,u,v),loss=inner(opt.x); m,s=opt.x; c=u+v
return np.array([a,c/s,(u-v)/c,m,s]),loss
def ssvi(k,theta,eta,rho):
phi=eta/np.sqrt(theta); z=phi*k
return theta/2*(1+rho*z+np.sqrt((z+rho)**2+1-rho*rho))
def fit_surface(df):
groups=list(df.groupby('T',sort=True)); times=np.array([t for t,_ in groups]); n=len(times)
k=np.concatenate([g.k.to_numpy() for _,g in groups])
vol=np.concatenate([g.iv.to_numpy() for _,g in groups])
h=np.concatenate([g.halfspread.to_numpy() for _,g in groups])
idx=np.concatenate([np.full(len(g),i) for i,(_,g) in enumerate(groups)])
if n<2 or np.any(times<=0) or np.any(h<=0): raise ValueError('Se requieren vencimientos y spreads positivos')
def decode(x):
theta=np.cumsum(x[:n]); rho=x[-1]
limit=min(np.sqrt(4/(1+abs(rho))),4/(np.sqrt(theta[-1])*(1+abs(rho))))
return theta,x[-2]*limit,rho
def residual(x):
theta,eta,rho=decode(x)
return (np.sqrt(ssvi(k,theta[idx],eta,rho)/times[idx])-vol)/h
initial=np.maximum.accumulate([np.median(g.iv)**2*t for t,g in groups])
increments=np.maximum(np.diff(np.r_[0,initial]),1e-5)
bounds=(np.r_[[1e-8]*n,.0001,-.99],np.r_[[1.]*n,.999,.99])
fits=[least_squares(residual,np.r_[increments,f,r],bounds=bounds,max_nfev=3000,
ftol=1e-12,xtol=1e-12,gtol=1e-12)
for f in (.2,.5,.8) for r in (-.7,-.3,.3)]
opt=min(fits,key=lambda x:np.sum(x.fun*x.fun))
if not opt.success: raise RuntimeError('La optimización no convergió')
theta,eta,rho=decode(opt.x)
pred=np.sqrt(ssvi(k,theta[idx],eta,rho)/times[idx]); error=pred-vol
grid=np.linspace(-3,3,1201); surface=np.array([ssvi(grid,t,eta,rho) for t in theta])
dk=grid[1]-grid[0]; wp=np.gradient(surface,dk,axis=1); wpp=np.gradient(wp,dk,axis=1)
g=(1-grid*wp/(2*surface))**2-wp**2*(1/surface+.25)/4+wpp/2
report={'rmse_iv':np.sqrt(np.mean(error**2)),'median_halfspread':np.median(h),
'rmse_spread':np.sqrt(np.mean((error/h)**2)),
'min_g_grid':g[:,2:-2].min(),'min_calendar_grid':np.diff(surface,axis=0).min(),
'butterfly_margin_1':4-eta*np.sqrt(theta[-1])*(1+abs(rho)),
'butterfly_margin_2':4-eta**2*(1+abs(rho))}
return theta,eta,rho,reportnpm run lab and open the connection link.The positive-increment parameterization guarantees the order of . The factor in (0, 0.999) keeps both butterfly inequalities strictly within the margin at the largest . Sampling is an independent diagnostic approximated by finite differences; it does not replace the analytic condition. Multiple initializations help with local minima but do not prove global optimality. Next compare the quasi-explicit fit with a direct five-parameter fit. Both require , but the direct one also limits to 0.999; their domains do not match exactly and one direct initialization does not certify its optimum.
rng=np.random.default_rng(13)
times=np.array([.1,.3,.7,1.2]); thetas=np.array([.005,.014,.032,.055])
synthetic=[]
for T,theta in zip(times,thetas):
for k in np.linspace(-.4,.4,31):
h=.002; true=np.sqrt(ssvi(k,theta,.6,-.5)/T)
synthetic.append((T,k,true+rng.normal(0,h*.5),h))
syn=pd.DataFrame(synthetic,columns=['T','k','iv','halfspread'])
cut=syn[syn['T']==times[1]]; k=cut.k.to_numpy(); T=times[1]
vol=cut.iv.to_numpy(); h=cut.halfspread.to_numpy(); w=vol**2*T; weights=1/(2*vol*T*h)**2
quasi,loss=fit_svi_slice(k,w,weights)
direct=least_squares(lambda p:(svi(k,*p)-w)*np.sqrt(weights),[.001,.1,-.5,0,.1],
bounds=([1e-12,1e-8,-.999,-1,.01],[1,5,.999,1,2]),max_nfev=5000)
theta,eta,rho,report=fit_surface(syn)
print('SVI cuasiexplícito pérdida',loss,'directo',np.sum(direct.fun**2))
print('SSVI sintético',report,'eta',eta,'rho',rho)
assert report['min_g_grid']>=-1e-5 and report['min_calendar_grid']>=0
assert report['butterfly_margin_1']>0 and report['butterfly_margin_2']>0npm run lab and open the connection link.In the run with seed 13, synthetic IV RMSE was 0.000979 for a half-spread of 0.002; normalized RMSE was 0.4895. The grid minimum of was 0.267 and the smallest variance difference between maturities was 0.00619. These data are an SSVI-generated control with known noise, not a market measurement. Weighted losses for the quasi-explicit slice and direct fit approximately matched at 3.5854 in this run.
Historical chain: check, do not promise
The next cell downloads the daily member of the provider’s sample using range requests, checks its SHA256, and filters five European SPXW maturities with PM settlement. It contains no quote times, so the bands are not verified as simultaneous. Time is approximated by calendar days divided by 365. The forward and discount are midpoint parity regressions in the 3600 to 4200 window, not curves observed without error. Bid and ask IVs are separately inverted with Black, discarding prices without an interior root in the numerical interval.
import io, urllib.request, zipfile, hashlib
from scipy.special import ndtr
from scipy.optimize import brentq
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)
with urllib.request.urlopen(urllib.request.Request(self.url,headers={'Range':f'bytes={self.pos}-{end}'}),timeout=60) as r:
if r.status!=206: raise RuntimeError('El proveedor no admite rangos')
data=r.read()
self.pos+=len(data); return data
url='https://historicaldata.net/file/options_sample_2022H2.zip'
with zipfile.ZipFile(RemoteZip(url)) as z: data=z.read('day_by_date/2022-09-15_options.csv')
assert hashlib.sha256(data).hexdigest()=='054acc61106b15a21a2b166e975a506fb0559b9a8d7ec896817ab5e6eb8c208a'
raw=pd.read_csv(io.BytesIO(data))
d=raw[(raw.underlying=='SPXW')&(raw['style']=='E')&(raw.settlement_time=='PM')].copy()
d=d[(d.bid>=0)&(d.ask>d.bid)&(d.volume>=1)&(d.open_interest>=10)]
def black(F,K,T,D,v,call):
s=v*np.sqrt(T); z=np.log(F/K)/s+s/2
return D*((F*ndtr(z)-K*ndtr(z-s)) if call else (K*ndtr(-z+s)-F*ndtr(-z)))
rows=[]
for expiry in ['2022-09-30','2022-10-14','2022-10-28','2022-11-18','2022-12-16']:
group=d[d.expiration==expiry].copy()
if group.duplicated(['strike','type']).any(): raise ValueError('Contrato duplicado')
pairs=group.pivot(index='strike',columns='type',values=['bid','ask']).dropna()
mids=(pairs['bid']+pairs['ask'])/2
mask=(pairs.index>=3600)&(pairs.index<=4200); K=pairs.index.to_numpy()[mask]
y=(mids['call']-mids['put']).to_numpy()[mask]
if len(K)<5: raise ValueError('Pocos pares para estimar paridad')
intercept,slope=np.linalg.lstsq(np.c_[np.ones(len(K)),K],y,rcond=None)[0]
D=-slope; F=intercept/D
if D<=0 or F<=0: raise ValueError('Forward o descuento inválido')
T=(pd.Timestamp(expiry)-pd.Timestamp('2022-09-15')).days/365
for q in group.itertuples():
if not 3600<=q.strike<=4200: continue
call=q.type=='call'
if call!=(q.strike>=F): continue
def iv(price):
lo=black(F,q.strike,T,D,.0001,call); hi=black(F,q.strike,T,D,4.,call)
if not lo<price<hi: return np.nan
return brentq(lambda s:black(F,q.strike,T,D,s,call)-price,.0001,4.)
v=iv((q.bid+q.ask)/2); vlo=iv(q.bid); vhi=iv(q.ask)
if np.isfinite(v) and np.isfinite(vlo) and np.isfinite(vhi) and vhi>vlo:
rows.append((expiry,T,np.log(q.strike/F),v,(vhi-vlo)/2))
print(expiry,'pares',len(K),'F',F,'D',D,'observaciones',sum(x[0]==expiry for x in rows))
real=pd.DataFrame(rows,columns=['expiry','T','k','iv','halfspread'])
first=real[real.expiry=='2022-09-30']; k=first.k.to_numpy(); T=first['T'].iloc[0]
vol=first.iv.to_numpy(); h=first.halfspread.to_numpy(); w=vol**2*T; weights=1/(2*vol*T*h)**2
quasi,loss=fit_svi_slice(k,w,weights)
direct=least_squares(lambda p:(svi(k,*p)-w)*np.sqrt(weights),[.001,.1,-.5,0,.1],
bounds=([1e-12,1e-8,-.999,-1,.01],[1,5,.999,1,2]),max_nfev=5000)
theta,eta,rho,report=fit_surface(real)
print('SVI cuasiexplícito',quasi,'pérdida',loss,'directo',direct.x,'pérdida',np.sum(direct.fun**2))
print('SSVI histórico theta',theta,'eta',eta,'rho',rho,'diagnóstico',report)npm run lab and open the connection link.This run obtained 389 IVs from the five selected dates. SSVI produced IV RMSE 0.00406 against a median half-spread of 0.000643, and normalized-error RMSE 6.41. The grid minimum of was 0.261 and the smallest variance difference between slices was 0.00123; both sufficient conditions had positive margin. The target error on the order of the half-spread is met in the synthetic control above, but not in this historical sample. The result alone does not establish why the fit fails: family rigidity, noise, forward estimation, and other data differences may contribute.
A good fit in one sample also does not certify synchronization or stability outside it. The objective divided by spread prioritizes narrow bands, and a wrong forward estimate or an isolated observation can dominate the result. Inspect deviations by maturity and strike, check other times, and retain an evaluation sample before using the surface in a pricing system. The September slice fit reached very close to the permitted limit: this warns about identification and is not a robust estimate of a structural parameter.
Exercises
Step 1 of 3. What form does the variance take?
def fit_svi_slice(k,w,weights):
raise NotImplementedError()Ideas to remember
SVI separates an outer search over two parameters from an inner linear fit. SSVI links slices through and ; its sufficient conditions control the stated domain. Spread, vega, and the timing quality of observations determine what a small error means.