SABR, smile dynamics and hedging
Implement SABR with Hagan's approximation by maturity and study how the smile moves as the underlying moves. Simulate delta hedging of an option portfolio using different models and rebalancing frequencies, and decompose PnL into Greeks to understand the remaining risk.
After this lesson you can
- Implement Hagan's formula and calibrate SABR by maturity.
- Compare Black-Scholes delta, sticky strike, sticky delta, and SABR-implied delta.
- Simulate delta hedging and measure hedging error against rebalancing frequency.
- Decompose PnL into delta, gamma, vega, theta, and residual.
Before you start
A smile does not say how it will move
Today’s surface does not specify tomorrow’s smile. To hedge an option you need an assumption about how it changes with the underlying, as well as a current price. A Black delta holds that option’s volatility fixed; another rule may move it with the forward. The difference is vega exposure disguised as delta.
The figure compares rules on the synthetic Heston surface from lesson five and its local projection. The SABR smile is fitted to one maturity; the local smile comes from conditional simulation of the projected field. These are not historical quotes or a market prediction.
SABR and the asymptotic formula
Under a forward measure, the SABR smile starts from
Assume , , , and . controls the scale dependence of volatility level, couples forward and volatility moves, and controls variability in . If is fixed while changes, the ATM scale is approximately : this is the backbone. Do not confuse with Black volatility unless and corrections are ignored.
With , , , and , define
The lognormal approximation of Hagan and colleagues is
At the money . To avoid numerical cancellation near zero use . This is an asymptotic approximation: check prices, convexity, and sensitivity at extreme strikes before extrapolating. Smoothness does not guarantee a nonnegative density or eliminate the problem of noisy quotes.
Four smile movements and four deltas
Under sticky strike, the IV assigned to a nominal strike remains fixed; delta is the usual Black delta. Under sticky delta, the smile remains a function of an agreed Black delta. Different markets use different delta conventions: here we use forward delta without premium or discount, at the same maturity. In that convention, for the same IV, matching deltas is equivalent to matching ; if the smile branch is invertible, the rule is implemented as . Changing the convention or allowing time to pass can break this equivalence.
In SABR, sensitivity to with fixed is . A delta projecting the correlated innovation of onto that of adds . That is modified Bartlett delta under this convention, not elimination of independent volatility noise. In the figure, the deterministic scenario path integrates and sets independent innovation to zero: it visualizes sensitivity, not all SABR paths.
The local projection is different: the conditional smile is calculated by simulating the absolute local field after an initial spot shift. Since the original surface starts from one spot, behavior outside the well-conditioned domain requires an extension; we use the flat extrapolation from the previous lesson. The comparison is therefore a defined numerical scenario, not a universal property of all local surfaces.
Calibrate before hedging
In the experiment we fix and fit to nine synthetic Heston IVs between strikes 80 and 120, without spreads or market data. These are three fits by maturity, not a joint SABR surface automatically free of calendar arbitrage. The objective is unweighted IV because all control data have the same nominal precision; for real quotes, spread and vega should enter the criterion.
import math
import numpy as np
import torch
from scipy.special import ndtr
from scipy.optimize import least_squares, brentq
def sabr_hagan_vol(F,K,T,alpha,beta,rho,nu):
F,K=np.broadcast_arrays(np.asarray(F,float),np.asarray(K,float))
if np.any(F<=0) or np.any(K<=0) or T<0 or alpha<=0 or not 0<=beta<=1 or abs(rho)>=1 or nu<0:
raise ValueError('Parámetros SABR fuera del dominio')
q=1-beta; logfk=np.log(F/K); fk=(F*K)**(q/2); z=nu/alpha*fk*logfk
root=np.sqrt(1-2*rho*z+z*z); x=np.log((root+z-rho)/(1-rho)); small=np.abs(z)<1e-5
zx=np.divide(z,x,out=np.ones_like(z),where=~small)
zx=np.where(small,1-rho*z/2+(2-3*rho*rho)*z*z/12,zx)
den=fk*(1+q*q*logfk**2/24+q**4*logfk**4/1920)
correction=(q*q*alpha*alpha/(24*fk*fk)+rho*beta*nu*alpha/(4*fk)+(2-3*rho*rho)*nu*nu/24)*T
return alpha/den*zx*(1+correction)
# Referencia COS autocontenida de Heston, log(S/F), descuento uno.
heston=(.04,.04,1.5,.3,-.7)
def heston_cf(u,T,p=heston):
v0,theta,kappa,xi,rho=p; beta=kappa-rho*xi*1j*u
d=np.sqrt(beta*beta+xi*xi*(u*u+1j*u)); g=(beta-d)/(beta+d); e=np.exp(-d*T)
C=kappa*theta/xi**2*((beta-d)*T-2*np.log((1-g*e)/(1-g)))
D=(beta-d)/xi**2*(1-e)/(1-g*e)
return np.exp(C+D*v0)
def cos_call(K,T,N=256,L=3.):
K=np.asarray(K,float); a=-L; b=L; u=np.arange(N)*np.pi/(b-a)
chi=(np.cos(-u*a)+u*np.sin(-u*a)-np.exp(a))/(1+u*u)
psi=np.empty_like(u); psi[0]=-a; psi[1:]=np.sin(-u[1:]*a)/u[1:]
H=2/(b-a)*(psi-chi); H[0]*=.5; coef=heston_cf(u,T)*np.exp(-1j*a*u)*H
phase=np.outer(np.log(100/K),u)
return K*(np.cos(phase)@coef.real-np.sin(phase)@coef.imag)+100-K
def black(F,K,T,sigma):
s=sigma*np.sqrt(T); d1=np.log(F/K)/s+s/2
return F*ndtr(d1)-K*ndtr(d1-s)
def implied(F,K,T,price): return brentq(lambda s:black(F,K,T,s)-price,.00001,4.)
strikes=np.arange(80.,121,5); beta=.5; fits={}
for T in (.5,1.,2.):
prices=cos_call(strikes,T); vols=np.array([implied(100,K,T,c) for K,c in zip(strikes,prices)])
opt=least_squares(lambda x:sabr_hagan_vol(100,strikes,T,x[0],beta,x[1],x[2])-vols,
[2.,-.5,.3],bounds=([.01,-.99,.001],[10,.99,2.]))
fits[T]=opt.x
print('T',T,'alpha,rho,nu',opt.x,'RMSE IV',np.sqrt(np.mean(opt.fun**2)),'máximo',max(abs(opt.fun)))npm run lab and open the connection link.The run produces IV RMSE of approximately 0.000694, 0.000300, and 0.000081 for . A good fit to these synthetic points does not certify extrapolation or uniquely identify all parameters. For subsequent experiments we fix parameters fitted at one year and make the rule for movement explicit.
Hedging and attribution
For an option priced with Black, call the calendar-time derivative with spot and volatility fixed. If a hedge is held for one step, the second-order hedging PnL attribution is
Here collects higher-order terms and discretization effects. Hedge trading costs are subtracted separately. At zero rates, fixed implied volatility, and a Black hedge, the Black equation gives . Replacing by realized step variance gives . This is a local approximation, not an identity for a stochastic smile and volatility: vega, vanna, and volga remain present.
Smile dynamics and hedging determine how much of that PnL remains exposed. Under Black without costs and with correctly specified volatility, reducing the step usually takes hedging-error standard deviation toward the scale. In a stochastic-variance world, a delta-only hedge leaves vega risk that can create a floor. More rebalancing also increases traded volume and, with proportional costs, can worsen the net result.
The next laboratory separates the two cases. First it checks scaling under Black. Then it simulates Heston spot and variance with QE-M, using an explicit proxy as the mark: Hagan with one-year parameters and . This rule is not Heston’s exact conditional price or a real chain; it allows study of attribution for a smile changing with variance. The position is a long ATM straddle and the hedge sells the calculated delta. Cost is 0.1% of the traded amount at each intermediate adjustment, with no initial or closing charge. Pre-cost PnL and average cost are printed separately.
device='cuda' if torch.cuda.is_available() else 'cpu'; v0,theta_h,kappa_h,xi_h,rho_h=heston
alpha0,rho_s,nu=fits[1.]; beta=.5; K=100.
def qe_step(v,dt,z1,z2):
e=math.exp(-kappa_h*dt); m=theta_h+(v-theta_h)*e
s2=v*xi_h**2*e*(1-e)/kappa_h+theta_h*xi_h**2*(1-e)**2/(2*kappa_h); psi=s2/(m*m)
q=(2/psi).clamp_min(1); b2=q-1+torch.sqrt(q*(q-1)); a=m/(1+b2)
vq=a*(torch.sqrt(b2)+z1)**2; prob=((psi-1)/(psi+1)).clamp(0,1-1e-7); rate=(1-prob)/m
U=(.5*(1+torch.erf(z1/math.sqrt(2)))).clamp(1e-7,1-1e-7)
ve=torch.where(U<=prob,torch.zeros_like(v),torch.log((1-prob)/(1-U))/rate)
vn=torch.where(psi<=1.5,vq,ve)
K1=.5*dt*(kappa_h*rho_h/xi_h-.5)-rho_h/xi_h
K2=.5*dt*(kappa_h*rho_h/xi_h-.5)+rho_h/xi_h; K3=.5*dt*(1-rho_h**2); K4=K3; A=K2+K4/2
denom=1-2*A*a
if A>=0 and (torch.any(denom<=0) or torch.any(rate<=A)): raise ValueError('Momento exponencial no existe')
log_mq=-.5*torch.log(denom)+A*a*b2/denom; log_me=torch.log(prob+(1-prob)*rate/(rate-A))
K0=-(K1+K3/2)*v-torch.where(psi<=1.5,log_mq,log_me)
return vn,K0+K1*v+K2*vn+torch.sqrt((K3*v+K4*vn).clamp_min(0))*z2
def hagan_torch(S,tau,alpha):
q=1-beta; ell=torch.log(S/K); A=(S*K)**(q/2); z=nu/alpha*A*ell
root=torch.sqrt(1-2*rho_s*z+z*z); x=torch.log((root+z-rho_s)/(1-rho_s))
ratio=torch.where(z.abs()<1e-3,1-rho_s*z/2+(2-3*rho_s**2)*z*z/12,z/x)
den=A*(1+q*q*ell**2/24+q**4*ell**4/1920)
correction=(q*q*alpha*alpha/(24*A*A)+rho_s*beta*nu*alpha/(4*A)+(2-3*rho_s**2)*nu**2/24)*tau
return alpha/den*ratio*(1+correction)
def greeks(S,tau,sigma):
d1=torch.log(S/K)/(sigma*math.sqrt(tau))+sigma*math.sqrt(tau)/2; d2=d1-sigma*math.sqrt(tau)
cdf=lambda x:.5*(1+torch.erf(x/math.sqrt(2))); density=torch.exp(-d1*d1/2)/math.sqrt(2*math.pi)
value=2*(S*cdf(d1)-K*cdf(d2))-(S-K); delta=2*cdf(d1)-1
gamma=2*density/(S*sigma*math.sqrt(tau)); vega=2*S*density*math.sqrt(tau)
theta=-S*density*sigma/math.sqrt(tau); vanna=-2*density*d2/sigma; volga=vega*d1*d2/sigma
return value,delta,gamma,vega,theta,vanna,volga
def bs_benchmark(n,steps):
dt=1/steps; gen=torch.Generator(device=device).manual_seed(400+steps)
S=torch.full((n,),100.,device=device); pnl=torch.zeros_like(S)
for i in range(steps):
tau=1-i*dt; sigma=torch.full_like(S,.2); old,delta,*_=greeks(S,tau,sigma)
Sn=S*torch.exp(-.5*.2**2*dt+.2*math.sqrt(dt)*torch.randn(n,device=device,generator=gen))
new=greeks(Sn,tau-dt,sigma)[0] if i<steps-1 else (Sn-K).abs()
pnl+=new-old-delta*(Sn-S); S=Sn
return pnl.std(unbiased=True).item()
def heston_hedge(n,steps,fee=0.,mode='strike'):
dt=1/steps; gen=torch.Generator(device=device).manual_seed(501)
S=torch.full((n,),100.,device=device); v=torch.full_like(S,v0)
pnl=torch.zeros_like(S); explained=torch.zeros_like(S); cost=torch.zeros_like(S); previous=None
components=torch.zeros(6,device=device)
for i in range(steps):
tau=1-i*dt; alpha=alpha0*torch.sqrt(v.clamp_min(1e-8)/v0); sigma=hagan_torch(S,tau,alpha)
C,delta,gamma,vega,theta,vanna,volga=greeks(S,tau,sigma); hedge=delta
if mode=='sabr':
bump=.01; da=rho_s*nu/(S**beta)*bump
slope=(hagan_torch(S+bump,tau,alpha+da)-hagan_torch(S-bump,tau,alpha-da))/(2*bump)
hedge=delta+vega*slope
if previous is not None: cost+=fee*S*(hedge-previous).abs()
z1=torch.randn(n,device=device,generator=gen); z2=torch.randn(n,device=device,generator=gen)
vn,dx=qe_step(v,dt,z1,z2); Sn=S*torch.exp(dx); dS=Sn-S
sigma_next=hagan_torch(Sn,max(tau-dt,0.),alpha0*torch.sqrt(vn.clamp_min(1e-8)/v0))
Cn=greeks(Sn,tau-dt,sigma_next)[0] if i<steps-1 else (Sn-K).abs()
ds=sigma_next-sigma; pnl+=Cn-C-hedge*dS
terms=[(delta-hedge)*dS,theta*dt,.5*gamma*dS*dS,vega*ds,vanna*dS*ds,.5*volga*ds*ds]
explained+=sum(terms); components+=torch.stack([term.mean() for term in terms])
previous=hedge; S=Sn; v=vn
residual=pnl-explained
print(mode,'pasos',steps,'std PnL bruto',pnl.std(unbiased=True).item(),'coste medio',cost.mean().item(),
'media neta',(pnl-cost).mean().item(),'residuo L1 / PnL L1',residual.abs().mean().item()/pnl.abs().mean().item(),
'componentes medias',components.cpu().numpy())
for steps in (12,52,252): print('Black pasos',steps,'desviación',bs_benchmark(200_000,steps))
for steps in (12,52,252): heston_hedge(100_000,steps,.001,'strike')
heston_hedge(100_000,52,.001,'sabr')npm run lab and open the connection link.In one RTX 3060 run, Black standard deviations were 3.853, 1.901, and 0.877 as rebalances increased from 12 to 52 and 252: the decrease is approximately proportional to in this control. In the Heston proxy with sticky-strike delta they were 5.308, 4.051, and 3.651; they do not keep falling as under Black because IV also changes. Mean costs at 0.1% were 0.213, 0.462, and 1.022 respectively. With 52 steps, modified SABR delta gave standard deviation 3.691 and mean cost 0.477, against 4.051 and 0.462 under sticky strike. These are simulation results, not a universal property of every hedge or an estimate of market costs.
For 252 steps, the gross-attribution ratio was approximately 0.0253, below 5% in this experiment. This is an aggregate absolute-error metric: it does not claim each path’s residual is below 5%, and the denominator can be problematic for individual paths with near-zero PnL. Vanna and volga terms are included before measuring the residual. The simulation also reports comparison with modified SABR delta, without guaranteeing it dominates under other dynamics.
At the final step the option value is the payoff, not a Black price with zero remaining time. To calculate in attribution, the Hagan proxy is extended to ; that terminal volatility is a numerical convention, not quoted IV. The residual includes sensitivity to that convention and expansion errors near maturity.
Reproducing the figure’s local scenarios
The figure does not use an invented rule for the local curve. This cell reconstructs the Dupire projection of the Heston characteristic function, as in the previous lesson, and simulates five initial spots from 90 to 110. The volatility grid stays in absolute coordinates , so changing initial spot intervenes on the same field. It is extended flat outside ; in particular, initially shifted spots depend on that extension. The first step uses the ATM limit 0.2. This is a defined scenario, not an observed market delta.
Each spot is also evaluated with shifts of ±0.1 using the same Brownian increments. Local delta is the mean paired payoff difference divided by 0.2. The standard error shown in the figure is that of those differences; discretization or extrapolation error is not included. Local curves show seven connected simulated values, with IV standard error approximated by price error divided by Black vega.
from threadpoolctl import threadpool_limits
def projected_grid(steps=256,nk=401,N=1024,L=3.):
a=-L; b=L; u=np.arange(N)*np.pi/(b-a); k=np.linspace(-.8,.8,nk); Kgrid=100*np.exp(k)
chi=(np.cos(-u*a)+u*np.sin(-u*a)-np.exp(a))/(1+u*u)
psi=np.empty_like(u); psi[0]=-a; psi[1:]=np.sin(-u[1:]*a)/u[1:]
H=2/(b-a)*(psi-chi); H[0]*=.5
density_weight=np.full(N,2/(b-a)); density_weight[0]*=.5
phase=np.outer(-k-a,u); c=np.cos(phase); s=np.sin(phase); denphase=np.cos(np.outer(k-a,u))
beta_h=kappa_h-rho_h*xi_h*1j*u; d=np.sqrt(beta_h**2+xi_h**2*(u*u+1j*u)); g=(beta_h-d)/(beta_h+d)
result=[]
with threadpool_limits(limits=1,user_api='blas'):
for i in range(1,steps):
t=i/steps; e=np.exp(-d*t); D=(beta_h-d)/xi_h**2*(1-e)/(1-g*e)
Dprime=.5*xi_h**2*D*D+(rho_h*xi_h*1j*u-kappa_h)*D-.5*(u*u+1j*u)
phi=heston_cf(u,t); phit=phi*(kappa_h*theta_h*D+v0*Dprime); coef=phit*H
ct=Kgrid*([email protected]@coef.imag)
density=denphase@(np.real(phi*np.exp(-1j*u*a))*density_weight)
radius=.6*np.sqrt(t)+.01; mask=np.abs(k)<=radius
if np.any(density[mask]<=0) or np.any(ct[mask]<=0): raise ValueError('Proyección no positiva')
local2=2*ct/(Kgrid*density); left=np.searchsorted(k,-radius); right=np.searchsorted(k,radius)-1
local2[:left]=local2[left]; local2[right+1:]=local2[right]; result.append(np.sqrt(local2))
return np.asarray(result)
grid=torch.tensor(projected_grid(),device=device,dtype=torch.float32)
spots=np.array([90.,95.,100.,105.,110.]); bumps=np.array([-.1,0.,.1]); initial=(spots[:,None]+bumps).reshape(-1)
n=100_000; steps=256; dt=1/steps; gen=torch.Generator(device=device).manual_seed(37)
x=torch.log(torch.tensor(initial/100,device=device,dtype=torch.float32))[:,None].expand(-1,n).clone()
for i in range(steps):
z=torch.randn(n,device=device,generator=gen)
if i==0: sigma=torch.full_like(x,.2)
else:
coordinate=((x+.8)/.004).clamp(0,399.999); j=coordinate.floor().long(); f=coordinate-j
sigma=grid[i-1,j]*(1-f)+grid[i-1,j+1]*f
x+=-.5*sigma*sigma*dt+sigma*math.sqrt(dt)*z[None,:]
if not torch.isfinite(x).all(): raise ValueError('Trayectorias no finitas')
terminal=100*torch.exp(x); strikes=np.array([85.,90.,95.,100.,105.,110.,115.])
for i,F in enumerate(spots):
center=terminal[3*i+1]; vols=[]; iv_se=[]
for strike in strikes:
payoff=(center-strike).clamp_min(0); price=payoff.mean().item(); se=payoff.std(unbiased=True).item()/math.sqrt(n)
sigma=implied(F,strike,1.,price); d1=np.log(F/strike)/sigma+sigma/2
vega=F*np.exp(-d1*d1/2)/np.sqrt(2*np.pi); vols.append(sigma); iv_se.append(se/vega)
plus=(terminal[3*i+2]-100).clamp_min(0); minus=(terminal[3*i]-100).clamp_min(0); delta=(plus-minus)/.2
print('spot',F,'IV',vols,'SE IV aprox',iv_se,'delta local',delta.mean().item(),'SE delta',delta.std(unbiased=True).item()/math.sqrt(n))npm run lab and open the connection link.In the run with 100,000 paths, for local delta was 0.45691 with paired SE 0.00139 and ATM IV was 0.18793 with approximate IV SE 0.00082. The Monte Carlo price uses a finite grid and extrapolation, so small discrepancies from the initial COS curve neither prove nor disprove exact equality in the continuous limit.
Exercises
Step 1 of 3. What cancels when adding the hedge?
def sabr_hagan_vol(F,K,T,alpha,beta,rho,nu):
raise NotImplementedError()Ideas to remember
PnL attribution requires defining the mark, the Greeks, and the horizon. The residual is a numerical diagnostic, not an automatic measure of profitability or skill.