Module contents
Lesson 14 of 30Advanced 115 min

PDE pricing and American options

Price European and American options with finite-difference PDEs, projected SOR and independently evaluated Longstaff-Schwartz policies.

After this lesson you can

  • Transform the Black-Scholes PDE to log-price and time to maturity with appropriate domain and boundaries.
  • Implement Crank-Nicolson with the Thomas algorithm and diagnose oscillations for discontinuous payoffs.
  • Apply Rannacher smoothing and measure empirical convergence of price and Greeks.
  • Formulate an American put as a linear complementarity problem and solve it with projected SOR.
  • Implement Longstaff-Schwartz, understand its bias and compare it with PDE and tree methods.

Before you start

Solving prices on a grid

A PDE produces values for many initial prices at once. It also permits an exercise obstacle, but requires a finite domain and checks that its boundaries do not contaminate the region of interest. For x=log⁡Sx=\log S, τ=T−t\tau=T-t and u(τ,x)=V(T−τ,ex)u(\tau,x)=V(T-\tau,e^x), the pricing PDE with continuous dividend qq is

uτ=12σ2uxx+(r−q−12σ2)ux−ru=Lu,u(0,x)=g(ex).u_\tau=\tfrac12\sigma^2u_{xx}+(r-q-\tfrac12\sigma^2)u_x-r u=Lu,\qquad u(0,x)=g(e^x).

The chain rule gives SVS=uxSV_S=u_x and S2VSS=uxx−uxS^2V_{SS}=u_{xx}-u_x. Diffusion therefore has constant coefficients in xx. For a European put without dividends, as SS approaches zero value approaches Ke−rτ−SKe^{-r\tau}-S; for an American put immediate exercise suggests K−SK-S at the lower edge. At the upper edge both values tend to zero. These are limits, so imposing them at finite Smin⁡S_{\min} and Smax⁡S_{\max} introduces truncation error: move boundaries and repeat valuation.

With step Δx\Delta x, centered differences approximate uxu_x and uxxu_{xx} and yield a tridiagonal operator LhL_h. The explicit scheme applies I+ΔτLhI+\Delta\tau L_h and may require a step restriction for stability and positivity. The implicit scheme solves (I−ΔτLh)un+1=un(I-\Delta\tau L_h)u^{n+1}=u^n; it damps fast modes but is first-order in time. Crank-Nicolson averages both:

(I−12ΔτLh)un+1=(I+12ΔτLh)un.\left(I-\tfrac12\Delta\tau L_h\right)u^{n+1} =\left(I+\tfrac12\Delta\tau L_h\right)u^n.

Each side incorporates boundary conditions at the corresponding time. Thomas solves the tridiagonal system in O(n)O(n) operations and linear memory, provided pivots are valid. CN is second-order in time for sufficiently smooth solutions and stable in the usual linear sense; stability does not guarantee monotonicity or absence of oscillations with discontinuous data.

Nonsmooth payoffs and Rannacher smoothing

A digital jumps at the strike and a call has a kink. In CN high-frequency spatial modes can persist and appear as spikes in values or Greeks even if the scheme is stable. Rannacher smoothing replaces initial CN steps with implicit half-steps to damp those modes before continuing with CN. Two half-steps cover the first time interval; four cover two. The plot calculates gamma of a digital on one particular grid: it does not establish a general bound for every scheme.

InteractiveCrank-Nicolson oscillations
  • Plain CN
  • CN with selected start
2
Implicit half steps
Δt / Δx²161.95
Hypothetical digital call with K = 100, r = 5%, σ = 20%, time remaining 0.05 years and 200 log-S intervals between 25 and 300. Compare pure CN with 0, 2 or 4 initial implicit half-steps; gamma uses differences on the price grid. The ratio Δt/Δx² applies to this grid.

To measure convergence, compare with an analytical solution or finer grid while controlling domain, interpolation and time. With errors eh≈Chpe_h\approx Ch^p, the ratio eh/eh/2e_h/e_{h/2} approximates 2p2^p; Richardson combines grids only if the error expansion and asymptotic regime apply. Gamma near a discontinuity may converge more slowly than price; showing price alone does not validate Greeks.

An American option is an obstacle

