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
- 28Black-Scholes PDEAmerican early exerciseMonte Carlo option pricingOption GreeksCox-Ross-Rubinstein binomial tree
- 29Finite difference stencils for PDEsCrank-Nicolson schemeVon Neumann stability analysis
- 09Banded and tridiagonal solversStationary iterative methods
- 11Basis function expansionLinear regression model and least-squares fitting
- 26Feynman-Kac formula
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 , and , the pricing PDE with continuous dividend is
The chain rule gives and . Diffusion therefore has constant coefficients in . For a European put without dividends, as approaches zero value approaches ; for an American put immediate exercise suggests at the lower edge. At the upper edge both values tend to zero. These are limits, so imposing them at finite and introduces truncation error: move boundaries and repeat valuation.
With step , centered differences approximate and and yield a tridiagonal operator . The explicit scheme applies and may require a step restriction for stability and positivity. The implicit scheme solves ; it damps fast modes but is first-order in time. Crank-Nicolson averages both:
Each side incorporates boundary conditions at the corresponding time. Thomas solves the tridiagonal system in 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.
To measure convergence, compare with an analytical solution or finer grid while controlling domain, interpolation and time. With errors , the ratio approximates ; 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 . In time remaining, the solution satisfies the complementarity problem
In continuation and the PDE holds with equality. In exercise 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 , and . Projected SOR updates each component with relaxed Gauss-Seidel and projects it onto . 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.
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 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.
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 , positive volatility and a domain containing and , and checks spatial coefficients; the lower-edge exercise condition remains a finite-domain approximation.
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}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 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 fixed also changes 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.
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
Step 1 of 3. What is S V_S?
Step 1 of 3. If u > g, what does the solution satisfy?
def psor(A,b,g,omega,tol):
raise NotImplementedError()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.