Module contents
Stage 5 of 8Advanced 120 min

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

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,

 ⁣dStSt=(r−q) ⁣dt+vt ⁣dWtS, ⁣dvt=κ(θ−vt) ⁣dt+ξvt ⁣dWtv, ⁣d⟨WS,Wv⟩t=ρ ⁣dt.\begin{aligned} \frac{\dd S_t}{S_t}&=(r-q)\dd t+\sqrt{v_t}\dd W_t^S,\\ \dd v_t&=\kappa(\theta-v_t)\dd t+\xi\sqrt{v_t}\dd W_t^v,\qquad \dd\langle W^S,W^v\rangle_t=\rho\dd t. \end{aligned}

v0v_0 is initial variance, θ\theta its reversion level, κ\kappa its speed, ξ\xi the volatility of variance, and ρ∈(−1,1)\rho\in(-1,1) the correlation. With v0,θ,κ,ξ>0v_0,\theta,\kappa,\xi>0, CIR variance is nonnegative. The Feller condition 2κθ≥ξ22\kappa\theta\ge\xi^2 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.

InteractiveHeston parameters and the smile
Smile at T = 1
ATM term structure
0.040
0.040
1.50
0.30
−0.70
2κθ0.1200
ξ²0.0900
Omitted points0
Feller satisfied.
Move one of the five parameters and compare the one-year smile with the ATM term structure. Curves are calculated using COS and inverted to Black volatility with an approximate normal CDF; F = 100 and discount one. Points are omitted if inversion or the 256 versus 512 term resolution check fails. Feller describes the variance boundary, not fit quality.

Riccati and the characteristic function

Let XT=log⁡(ST/FT)X_T=\log(S_T/F_T) with FT=S0e(r−q)TF_T=S_0e^{(r-q)T}. The Heston characteristic function is ϕ(u,T)=E[eiuXT]\phi(u,T)=\E[e^{iuX_T}]. The affine structure suggests ϕ=exp⁡(C(T,u)+D(T,u)v0)\phi=\exp(C(T,u)+D(T,u)v_0). Substituting this ansatz into the Kolmogorov backward equation and grouping the constant and the coefficient of vv gives

D′=12ξ2D2+(ρξiu−κ)D−12(u2+iu),C′=κθD,C(0)=D(0)=0.D'=\tfrac12\xi^2D^2+(\rho\xi iu-\kappa)D-\tfrac12(u^2+iu), \qquad C'=\kappa\theta D,\quad C(0)=D(0)=0.

The iuiu term appears because of the log-price drift −v/2-v/2. With β=κ−ρξiu\beta=\kappa-\rho\xi iu, d=β2+ξ2(u2+iu)d=\sqrt{\beta^2+\xi^2(u^2+iu)}, choose the root with nonnegative real part and g=(β−d)/(β+d)g=(\beta-d)/(\beta+d). A stable form is

D=β−dξ21−e−dT1−ge−dT,C=κθξ2[(β−d)T−2log⁡1−ge−dT1−g].\begin{aligned} D&=\frac{\beta-d}{\xi^2}\frac{1-e^{-dT}}{1-ge^{-dT}},\\ C&=\frac{\kappa\theta}{\xi^2}\left[(\beta-d)T-2\log\frac{1-ge^{-dT}}{1-g}\right]. \end{aligned}

Direct verification gives ϕ(0,T)=1\phi(0,T)=1. Under the martingale assumptions used here, ϕ(−i,T)=1\phi(-i,T)=1 because ST/FTS_T/F_T 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.

InteractiveThe complex logarithm trap
  • Original argument
  • Stable argument
Compressed complex plane
Imaginary part of the principal logarithm
5.0
Original phase jumps on the grid2
Increase T and compare the principal phase of the original and stable arguments at frequencies from 0.05 to 40. In the plane z is radially compressed as z/(1+|z|), preserving its angle. Jumps of the original branch are counted on the grid; they are not jumps of a correctly calculated continuous characteristic function.

In the alternative formulation, the argument [1−g−1edT]/[1−g−1][1-g^{-1}e^{dT}]/[1-g^{-1}] may cross the principal logarithm’s branch cut. Its phase jumps between π\pi and −π-\pi even though the continuous logarithm needed by the Riccati solution follows another branch. In the figure’s example, two crossings appear at T=5T=5 and three at T=10T=10 on the stated grid; these are counts for that discretization. The form with e−dTe^{-dT} 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 [a,b][a,b] with cosines. For a put, it integrates the payoff on [a,0][a,0], sums cosine coefficients weighted by the characteristic function, and recovers the call by parity. Using the put limits amplification of ebe^b in right wings. The number of terms NN controls the series, but the interval must also cover the tails: increasing NN with fixed [a,b][a,b] 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 F=100F=100, discount one, and parameters (v0,θ,κ,ξ,ρ)=(0.04,0.04,1.5,0.3,−0.7)(v_0,\theta,\kappa,\xi,\rho)=(0.04,0.04,1.5,0.3,-0.7). These are synthetic parameters, not a market calibration. The fixed interval [−3,3][-3,3] refers to log⁡(ST/K)\log(S_T/K); 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.

[ ]Characteristic function, COS, and Carr-MadanLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For N=256N=256 the five strikes yield approximately 21.69949, 13.81020, 7.54027, 3.32467, and 1.12459. Comparing N=128N=128 with 256 checks the series in this case, not the tail. Change LL and NN 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 T=1T=1, F=100F=100, and discount one as in COS.

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

In the verified run, maximum COS error against QuantLib was 2.33⋅10−92.33\cdot10^{-9} 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.

[ ]Timing a thousand pricesLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Monte Carlo referenceLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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 ∣ρ∣<1|\rho|<1; 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: ∂ϑσ=(∂ϑC)/vega\partial_\vartheta\sigma=(\partial_\vartheta C)/\text{vega}. The code inverts Black separately and does not attempt to differentiate bisection decisions.

[ ]Levenberg-Marquardt with automatic JacobianLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the noise-free run, all three initializations recovered (0.04,0.05,1.4,0.45,−0.6)(0.04,0.05,1.4,0.45,-0.6) and maximum IV error was below 3⋅10−133\cdot10^{-13}. 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 2.56⋅10−52.56\cdot10^{-5}: that selection contains a much less sensitive direction. The maximum difference between the automatic Jacobian and centered differences was on the order of 10−910^{-9} 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

ProofThe affine ansatz
Prove: Obtain the Riccati equations for the characteristic function of Heston's normalized log-price.
0
Use f(τ,x,v) = exp(iux + C(τ,u) + D(τ,u)v), with τ = 0 as the terminal condition.

Step 1 of 4. Which derivatives with respect to x appear in the generator?

NumericThe variance boundary
With κ = 1.5, θ = 0.04 and ξ = 0.3, calculate the margin 2κθ − ξ². Is it positive? Enter the margin.
QuizSkew and curvature
Which pair usually controls smile skew and curvature most directly, respectively?
CodePricing with COS
Implement cos_price(cf,F,K,T,N,L), for forward F and discount one. cf(u,T) is the characteristic function of log(S_T/F). Use a put on [−L,0] and parity for the call; accept an array K and assign half weight to the zero term.
def cos_price(cf,F,K,T,N,L):
  raise NotImplementedError()
Shift+Enter to run

Ideas to remember

Key idea
The characteristic function turns Heston’s affine dynamics into a Fourier problem; choosing branches, controlling truncation, and inspecting identification are as necessary as obtaining a price.

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.