The American put allows immediate exercise g(S)=(K−S)+g(S)=(K-S)^+. In time remaining, the solution satisfies the complementarity problem

u−g≥0,uτ−Lu≥0,(u−g)(uτ−Lu)=0.u-g\ge0,\qquad u_\tau-Lu\ge0,\qquad (u-g)(u_\tau-Lu)=0.

In continuation u>gu>g and the PDE holds with equality. In exercise u=gu=g and the other expression is nonnegative. Equality can also hold at the boundary: strict inequality is not required throughout the exercise region. The free boundary separates decisions and is part of the solution.

Discretizing each step gives Av≥bAv\ge b, v≥gv\ge g and (v−g)⊤(Av−b)=0(v-g)^\top(Av-b)=0. Projected SOR updates each component with relaxed Gauss-Seidel and projects it onto gg. Check convergence and complementarity residual, not merely stop after a fixed iteration count. Another family replaces the obstacle with a penalty: accuracy then also depends on its parameter.

InteractiveThe American put free boundary
  • PDE American put
  • Immediate exercise
  • PDE boundary
  • Tree boundary
Time remaining τ = 1.00
Time remaining τ1.000
Grid boundary80.38
Maximum PSOR residual9.94e-9
Put with S₀ = K = 100, r = 5%, σ = 20% and T = 1. The PDE uses 100 log-price intervals and 40 PSOR steps; the CRR tree uses 40 steps. The PDE boundary is the largest in-the-money node touching the obstacle; the tree uses exercise strictly greater than continuation. Replay evolution from maturity.

A grid boundary is discrete and depends on tolerance, domain and resolution. A tree curve can be jagged because its nodes change with date. At the same step count, different methods do not cost the same; compare error and runtime, not just nominal parameters.

Longstaff-Schwartz: learning when to stop

The Longstaff-Schwartz algorithm simulates paths under QQ and works backward from maturity. At each date, for in-the-money paths, it regresses discounted future cash flow on state functions. Regression approximates continuation; exercise occurs if immediate payoff exceeds that estimate. The decision policy is then saved, not only the average training cash flows.

InteractiveLongstaff-Schwartz regression at one date
  • Realized continuation value
  • Regression
  • Exercise
Basis
Basis functions
In-sample value6.126
Out-of-sample policy value ± SE6.093 ± 0.113
Put with S₀ = K = 100, r = 5%, σ = 20%, 24 dates, 6000 training paths and 4000 new evaluation paths; seeds 281401 and 281402. Points show a subsample of realized continuations at the middle date. Powers and Laguerre polynomials of equal degree span the same space; the basis may affect numerical conditioning.

A fixed policy evaluated on independent paths is feasible: its expectation cannot exceed optimal exercise value at the allowed dates. Its finite Monte Carlo mean can exceed it by chance. Reusing paths to fit and evaluate introduces selection or look-ahead bias in sample; it does not mean each individual run exceeds exact value. Too few basis functions may underfit; too many may overfit or destabilize regression. A dual upper bound requires an additional martingale construction; it does not follow automatically from the same regression. The original formulation is in Longstaff and Schwartz (2001).

Lab: CN and PSOR

The solver below works in log-price, solves CN with Thomas and allows two initial implicit half-steps. For American options it uses PSOR with a complementarity criterion and iteration limit; projecting the CN scheme does not automatically make it monotone. The example requires r≥0r\ge0, positive volatility and a domain containing S0S_0 and KK, and checks spatial coefficients; the lower-edge exercise condition remains a finite-domain approximation.

[ ]Finite differences and complementarityBrowser
import numpy as np
from scipy.special import ndtr
def bs_put(S,K,r,sigma,T):
    a=sigma*np.sqrt(T); d1=(np.log(S/K)+(r+.5*sigma*sigma)*T)/a; d2=d1-a
    return K*np.exp(-r*T)*ndtr(-d2)-S*ndtr(-d1)
def thomas(a,b,c,d):
    b=b.copy(); d=d.copy(); n=len(b)
    for i in range(1,n):
        if abs(b[i-1])<1e-14: raise ValueError('Pivote nulo')
        w=a[i-1]/b[i-1]; b[i]-=w*c[i-1]; d[i]-=w*d[i-1]
    if abs(b[-1])<1e-14: raise ValueError('Pivote nulo')
    x=np.empty(n); x[-1]=d[-1]/b[-1]
    for i in range(n-2,-1,-1): x[i]=(d[i]-c[i]*x[i+1])/b[i]
    return x
