Module contents
Stage 7 of 8Advanced 100 min

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.

InteractiveMove the underlying and see the smile
  • Sticky strike
  • Sticky delta
  • SABR
  • Local (Monte Carlo)
100
Sticky-strike delta0.5377
Sticky-delta delta0.6020
Modified SABR delta0.4738
Local delta0.4569
Local delta SE0.0014
Maximum approximate local IV SE0.0017
Shift spot among available scenarios and compare sticky strike, sticky delta, SABR, and the local projection. Local IVs come from Monte Carlo and are shown only at calculated strikes; their values have uncertainty. The scenario shifts spot while retaining the original local field: away from the initial point it includes the extrapolation stated in the lesson.

SABR and the asymptotic formula

Under a forward measure, the SABR smile starts from

 ⁣dFt=αtFtβ ⁣dWtF, ⁣dαt=ναt ⁣dWtα, ⁣d⟨WF,Wα⟩t=ρ ⁣dt.\dd F_t=\alpha_tF_t^\beta\dd W_t^F,\qquad \dd\alpha_t=\nu\alpha_t\dd W_t^\alpha,\qquad \dd\langle W^F,W^\alpha\rangle_t=\rho\dd t.

Assume F,K,α>0F,K,\alpha>0, 0≤β≤10\le\beta\le1, ν≥0\nu\ge0, and ∣ρ∣<1|\rho|<1. β\beta controls the scale dependence of volatility level, ρ\rho couples forward and volatility moves, and ν\nu controls variability in α\alpha. If α\alpha is fixed while FF changes, the ATM scale is approximately α/F1−β\alpha/F^{1-\beta}: this is the backbone. Do not confuse α\alpha with Black volatility unless β=1\beta=1 and corrections are ignored.

With q=1−βq=1-\beta, ℓ=log⁡(F/K)\ell=\log(F/K), A=(FK)q/2A=(FK)^{q/2}, and z=(ν/α)Aℓz=(\nu/\alpha)A\ell, define

x(z)=log⁡1−2ρz+z2+z−ρ1−ρ.x(z)=\log\frac{\sqrt{1-2\rho z+z^2}+z-\rho}{1-\rho}.

The lognormal approximation of Hagan and colleagues is

σB≈αA(1+q2ℓ2/24+q4ℓ4/1920)zx(z)[1+T(q2α224A2+ρβνα4A+(2−3ρ2)ν224)].\sigma_B\approx\frac{\alpha}{A(1+q^2\ell^2/24+q^4\ell^4/1920)}\frac{z}{x(z)} \left[1+T\left(\frac{q^2\alpha^2}{24A^2}+\frac{\rho\beta\nu\alpha}{4A}+\frac{(2-3\rho^2)\nu^2}{24}\right)\right].

At the money z/x(z)→1z/x(z)\to1. To avoid numerical cancellation near zero use 1−ρz/2+(2−3ρ2)z2/121-\rho z/2+(2-3\rho^2)z^2/12. 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 K/FK/F; if the smile branch is invertible, the rule is implemented as σ(F,K)=σ(F0,KF0/F)\sigma(F,K)=\sigma(F_0,KF_0/F). Changing the convention or allowing time to pass can break this equivalence.

In SABR, sensitivity to FF with fixed α\alpha is ΔBlack+Vega ∂FσB\Delta_{\rm Black}+\mathrm{Vega}\,\partial_F\sigma_B. A delta projecting the correlated innovation of α\alpha onto that of FF adds Vega ∂ασB ρν/Fβ\mathrm{Vega}\,\partial_\alpha\sigma_B\,\rho\nu/F^\beta. That is modified Bartlett delta under this convention, not elimination of independent volatility noise. In the figure, the deterministic scenario path integrates  ⁣dα/ ⁣dF=ρν/Fβ\dd\alpha/\dd F=\rho\nu/F^\beta 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 β=0.5\beta=0.5 and fit α,ρ,ν\alpha,\rho,\nu 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.

[ ]Hagan and calibration to synthetic vanillasLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The run produces IV RMSE of approximately 0.000694, 0.000300, and 0.000081 for T=0.5,1,2T=0.5,1,2. 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 α\alpha movement explicit.

Hedging and attribution

For an option priced with Black, call Θ\Theta the calendar-time derivative with spot and volatility fixed. If a hedge hh is held for one step, the second-order hedging PnL attribution is

ΔΠ≈(ΔBlack−h)ΔS+ΘΔt+12Γ(ΔS)2+VegaΔσ+Vanna ΔSΔσ+12Volga(Δσ)2+R.\begin{aligned} \Delta\Pi\approx{}&(\Delta_{\rm Black}-h)\Delta S+\Theta\Delta t+ \tfrac12\Gamma(\Delta S)^2+\mathrm{Vega}\Delta\sigma\\ &+\mathrm{Vanna}\,\Delta S\Delta\sigma+\tfrac12\mathrm{Volga}(\Delta\sigma)^2+R. \end{aligned}

Here RR 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 Θ=−ΓS2σimp2/2\Theta=-\Gamma S^2\sigma_{\rm imp}^2/2. Replacing (ΔS/S)2/Δt(\Delta S/S)^2/\Delta t by realized step variance gives 12ΓS2(σreal2−σimp2)Δt\tfrac12\Gamma S^2(\sigma_{\rm real}^2-\sigma_{\rm imp}^2)\Delta t. 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 N−1/2N^{-1/2} 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 αt=α0vt/v0\alpha_t=\alpha_0\sqrt{v_t/v_0}. 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.

[ ]Hedging in Black and a synthetic Heston worldLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with 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 N−1/2N^{-1/2} 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 ∑i∣Ri∣/∑i∣Πi∣\sum_i|R_i|/\sum_i|\Pi_i| 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 Δσ\Delta\sigma in attribution, the Hagan proxy is extended to τ=0\tau=0; 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 log⁡(S/100)\log(S/100), so changing initial spot intervenes on the same field. It is extended flat outside ∣k∣≤0.6t+0.01|k|\le0.6\sqrt t+0.01; 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.

[ ]Local projection and spot scenariosLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the run with 100,000 paths, for F=100F=100 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

ProofGamma versus theta
Prove: Derive the approximate PnL of a delta-hedged option under Black with zero rates and fixed implied volatility.
0
Over a small step, ΔC ≈ Δ ΔS + Θ Δt + Γ(ΔS)²/2; the hedge holds −Δ shares.

Step 1 of 3. What cancels when adding the hedge?

NumericStraddle gamma
A hedged straddle has Γ = 0.04 per price unit, S = 100, implied volatility 0.20 and realized volatility 0.25. At zero rates and one day of 1/252 year, estimate gamma plus theta PnL.
QuizSign of covariation
In SABR, if ρ is negative, which statement about forward and α innovations is correct?
CodeHagan and its ATM limit
Implement sabr_hagan_vol(F,K,T,alpha,beta,rho,nu), with NumPy arrays for F and K. Use the stable limit of z/x(z) near zero and the lognormal approximation shown in the text.
def sabr_hagan_vol(F,K,T,alpha,beta,rho,nu):
  raise NotImplementedError()
Shift+Enter to run

Ideas to remember

Key idea
Delta depends on how the smile moves; more frequent hedging reduces some discretization error but does not by itself eliminate vega or costs.

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.