Heston: characteristic function, Fourier pricing and calibration
Derive Heston's characteristic function, implement its stable form for the complex logarithm discontinuity, and price options using Carr-Madan and COS. Calibrate Heston to the surface with Levenberg-Marquardt in implied volatility and study parameter identifiability using synthetic surfaces.
After this lesson you can
- Derive Heston's characteristic function using the associated Riccati equation.
- Implement the stable formulation and price with Carr-Madan and COS.
- Calibrate Heston with Levenberg-Marquardt and analytic or automatic gradients.
- Diagnose parameter identifiability using the Jacobian and repeated calibrations.
Before you start
- P03Robust implied volatility inversionArbitrage-free calibration
- 28Heston modelRisk-neutral measure
- 04Characteristic functionUniqueness and Fourier inversion
- 09Discrete Fourier transform and FFTComposite Newton-Cotes rulesGaussian quadrature
- 06Gauss-Newton methodLevenberg-Marquardt method
- 02Singular value decompositionCondition number of a matrix
A smile generated by random variance
Local volatility assigns a deterministic intensity to each level and time. The Heston (1993) model adds another source of randomness: variance itself evolves and can correlate with the asset. Under the risk-neutral measure, with deterministic rates and dividends,
is initial variance, its reversion level, its speed, the volatility of variance, and the correlation. With , CIR variance is nonnegative. The Feller condition makes zero unreachable from positive variance; violating it does not make the model invalid, but the boundary can be reached and the numerical scheme must handle it.
Riccati and the characteristic function
Let with . The Heston characteristic function is . The affine structure suggests . Substituting this ansatz into the Kolmogorov backward equation and grouping the constant and the coefficient of gives
The term appears because of the log-price drift . With , , choose the root with nonnegative real part and . A stable form is
Direct verification gives . Under the martingale assumptions used here, because has expectation one. The formula must be evaluated with attention to roots, logarithms, and complex moments: copying an algebraically equivalent expression and independently calling the principal logarithm at each frequency is insufficient.
In the alternative formulation, the argument may cross the principal logarithm’s branch cut. Its phase jumps between and even though the continuous logarithm needed by the Riccati solution follows another branch. In the figure’s example, two crossings appear at and three at on the stated grid; these are counts for that discretization. The form with avoids explosive exponential growth for this parameterization. The analysis by Albrecher and colleagues explains the trap and choice of representation.
COS and Carr-Madan
Fourier pricing converts a known characteristic function into prices by integration or series. Carr and Madan damp the call by an exponential factor so its transform is integrable and apply an FFT on a log-strike grid. The damping parameter requires the corresponding complex moment to exist; a finite program result does not prove that assumption. Frequency spacing determines both strike spacing and grid width: interpolating a call between nodes introduces another error. See Carr and Madan.
The COS method of Fang and Oosterlee approximates density on an interval with cosines. For a put, it integrates the payoff on , sums cosine coefficients weighted by the characteristic function, and recovers the call by parity. Using the put limits amplification of in right wings. The number of terms controls the series, but the interval must also cover the tails: increasing with fixed does not correct truncated mass. Fast convergence depends on regularity and interval choice; it is not a uniform exponential guarantee for every parameter or payoff.
Laboratory: two pricers and three comparisons
We use , discount one, and parameters . These are synthetic parameters, not a market calibration. The fixed interval refers to ; for other maturities or wings, expand it and check convergence. The first cell implements the characteristic function, COS on puts, and Carr-Madan FFT. The last calculation interpolates on the FFT grid, so it should not match COS bit for bit.
import math,time
import numpy as np
from scipy.special import ndtr
from scipy.optimize import brentq
def cf(u,T,p):
v0,theta,kappa,xi,rho=p; u=np.asarray(u,complex)
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_price(F,K,T,p,N=256,L=3.):
K=np.atleast_1d(np.asarray(K,float)); a=-L; b=L; u=np.arange(N)*np.pi/(b-a)
def chi(c,d):
return (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)
def psi(c,d):
out=np.empty_like(u); out[0]=d-c
out[1:]=(np.sin(u[1:]*(d-a))-np.sin(u[1:]*(c-a)))/u[1:]
return out
H=2/(b-a)*(psi(a,0)-chi(a,0)); H[0]*=.5
phase=np.outer(np.log(F/K),u); coef=cf(u,T,p)*np.exp(-1j*a*u)*H
put=K*(np.cos(phase)@coef.real-np.sin(phase)@coef.imag)
return put+F-K
def carr_madan(F,T,p,N=2**14,eta=.04,alpha=1.2):
u=np.arange(N)*eta; spacing=2*np.pi/(N*eta); b=N*spacing/2
x=-b+np.arange(N)*spacing
psi=cf(u-(alpha+1)*1j,T,p)/(alpha**2+alpha-u**2+1j*(2*alpha+1)*u)
weights=np.ones(N)*eta; weights[0]*=.5
values=F*np.exp(-alpha*x)/np.pi*np.real(np.fft.fft(np.exp(1j*b*u)*psi*weights))
return x,values
def black(F,K,T,vol):
s=vol*np.sqrt(T); z=np.log(F/K)/s+s/2
return F*ndtr(z)-K*ndtr(z-s)
def implied(F,K,T,c):
return brentq(lambda vol:black(F,K,T,vol)-c,.00001,4)
p=(.04,.04,1.5,.3,-.7); K=np.array([80.,90.,100.,110.,120.])
print('φ(0)',cf(0,1,p),'φ(-i)',cf(-1j,1,p))
for N in (64,128,256,512): print('COS N',N,cos_price(100,K,1,p,N))
x,prices=carr_madan(100,1,p)
print('FFT interpolada',np.interp(np.log(K/100),x,prices))npm run lab and open the connection link.For the five strikes yield approximately 21.69949, 13.81020, 7.54027, 3.32467, and 1.12459. Comparing with 256 checks the series in this case, not the tail. Change and independently to distinguish truncation from resolution. For FFT, reduce the log-strike step or interpolate carefully before attributing the difference to the pricing method.
The independent comparison uses QuantLib 1.44. Install it in your local environment with python -m pip install QuantLib==1.44 before running this cell. Dates are exactly 365 days apart under Actual365Fixed, with zero rate and dividend curves; therefore , , and discount one as in COS.
import QuantLib as ql
today=ql.Date(1,1,2025); expiry=today+365; ql.Settings.instance().evaluationDate=today
rate=ql.YieldTermStructureHandle(ql.FlatForward(today,0.,ql.Actual365Fixed()))
spot=ql.QuoteHandle(ql.SimpleQuote(100.)); v0,theta,kappa,xi,rho=p
process=ql.HestonProcess(rate,rate,spot,v0,kappa,theta,xi,rho)
engine=ql.AnalyticHestonEngine(ql.HestonModel(process)); reference=[]
for strike in K:
option=ql.VanillaOption(ql.PlainVanillaPayoff(ql.Option.Call,float(strike)),ql.EuropeanExercise(expiry))
option.setPricingEngine(engine); reference.append(option.NPV())
ours=cos_price(100,K,1.,p)
print('QuantLib',ql.__version__,'COS',ours,'referencia',reference,'máximo error',np.max(np.abs(ours-reference)))npm run lab and open the connection link.In the verified run, maximum COS error against QuantLib was in price units for the five contracts. This comparison depends on the stated conventions and interval; it does not certify the entire parameter space. The next cell measures warmed-up batch evaluation, excluding package downloads and compilation. Times depend on CPU, BLAS, and shared load.
strikes=np.linspace(80,120,1000); cos_price(100,strikes,1,p)
elapsed=[]
for _ in range(20):
t=time.perf_counter();cos_price(100,strikes,1,p);elapsed.append(time.perf_counter()-t)
print('1000 precios COS, N=256: mediana',np.median(elapsed),'s, mínimo',min(elapsed),'s')npm run lab and open the connection link.In one run on this machine the median was 0.00511 s for a thousand prices. This is not a latency promise: if your result exceeds 10 ms, report hardware, load, and configuration before comparing it. For an independent simulation comparison, we use full-truncation Euler for variance and one million paths. Monte Carlo deviation does not include time-step bias.
import torch
device='cuda' if torch.cuda.is_available() else 'cpu'; n=1_000_000; steps=512; dt=1/steps
v0,theta,kappa,xi,rho=p
rng=torch.Generator(device=device).manual_seed(17); x=torch.zeros(n,device=device); var=torch.full_like(x,v0)
for _ in range(steps):
z1=torch.randn(n,device=device,generator=rng)
z2=rho*z1+math.sqrt(1-rho*rho)*torch.randn(n,device=device,generator=rng)
positive=var.clamp_min(0); diffusion=torch.sqrt(positive*dt)
x+=-.5*positive*dt+diffusion*z2
var+=kappa*(theta-positive)*dt+xi*diffusion*z1
if not torch.isfinite(x).all(): raise ValueError('Trayectorias no finitas')
S=100*torch.exp(x); values=cos_price(100,K,1,p)
for strike,model in zip(K,values):
payoff=(S-strike).clamp_min(0); mean=payoff.mean().item(); se=payoff.std(unbiased=True).item()/math.sqrt(n)
print('K',strike,'COS',model,'MC',mean,'SE',se,'diferencia en SE',(mean-model)/se)
print('media S terminal',S.mean().item())npm run lab and open the connection link.On the RTX 3060 with seed 17, the five differences from COS were between −0.684 and 0.195 standard errors; the terminal mean was 99.9968. This is a finite experiment, not proof of absence of discretization bias. Repeat with more steps and seeds before interpreting the comparison as evidence of convergence.
Calibrating and investigating identification
Heston calibration seeks parameters that reproduce a set of observed IVs. Minimizing unweighted price errors often lets expensive options dominate; here we minimize IV errors. For real data, incorporate spreads and reject prices without a stable Black inverse. The next example generates 45 noise-free IVs from known parameters and searches from three initial points.
Levenberg-Marquardt works on unbounded variables. We use a smooth sigmoid transform that keeps parameters in positive intervals and ; these limits are experimental choices. The Jacobian is calculated by automatic differentiation of the COS price and converted to the IV Jacobian using the implicit function: . The code inverts Black separately and does not attempt to differentiate bisection decisions.
from scipy.optimize import least_squares
torch.set_num_threads(1)
dtype=torch.float64
lower=torch.tensor([.005,.005,.1,.05,-.98],dtype=dtype)
upper=torch.tensor([.3,.3,5.,2.,.98],dtype=dtype)
def transform(z): return lower+(upper-lower)*torch.sigmoid(z)
def inverse_transform(p):
q=(np.asarray(p)-lower.numpy())/(upper-lower).numpy()
return np.log(q/(1-q))
def torch_cf(u,T,p):
v0,theta,kappa,xi,rho=p; beta=kappa-rho*xi*1j*u
d=torch.sqrt(beta*beta+xi*xi*(u*u+1j*u)); g=(beta-d)/(beta+d); e=torch.exp(-d*T)
C=kappa*theta/xi**2*((beta-d)*T-2*torch.log((1-g*e)/(1-g)))
D=(beta-d)/xi**2*(1-e)/(1-g*e)
return torch.exp(C+D*v0)
N=256; L=3.; a=-L; b=L; u=torch.arange(N,dtype=dtype)*torch.pi/(b-a)
def chi(c,d):
return (np.exp(d)*(torch.cos(u*(d-a))+u*torch.sin(u*(d-a)))-np.exp(c)*(torch.cos(u*(c-a))+u*torch.sin(u*(c-a))))/(1+u*u)
psi=torch.empty_like(u); psi[0]=-a; psi[1:]=torch.sin(u[1:]*(0-a))/u[1:]
H=2/(b-a)*(psi-chi(a,0)); H[0]*=.5
times=np.array([.25,.5,1.,2.,3.]); grid=np.array([80.,85.,90.,95.,100.,105.,110.,115.,120.])
truth=np.array([.04,.05,1.4,.45,-.6])
target=np.array([[implied(100,strike,T,c) for strike,c in zip(grid,cos_price(100,grid,T,truth))] for T in times]).ravel()
def torch_prices(z):
p=transform(z); Kt=torch.tensor(grid,dtype=dtype)
phase=torch.exp(1j*(torch.log(100/Kt)[:,None]-a)*u[None,:])
return torch.cat([Kt*torch.real(phase@(torch_cf(u,float(T),p)*H))+100-Kt for T in times])
def prices_jac(z):
zt=torch.tensor(z,dtype=dtype,requires_grad=True)
price=torch_prices(zt).detach().numpy()
jac=torch.autograd.functional.jacobian(torch_prices,zt,vectorize=True,strategy='forward-mode').detach().numpy()
return price,jac
def invert_all(prices):
iv=[]; vegas=[]
for T in times:
for strike in grid:
sigma=implied(100,strike,T,prices[len(iv)]); iv.append(sigma)
d1=np.log(100/strike)/(sigma*np.sqrt(T))+sigma*np.sqrt(T)/2
vegas.append(100*np.exp(-d1*d1/2)/np.sqrt(2*np.pi)*np.sqrt(T))
return np.array(iv),np.array(vegas)
def residual(z):
with torch.no_grad(): price=torch_prices(torch.tensor(z,dtype=dtype)).numpy()
return invert_all(price)[0]-target
def jacobian(z):
price,jac=prices_jac(z)
return jac/invert_all(price)[1][:,None]
starts=[[.03,.04,1.,.3,-.4],[.06,.07,2.,.7,-.3],[.08,.03,.8,.35,-.8]]
for start in starts:
result=least_squares(residual,inverse_transform(start),jac=jacobian,method='lm',max_nfev=150,
xtol=1e-11,ftol=1e-11,gtol=1e-11)
recovered=transform(torch.tensor(result.x)).numpy(); singular=np.linalg.svd(jacobian(result.x),compute_uv=False)
print('inicio',start,'éxito',result.success,'parámetros',recovered,'error máximo IV',np.max(np.abs(result.fun)),
'valores singulares',singular,'evaluaciones',result.nfev)
print('singulares primer vencimiento',np.linalg.svd(jacobian(result.x)[:len(grid)],compute_uv=False))
step=1e-5; basis=np.eye(5)
fd=np.column_stack([(residual(result.x+step*basis[j])-residual(result.x-step*basis[j]))/(2*step) for j in range(5)])
print('diferencia máxima entre jacobiano automático y diferencias centradas',np.max(np.abs(jacobian(result.x)-fd)))npm run lab and open the connection link.In the noise-free run, all three initializations recovered and maximum IV error was below . Singular values of the Jacobian with respect to transformed variables were approximately 0.398, 0.178, 0.109, 0.0401, and 0.0147. Keeping only the first maturity reduced the smallest to : that selection contains a much less sensitive direction. The maximum difference between the automatic Jacobian and centered differences was on the order of in these checks.
Singular-value scale changes with units or parameterization: do not compare those values without specifying the transform. The singular vector associated with the small value identifies a combination of variables to which IVs respond less. Noise-free recovery constructed with the same pricer does not guarantee parameter identification on a noisy chain or stability over time.
Exercises
Step 1 of 4. Which derivatives with respect to x appear in the generator?
def cos_price(cf,F,K,T,N,L):
raise NotImplementedError()Ideas to remember
COS, FFT, and Monte Carlo provide checks with different errors. Noise-free synthetic recovery verifies a specific implementation, but does not establish calibration stability on real quotes.