def psor_tri(a,b,c,rhs,g,initial,omega=1.4,tol=1e-8,maxiter=20000):
    v=np.maximum(initial,g).copy(); n=len(v)
    for it in range(maxiter):
        for i in range(n):
            rest=(a[i-1]*v[i-1] if i else 0)+(c[i]*v[i+1] if i<n-1 else 0)
            v[i]=max(g[i],v[i]+omega*((rhs[i]-rest)/b[i]-v[i]))
        residual=b*v-rhs; residual[1:]+=a*v[:-1]; residual[:-1]+=c*v[1:]
        violation=max(float(np.max(np.maximum(-residual,0))),float(np.max(np.maximum(g-v,0))),float(np.max(np.abs((v-g)*residual))))
        if violation<tol: return v,it+1,violation
    raise RuntimeError('PSOR no converge')
def fd_put(S0=100.,K=100.,r=.05,sigma=.2,T=1.,n=160,m=100,american=False,rannacher=True,low=20.,high=400.):
    if not (0<low<min(S0,K) and high>max(S0,K) and r>=0 and sigma>0 and T>0 and isinstance(n,int) and n>=3 and isinstance(m,int) and m>=1): raise ValueError('Parámetros o dominio inválidos')
    x=np.linspace(np.log(low),np.log(high),n+1); S=np.exp(x); dx=x[1]-x[0]; dt=T/m
    l=.5*sigma**2/dx**2-(r-.5*sigma**2)/(2*dx); d=-sigma**2/dx**2-r; u=.5*sigma**2/dx**2+(r-.5*sigma**2)/(2*dx)
    if l<0 or u<0: raise ValueError('Malla no monótona para este operador')
    payoff=np.maximum(K-S,0); v=payoff.copy(); tau=0.; max_residual=0.
    def advance(v,tau,h,theta):
        left=K-S[0] if american else max(K*np.exp(-r*(tau+h))-S[0],0); right=0.
        A=-theta*h*l; B=1-theta*h*d; C=-theta*h*u
        rhs=v[1:-1]+(1-theta)*h*(l*v[:-2]+d*v[1:-1]+u*v[2:]); rhs=rhs.copy(); rhs[0]-=A*left; rhs[-1]-=C*right
        aa=np.full(n-2,A); bb=np.full(n-1,B); cc=np.full(n-2,C)
        if american: inner,_,res=psor_tri(aa,bb,cc,rhs,payoff[1:-1],v[1:-1]);
        else: inner=thomas(aa,bb,cc,rhs); res=0.
        return np.r_[left,inner,right],res
    if rannacher:
        for _ in range(2): v,res=advance(v,tau,dt/2,1.); tau+=dt/2; max_residual=max(max_residual,res)
    for _ in range(m-int(rannacher)):
        v,res=advance(v,tau,dt,.5); tau+=dt; max_residual=max(max_residual,res)
    slopes=np.diff(v)/np.diff(S); gamma=2*np.diff(slopes)/(S[2:]-S[:-2]); delta=(v[2:]-v[:-2])/(S[2:]-S[:-2])
    return {'precio':float(np.interp(S0,S,v)),'delta':float(np.interp(S0,S[1:-1],delta)), 'gamma':float(np.interp(S0,S[1:-1],gamma)), 'residuo':max_residual}
[ ]Grid and tree comparisonBrowser
def tree_put(n,american):
    S=100.; K=100.; r=.05; sigma=.2; dt=1/n; u=np.exp(sigma*np.sqrt(dt)); d=1/u; p=(np.exp(r*dt)-d)/(u-d)
    j=np.arange(n+1); v=np.maximum(K-S*u**(2*j-n),0)
    for i in range(n-1,-1,-1):
        j=np.arange(i+1); cont=np.exp(-r*dt)*((1-p)*v[:-1]+p*v[1:]); v=np.maximum(cont,np.maximum(K-S*u**(2*j-i),0)) if american else cont
    return v[0]
