Stochastic volatility, jumps and calibration
Study Heston, jump-diffusion and SABR models, Fourier pricing, simulation, calibration and smile dynamics.
After this lesson you can
- Write Heston's model, derive its characteristic function and explain Feller's condition and parameter effects.
- Price European options using COS and Carr-Madan while controlling truncation and term count.
- Simulate Heston with Andersen's nonnegative-variance QE scheme and compare truncated Euler.
- Calibrate Heston and Merton to a noisy surface and diagnose weakly identified parameters.
- Apply the SABR asymptotic formula and compare local and stochastic-volatility smile dynamics.
Before you start
- 28Implied volatilityVolatility smile, skew and term structureDupire local volatilitySVI parametrizationMartingale pricing and change of numeraireMonte Carlo option pricingOption Greeks
- 26CIR process and Feller conditionExact simulation of SDEsCompound Poisson process
- 04Characteristic function
- 09Discrete Fourier transform and FFTGaussian quadrature
- 06Levenberg-Marquardt methodGauss-Newton method
- 29Structural and practical identifiability
One surface, several dynamics
Local volatility can reproduce today’s European prices under Dupire’s assumptions, but those prices do not identify the underlying’s temporal dependence. Pricing path-dependent derivatives or estimating hedges requires additional dynamics. An observed smile does not by itself prove the following model true.
In the Heston model, under a risk-neutral measure and zero dividend,
determines the instantaneous level; is the long-run mean and the mean-reversion speed. is volatility of variance. Negative correlation often tilts the smile: price falls accompanied by variance increases represent a mechanism consistent with the leverage effect. Curvature and maturities depend on several parameters at once.
The Feller condition makes zero unattainable for a CIR variance started positive under usual assumptions. If it fails, zero may be reached but the continuous solution remains nonnegative. Naive Euler can produce negative variances: a numerical correction must state its bias.
Characteristic function and Fourier
For , the affine property lets us write . Substituting this form into the pricing equation converts the PDE into Riccati equations for .
In time to maturity, with , the equations are
The linear term in contains correlation, while the quadratic term comes from variance diffusion. The following closed-form solution is one way to solve those equations; checking and provides basic convention and drift checks, though it does not verify all complex values.
The complex square root and logarithm need a continuous convention. The form reduces discontinuities in the original expression but does not remove the need to check branches, integrability and stability for the parameters and contours used. This difficulty is known as the Heston trap. The original paper is Heston (1993).
Fourier pricing uses without reconstructing paths. COS approximates density on with cosines and integrates its coefficients against payoff:
The prime indicates that the zero term has half weight. It is useful to calculate the bounded put and recover the call by parity; direct call coefficients can suffer cancellation on wide windows. Large does not repair a window truncating probability. Fang and Oosterlee study COS convergence.
Carr-Madan damps the call in log-strike with and transforms the result. The integral uses ; the corresponding exponential moment must exist. The lab’s quadrature evaluates the integral directly without claiming an FFT. Compare maximum frequency, step and damping, in addition to and window in COS.
With , one convention for that inversion is
The integrand contains the characteristic function of , not a centered return; mixing conventions shifts price. In practice the integral is truncated and discretized: stability when extending the limit and refining the grid is a check, not a general proof of accuracy.
Simulation, jumps and SABR
Andersen’s QE scheme approximates the conditional law of by matching its CIR mean and variance. For small ratio it uses a Gaussian square; for large a mixture of point mass at zero and an exponential tail. This preserves nonnegative variance, but price discretization remains. The lab also measures discounted mean to detect martingale bias. The implemented variant applies no additional martingale correction. See Andersen (2008).
With , the conditional moments matched are
The quadratic branch uses and the other assigns probability to zero and an exponential tail. Correlation enters the log-price step through and new variance. Matching the first two moments does not make the entire simulated transition exact.
In the Merton jump-diffusion model, is the log jump and . With , compensation preserves risk-neutral drift. Conditioning on jump count,
The sum must be truncated with a tail bound or check. Jumps can produce pronounced wings at short maturities; risk-neutral parameters incorporate risk premiums and are not automatically physical frequencies. The source is Merton (1976).
Omitted Poisson mass alone does not bound call value without considering underlying growth. Since payoff is at most , a bound on discounted value of terms with is , where is Poisson with mean . This tilted law appears when each weight is multiplied by conditional mean . In the fit, the cell uses 40 terms and bounded parameters; that tail can be checked when changing bounds.
The SABR model describes a forward and stochastic volatility : , , correlation . The asymptotic formula of Hagan and coauthors approximates Black volatility as a function of ; the code implements it and uses the continuous limit when . This is an expansion, not an exact price: near low strikes and for long maturities or extreme parameters it may fail and generate arbitrage.
For , set and . The approximation is
where and near the money. The lab fixes to reduce fit dimensionality; freeing can worsen identifiability.
Calibration and identifiability
Calibration minimizes discrepancies between quotes and model prices. Inverse-vega weighting approximates volatility error, though very small vega needs a floor to avoid huge weights. Bid-ask, synchronization, parameter bounds, multiple seeds and out-of-sample checking matter as much as the optimizer.
A flat valley means several combinations can produce close prices in the observed set. A good fit does not guarantee unique parameters or good hedging. Check other maturities, volatility-sensitive instruments and stability across dates without treating those data as an automatic guarantee.
The residual Jacobian with respect to parameters helps locate weak directions: a small singular value means a combined change alters quotes little on the chosen scale. This is a local observation depending on weights, units and data; an error surface does not identify all minima of a five-dimensional problem. The chart deliberately fixes three parameters while the lab fits all five.
Smile dynamics and hedging
Smile dynamics affect effective delta. Sticky strike freezes volatility at each strike as the underlying moves; sticky delta approximately maintains shape in delta coordinates. These are scenario rules, not universal identities. Local diffusion or Heston predict shifts depending on state and parameterization, not always one of those extremes.
In Heston, if also moves when changes, scenario delta incorporates that covariation. In local diffusion the local-volatility function stays fixed in price-time coordinates; freezing the implied smile by strike would be another scenario. Choosing between models with the same current fit requires information about later dynamics and hedging, not just today’s RMSE.
Lab: Heston from start to finish
The first cell implements the characteristic function, COS, Carr-Madan quadrature and QE. The COS window is centered on exact mean log-price; its width is a chosen rule, not a tail-coverage guarantee. QE uses two CIR moments and an approximate log-price step.
import numpy as np
from scipy.special import ndtr
from scipy.integrate import simpson
from scipy.optimize import brentq
def bs(S,K,r,T,s):
d1=(np.log(S/K)+(r+.5*s*s)*T)/(s*np.sqrt(T)); d2=d1-s*np.sqrt(T)
return S*ndtr(d1)-K*np.exp(-r*T)*ndtr(d2)
def heston(u,S,r,T,p):
v0,theta,kappa,xi,rho=p; iu=1j*u; beta=kappa-rho*xi*iu
d=np.sqrt(beta*beta+xi*xi*(u*u+iu)); g=(beta-d)/(beta+d); e=np.exp(-d*T)
C=iu*(np.log(S)+r*T)+kappa*theta/(xi*xi)*((beta-d)*T-2*np.log((1-g*e)/(1-g)))
D=(beta-d)/(xi*xi)*(1-e)/(1-g*e)
return np.exp(C+D*v0)
def cos_price(S,K,r,T,p,N=256,L=10):
v0,theta,kappa,xi,rho=p
c1=np.log(S/K)+r*T-.5*(theta*T+(v0-theta)*(1-np.exp(-kappa*T))/kappa)
a,b=c1-L*np.sqrt(max(v0,theta)*T+.05*T*T),c1+L*np.sqrt(max(v0,theta)*T+.05*T*T)
if a>=0: return S-K*np.exp(-r*T)
u=np.arange(N)*np.pi/(b-a); c=a; d=min(0,b)
psi=np.empty(N); psi[0]=d-c; psi[1:]=(np.sin(u[1:]*(d-a))-np.sin(u[1:]*(c-a)))/u[1:]
chi=(np.exp(d)*(np.cos(u*(d-a))+u*np.sin(u*(d-a)))-np.exp(c)*(np.cos(u*(c-a))+u*np.sin(u*(c-a))))/(1+u*u)
V=2*K/(b-a)*(psi-chi); V[0]*=.5
put=np.exp(-r*T)*np.sum(np.real(heston(u,S,r,T,p)*np.exp(-1j*u*(np.log(K)+a)))*V)
return put+S-K*np.exp(-r*T)
def carr(S,K,r,T,p,alpha=1.5,U=200,n=4097):
u=np.linspace(0,U,n); z=u-1j*(alpha+1); phi=heston(z,S,r,T,p)
den=alpha*alpha+alpha-u*u+1j*(2*alpha+1)*u
return np.exp(-alpha*np.log(K)-r*T)/np.pi*simpson(np.real(np.exp(-1j*u*np.log(K))*phi/den),x=u)
def qe(S,r,T,p,N=100000,steps=100,seed=42):
v0,theta,kappa,xi,rho=p; rng=np.random.default_rng(seed); dt=T/steps; v=np.full(N,v0); x=np.full(N,np.log(S)); exp=np.exp(-kappa*dt)
K0=-rho*kappa*theta*dt/xi; K1=.5*dt*(kappa*rho/xi-.5)-rho/xi; K2=.5*dt*(kappa*rho/xi-.5)+rho/xi; K3=.5*dt*(1-rho*rho); K4=K3
for _ in range(steps):
m=theta+(v-theta)*exp; s2=v*xi*xi*exp*(1-exp)/kappa+theta*xi*xi*(1-exp)**2/(2*kappa); psi=s2/(m*m)
z=rng.standard_normal(N); u=rng.random(N); vn=np.empty(N); low=psi<=1.5
b2=2/psi[low]-1+np.sqrt(2/psi[low])*np.sqrt(2/psi[low]-1); a=m[low]/(1+b2); vn[low]=a*(np.sqrt(b2)+z[low])**2
prob=(psi[~low]-1)/(psi[~low]+1); beta=(1-prob)/m[~low]; vn[~low]=np.where(u[~low]<=prob,0,np.log((1-prob)/(1-u[~low]))/beta)
x+=r*dt+K0+K1*v+K2*vn+np.sqrt(K3*v+K4*vn)*rng.standard_normal(N); v=vn
payoff=np.maximum(np.exp(x)-100,0)*np.exp(-r*T); return payoff.mean(),payoff.std(ddof=1)/np.sqrt(N),np.mean(np.exp(x-r*T))p=(.04,.04,1.5,.5,-.7)
print('φ(0)',heston(0,100,.03,1,p),'φ(-i)',heston(-1j,100,.03,1,p),'forward',100*np.exp(.03))
for T in [.25,1,2]:
for K in [80,100,120]: print(T,K,cos_price(100,K,.03,T,p),carr(100,K,.03,T,p))
print('QE',qe(100,.03,1,p))
from scipy.optimize import least_squares
from scipy.stats import poisson
print('cota de cola Merton en límites del ajuste',100*poisson.sf(39,3*np.exp(.2+.6**2/2)))
def merton(S,K,r,T,sig,lam,muj,sj):
kappa=np.exp(muj+.5*sj*sj)-1; result=0.; weight=np.exp(-lam*T)
for n in range(40):
Sn=S*np.exp(-lam*kappa*T+n*(muj+.5*sj*sj)); sn=np.sqrt(sig*sig+n*sj*sj/T)
result+=weight*bs(Sn,K,r,T,sn); weight*=lam*T/(n+1)
return result
def sabr(F,K,T,alpha,beta,rho,nu):
z=np.log(F/K); power=(F*K)**((1-beta)/2); zz=nu/alpha*power*z
if abs(zz)<1e-7: ratio=1-.5*rho*zz+(2-3*rho*rho)*zz*zz/12
else: ratio=zz/np.log((np.sqrt(1-2*rho*zz+zz*zz)+zz-rho)/(1-rho))
den=power*(1+(1-beta)**2*z*z/24+(1-beta)**4*z**4/1920)
correction=1+T*((1-beta)**2*alpha*alpha/(24*power*power)+rho*beta*nu*alpha/(4*power)+(2-3*rho*rho)*nu*nu/24)
return alpha/den*ratio*correction
def iv(p,S,K,r,T): return brentq(lambda s:bs(S,K,r,T,s)-p,1e-4,3)
# Synthetic Heston quotes with fixed, bounded noise in price; calibrate five params.
rng=np.random.default_rng(281616); times=[.5,1,2]; strikes=[80,90,100,110,120]; pairs=[(T,K) for T in times for K in strikes]
true=(.04,.04,1.5,.5,-.7); clean=np.array([cos_price(100,K,.03,T,true,96,10) for T,K in pairs]); obs=clean+rng.uniform(-.02,.02,len(clean))
weights=np.array([max(.5,100*np.sqrt(T)*np.exp(-.5*((np.log(100/K)+(.03+.5*.2**2)*T)/(.2*np.sqrt(T)))**2)/np.sqrt(2*np.pi)) for T,K in pairs])
def residual(p):return np.array([cos_price(100,K,.03,T,p,96,10) for T,K in pairs])/weights-obs/weights
for x in [[.03,.06,1,.3,-.3],[.06,.03,2.5,.7,-.8]]:
fit=least_squares(residual,x,bounds=([.005,.005,.2,.1,-.95],[.2,.2,4,1,.95]),max_nfev=300,xtol=1e-9,ftol=1e-9,gtol=1e-9)
print('Heston fit',np.round(fit.x,5),'RMSE vols approx',np.sqrt(np.mean(fit.fun**2)))
# Three independent noise draws: fit separate Merton or SABR to each maturity.
for day in range(3):
for T in [.25,1.]:
Ks=np.linspace(80,120,9); clean=np.array([merton(100,K,.03,T,.17,.8,-.08,.18) for K in Ks]); obs=clean+rng.uniform(-.01,.01,len(Ks)); vols=np.array([iv(P,100,K,.03,T) for K,P in zip(Ks,obs)]); F=100*np.exp(.03*T)
fm=least_squares(lambda p: np.array([merton(100,K,.03,T,*p) for K in Ks])-obs,[.16,.6,-.05,.15],bounds=([.05,.01,-.4,.01],[.5,3,.2,.6]),max_nfev=200)
fs=least_squares(lambda p:np.array([sabr(F,K,T,p[0],.5,p[1],p[2]) for K in Ks])-vols,[2.,-.3,.4],bounds=([.05,-.95,.01],[10,.95,3]),max_nfev=200)
merton_vols=np.array([iv(merton(100,K,.03,T,*fm.x),100,K,.03,T) for K in Ks])
rmse_m=np.sqrt(np.mean((merton_vols-vols)**2));rmse_s=np.sqrt(np.mean(fs.fun**2))
print('dia',day,'T',T,'Merton',np.round(fm.x,4),'SABR',np.round(fs.x,4),'RMSE vol común Merton/SABR',round(rmse_m,6),round(rmse_s,6))In this run, the nine COS and Carr-Madan prices differ by at most 4.58e-7; the one-year ATM call is approximately 8.80266. QE with 100,000 paths and 100 steps gives 8.76124 with standard error 0.03166 and discounted mean 99.89848 versus 100: the discrepancy includes discretization and noise and does not prove exact equivalence. Two optimization seeds lead to very close parameters in this example; that does not prove uniqueness. Fifteen synthetic prices with uniform noise amplitude 0.02 and vega weights floored at 0.5 are calibrated.
The second code section separately fits Merton and SABR to three Merton price-noise realizations. For the fit bounds and maximum one-year maturity, the tail bound after 40 terms is approximately 8.29e-23 price units. The fitting objectives differ: Merton minimizes price error and SABR volatility error. To compare them, Merton prices are inverted to Black volatility and RMSE is calculated for both over the same nine options on each day and maturity. For example, at one year estimated Merton intensity varies approximately between 0.76 and 1.00 despite a small fitting error. These are not real days or empirical evidence: this is a sensitivity test to known perturbations.
In the first realization, common volatility RMSE for Merton and SABR is respectively 0.000588 and 0.001168 at three months, and 0.000185 and 0.000259 at one year. The generating surface belongs to Merton; this comparison does not show Merton fits other surfaces better. Other realizations and parameters appear in the output.
def euler(S,r,T,p,N=100000,steps=100,seed=42):
v0,theta,kappa,xi,rho=p; rng=np.random.default_rng(seed); dt=T/steps
v=np.full(N,v0); x=np.full(N,np.log(S)); negative=0
for _ in range(steps):
z=rng.standard_normal(N); z2=rng.standard_normal(N); vp=np.maximum(v,0)
x+=(r-.5*vp)*dt+np.sqrt(vp*dt)*(rho*z+np.sqrt(1-rho*rho)*z2)
v+=kappa*(theta-vp)*dt+xi*np.sqrt(vp*dt)*z
negative+=int(np.count_nonzero(v<0))
payoff=np.exp(-r*T)*np.maximum(np.exp(x)-100,0)
return payoff.mean(),payoff.std(ddof=1)/np.sqrt(N),negative/(N*steps)
for steps in [25,100,400]:
print('pasos',steps,'Euler',euler(100,.03,1,p,N=20000,steps=steps),
'QE',qe(100,.03,1,p,N=20000,steps=steps))Euler uses full truncation in coefficients, but the auxiliary state can be negative; the third value counts that frequency. QE figures include discounted mean. Refining the step can reduce bias, while Monte Carlo error depends on path count; method seeds and samples do not produce a paired comparison.
Reconstruct the smile comparison
The cell derives a Dupire grid from Heston prices in the first cell. Finite differences in price and time amplify tail error: quotients outside variance interval [0.0025,1] are discarded and valid values interpolated in strike, with constant extension at endpoints. Volatility 0.2 is used until t = 0.02 and boundaries extended for states outside [60,150]. Local diffusion is simulated with 20,000 paths and 80 steps, using common random numbers for four initial values. This is an explicit approximation, not exact surface equality. Columns show strike, price, implied volatility, price standard error and, for S = 100, reference Heston price. The central difference using S = 99 and 101 approximates local delta at K = 100.
p=(.04,.04,1.5,.5,-.7); S=100.;r=.03; Ks=np.linspace(60,150,91); ts=np.linspace(.02,1.,50); grid=np.empty((len(ts),len(Ks))); invalid=0
def cos_many(K,T):
v0,theta,kappa,xi,rho=p; K=np.asarray(K)
c1=np.log(S/K)+r*T-.5*(theta*T+(v0-theta)*(1-np.exp(-kappa*T))/kappa)
width=12*np.sqrt(max(v0,theta)*T+.05*T*T); a=c1-width; b=c1+width
u=np.arange(256)[None,:]*np.pi/(b-a)[:,None]; aa=a[:,None]; d=np.minimum(0,b)[:,None]
psi=np.empty_like(u);psi[:,0]=(d-aa)[:,0];psi[:,1:]=(np.sin(u[:,1:]*(d-aa))-np.sin(u[:,1:]*(aa-aa)))/u[:,1:]
chi=(np.exp(d)*(np.cos(u*(d-aa))+u*np.sin(u*(d-aa)))-np.exp(aa))/(1+u*u)
V=2*K[:,None]/(b-a)[:,None]*(psi-chi);V[:,0]*=.5
put=np.exp(-r*T)*np.sum(np.real(heston(u,S,r,T,p)*np.exp(-1j*u*(np.log(K)[:,None]+aa)))*V,axis=1)
return np.where(a>=0,S-K*np.exp(-r*T),put+S-K*np.exp(-r*T))
for i,T in enumerate(ts):
dk=.5;dt=.005
c=cos_many(Ks,T);kp=cos_many(Ks+dk,T);km=cos_many(Ks-dk,T)
ct=(cos_many(Ks,T+dt)-cos_many(Ks,T-dt))/(2*dt)
ck=(kp-km)/(2*dk);ckk=(kp-2*c+km)/(dk*dk)
with np.errstate(divide='ignore',invalid='ignore'): local=np.where(ckk>1e-8,(ct+r*Ks*ck)/(.5*Ks*Ks*ckk),np.nan)
valid=np.isfinite(local)&(local>=.0025)&(local<=1.); invalid+=np.count_nonzero(~valid)
grid[i]=np.sqrt(np.where(valid,local,np.nan))
# interpolación en strike y extensión constante en los extremos
valid=np.isfinite(grid[i]); grid[i]=np.interp(Ks,Ks[valid],grid[i,valid])
print('invalid cells',invalid,'/',grid.size,'range',grid.min(),grid.max())
N=20000;steps=80;dt=1/steps;rng=np.random.default_rng(281616);z=rng.standard_normal((steps,N))
spots=np.array([99.,100.,101.,105.]); paths=np.broadcast_to(spots[:,None],(4,N)).copy(); boundary=np.zeros(4,int)
for i in range(steps):
t=(i+.5)*dt; boundary+=np.sum((paths<60)|(paths>150),axis=1)
if t<.02: vol=np.full_like(paths,.2)
else:
j=min(np.searchsorted(ts,t)-1,len(ts)-2); w=(t-ts[j])/(ts[j+1]-ts[j])
vol=(1-w)*np.interp(paths,Ks,grid[j])+w*np.interp(paths,Ks,grid[j+1])
paths*=np.exp((r-.5*vol*vol)*dt+vol*np.sqrt(dt)*z[i])
for row,spot in enumerate(spots):
S0=paths[row]
Ks2=np.arange(75,131,5); vals=[]
for K in Ks2:
payoff=np.exp(-r)*np.maximum(S0-K,0);c=payoff.mean();lo,hi=.001,2.
for j in range(40):
m=(lo+hi)/2
if bs(spot,K,r,1,m)<c:lo=m
else:hi=m
vals.append((K,c,(lo+hi)/2,payoff.std(ddof=1)/np.sqrt(N),cos_price(100,K,r,1,p) if spot==100 else 0))
print('spot',spot,'boundary fraction',boundary[row]/(N*steps),'discounted mean',np.exp(-r)*S0.mean());print('result',vals)The run replaces 206 of 4550 cells and, with initial S 100, 1.13% of states per step use boundary extension. The local ATM call is 8.86695 with standard error 0.07090 versus Heston’s 8.80266. With S = 105, 0.56% use that extension. Approximate local delta is 0.4850, calculated with the same innovations for both shifts; these diagnostics do not certify the wings or real market dynamics.
Exercises
Step 1 of 3. What is the log-price distribution conditional on N = n?
def cos_price(cf,S,K,r,T,N,L):
raise NotImplementedError()Ideas to remember
Heston and Merton introduce different dynamics that can fit similar prices. COS and Carr-Madan require checking truncation and complex branches; QE preserves nonnegativity of approximate variance but does not eliminate all bias. Calibration is an inverse problem and today’s smile does not certify future hedging.