reference=bs_put(100,100,.05,.2,1); d1=(.05+.5*.2**2)/.2
exact_delta=ndtr(d1)-1; exact_gamma=np.exp(-.5*d1*d1)/np.sqrt(2*np.pi)/(100*.2)
print('put europea exacta',round(reference,8),'delta',round(exact_delta,8),'gamma',round(exact_gamma,8),'árbol americana 1000',round(tree_put(1000,True),8)); values=[]
for n,m in ((80,50),(160,100),(320,200)):
    eu=fd_put(n=n,m=m); am=fd_put(n=n,m=m,american=True)
    values.append(eu['precio']); print('n,m',n,m,'europea',eu,'error',round(eu['precio']-reference,7),'americana',am)
order=np.log2(abs((values[0]-values[1])/(values[1]-values[2]))); richardson=values[2]+(values[2]-values[1])/(2**order-1)
print('orden empírico y extrapolación',round(order,5),round(richardson,8))
for low,high in ((10.,600.),(20.,400.),(40.,200.)):
    print('dominio',low,high,'europea',fd_put(n=160,m=100,low=low,high=high)['precio'])
print('malla de figura americana',fd_put(n=100,m=40,american=True,rannacher=False,low=25.,high=300.)['precio'])

In this run, European errors were −0.0275402, −0.0055799 and −0.0008012 on refinement; the three differences gave empirical order 2.2002 and extrapolation 5.57405393 versus exact value 5.57352602. On the finest grid, delta and gamma were −0.3631855 and 0.0187647 versus analytical −0.3631694 and 0.0187620. Interpolation at S0S_0 and finite boundaries contribute to error; one sequence does not prove a universal order.

Changing domain with 160 intervals gave European values 5.56054 for [10,600], 5.56795 for [20,400] and 5.57274 for [40,200]. Changing endpoints while keeping nn fixed also changes Δx\Delta x and strike alignment, so this comparison alone does not isolate boundary error. To diagnose it, keep spatial step approximately fixed while moving boundaries, then refine.

Lab: out-of-sample exercise policy

We train regressions on GBM paths independent of evaluation paths. The put is one-dimensional; the call on the maximum of two assets uses a multivariate basis and continuous dividend so early exercise can make sense. Both are Bermudan on simulated dates: an American option permits more exercise dates.

[ ]LSM with an independent policyBrowser
import numpy as np
def simulate(seed,N,n,S0,sigma,r,q,rho=0.):
    g=np.random.default_rng(seed); dim=len(S0); dt=1/n; z=g.standard_normal((N,n,dim))
    if dim==2: z[:,:,1]=rho*z[:,:,0]+np.sqrt(1-rho*rho)*z[:,:,1]
    increments=(r-np.asarray(q)-.5*np.asarray(sigma)**2)*dt+np.asarray(sigma)*np.sqrt(dt)*z
    return np.concatenate((np.broadcast_to(S0,(N,1,dim)),np.asarray(S0)*np.exp(np.cumsum(increments,axis=1))),axis=1)
def payoff(s,kind): return np.maximum(100-s[:,0],0) if kind=='put' else np.maximum(s.max(axis=1)-100,0)
def basis(s,kind,k=3):
    x=s[:,0]/100
    if kind=='put': return np.column_stack((np.ones(len(s)),1-x,1-2*x+x*x/2,1-3*x+1.5*x*x-x*x*x/6))[:,:k]
    y=s[:,1]/100; return np.column_stack((np.ones(len(s)),x,y,x*x,x*y,y*y,np.maximum(np.maximum(x,y)-1,0)))
def train_policy(paths,kind,r=.05,k=3):
    N,n1,_=paths.shape; n=n1-1; disc=np.exp(-r/n); cash=payoff(paths[:,-1],kind); coeff=[None]*n
    for i in range(n-1,0,-1):
        cash*=disc; exercise=payoff(paths[:,i],kind); active=exercise>0
        if active.sum()<basis(paths[:1,i],kind,k).shape[1]: continue
        X=basis(paths[active,i],kind,k); coef=np.linalg.lstsq(X,cash[active],rcond=None)[0]; coeff[i]=coef
        take=active.copy(); take[active]=exercise[active]>X@coef; cash[take]=exercise[take]
    return coeff,float(cash.mean()*disc)
def evaluate(paths,kind,coeff,r=.05):
    N,n1,_=paths.shape; n=n1-1; alive=np.ones(N,bool); discounted=np.zeros(N)
    for i in range(1,n):
        if coeff[i] is None: continue
        exercise=payoff(paths[:,i],kind); take=alive&(exercise>0)&(exercise>basis(paths[:,i],kind,len(coeff[i]))@coeff[i])
        discounted[take]=np.exp(-r*i/n)*exercise[take]; alive[take]=False
    discounted[alive]=np.exp(-r)*payoff(paths[alive,-1],kind)
    return discounted.mean(),discounted.std(ddof=1)/np.sqrt(N)
n=30
for kind,S0,sigma,q,rho in [('put',[100.],[.2],[0.],0.),('máximo',[100.,100.],[.2,.2],[.1,.1],.3)]:
    train=simulate(281410,8000,n,S0,sigma,.05,q,rho); test=simulate(281411,12000,n,S0,sigma,.05,q,rho)
    policy,inside=train_policy(train,kind); value,se=evaluate(test,kind,policy)
    print(kind,'entrenamiento',round(inside,5),'evaluación',round(value,5),'EE',round(se,5))
print('referencia put PSOR',fd_put(n=160,m=100,american=True)['precio'])
test_put=simulate(281412,12000,n,[100.],[.2],.05,[0.])
for count in (2500,8000):
    train=simulate(281413,count,n,[100.],[.2],.05,[0.])
    for k in (2,4):
        policy,inside=train_policy(train,'put',k=k); value,se=evaluate(test_put,'put',policy)
        print('put N y base',count,k,'entrenamiento',round(inside,5),'evaluación',round(value,5),'EE',round(se,5))

The evaluation’s statistical interval excludes policy bias and date discretization. The maximum-basket result is not compared with the one-dimensional solver, which does not represent two factors. A new basis must be evaluated on new paths; selecting the best on the same evaluation set would reintroduce selection.

With this run’s seeds, the put gave 5.99645 in training and 6.08332 in evaluation, with SE 0.06617; PSOR on the 160-interval grid gave 6.08291 and the 1000-step tree 6.08960. The call on the maximum gave 9.65422 in training and 9.50235 in evaluation, with SE 0.09496. These are results for the specified options, dates and samples; an independent value from one sample can exceed training without contradicting the expectation bound.

In the basis test, evaluations with 2500 training paths were 6.08799 and 6.13069 for two and four functions; with 8000 they were 6.06889 and 6.12469. They share the same evaluation set and their differences are correlated. One seed does not measure mean bias or establish that one basis dominates; repeat training and evaluate separately without choosing the winner on the test sample.

Exercises

ProofFrom Black-Scholes to convection-diffusion
Prove: Transform the Black-Scholes PDE with x=log⁡Sx=\log S and τ=T−t\tau=T-t.
0
Let u(τ,x)=V(T−τ,ex)u(\tau,x)=V(T-\tau,e^x).

Step 1 of 3. What is S V_S?

ProofContinuation and exercise
Prove: Explain the complementarity conditions for an American put in time remaining.
0
u≥gu\ge g and LL is the pricing operator.

Step 1 of 3. If u > g, what does the solution satisfy?

NumericOperation scaling
With 200 unknowns and 100 steps, estimate n·m, the linear operation scale of Thomas, ignoring constants.
NumericDense comparison
With the same data, estimate m·n³, the scale of dense elimination at each step, ignoring constants and factorization reuse.
QuizEvaluate a policy
What does evaluating a fixed stopping policy on independent paths guarantee?
CodeProjected SOR
Implement psor(A,b,g,omega,tol) for a small dense-matrix complementarity problem. Return v ≥ g with Av − b ≥ 0 and complementary product near zero; limit iterations and raise RuntimeError if it does not converge.
def psor(A,b,g,omega,tol):
  raise NotImplementedError()
Shift+Enter to run

Ideas to remember

The grid transforms the PDE into banded systems; boundaries and payoff smoothness matter for prices and Greeks. PSOR solves a discrete obstacle if it converges. LSM approximates a stopping policy and needs independent evaluation, with Monte Carlo error and discretization bias stated.