# 量化分析师的Python日记【Q Quant兵器谱之偏微分方程3的具体金融学运用】

import numpy as np
import math
import seaborn as sns
from matplotlib import pylab
from CAL.PyCAL import *
font.set_size(15)

## 1. 问题的提出

BSM模型可以设置为如下的偏微分方差初值问题：

{C(S,t)t+rSC(S,t)S+12σ2S22C(S,t)S2rC(S,t)=0,0tT\[5pt]C(S,T)=max(SK,0)

C(x,τ)τ\[5pt]C(x,0)\[5pt]C(xmax,τ)\[5pt]C(xmin,τ)=(r12σ2)C(x,τ)x+12σ22C(x,τ)x2rC(x,τ)=0,0τT=max(exK,0),=exmaxKeτ,=0

## 2. 算法

\begin{align}&\frac{C_{j,k+1} - C_{j,k}}{\Delta \tau} = (r - \frac{1}{2}\sigma^2)\frac{C_{j+1,k+1} - C_{j-1,k+1}}{2\Delta x} + \frac{1}{2}\sigma^2 \frac{C_{j+1,k+1} - 2C_{j,k+1} + C_{j-1,k+1}}{\Delta x^2} - rC_{j,k+1}, \\\[5pt]\Rightarrow& \quad C_{j,k+1} - C_{j,k} - (r - \frac{1}{2}\sigma^2)\frac{\Delta \tau}{2\Delta x}(C_{j+1,k+1} - C_{j-1,k+1}) - \frac{1}{2}\sigma^2 \frac{\Delta \tau}{\Delta x^2}(C_{j+1,k+1} - 2C_{j,k+1} + C_{j-1,k+1}) + r\Delta \tau C_{j,k+1} = 0, \\\[5pt]\Rightarrow& \quad - (\frac{1}{2}(r - \frac{1}{2}\sigma^2)\frac{\Delta \tau}{\Delta x} + \frac{1}{2}\sigma^2\frac{\Delta \tau}{\Delta x^2})C_{j+1,k+1} + (1 + \sigma^2\frac{\Delta \tau}{\Delta x^2} + r\Delta \tau)C_{j,k+1} - (\frac{1}{2}\sigma^2\frac{\Delta \tau}{\Delta x^2} - \frac{1}{2}(r - \frac{1}{2}\sigma^2 )\frac{\Delta \tau}{\Delta x})C_{j-1,k+1} = C_{j,k}, \\\[5pt]\Rightarrow& \quad l_j C_{j-1,k+1} + c_j C_{j,k+1} + u_j C_{j+1,k+1} = C_{j,k}\end{align}

\begin{align*}C_{0,k} = C(x_{min},\tau), \\\[5pt]C_{N,k} = C(x_{max},\tau)

\end{align*}

## 3.实现

import scipy as sp
from scipy.linalg import solve_banded 

class BSMModel:

def __init__(self, s0, r, sigma):
self.s0 = s0
self.x0 = math.log(s0)
self.r = r
self.sigma = sigma

def log_expectation(self, T):
return self.x0 + (self.r - 0.5 * self.sigma * self.sigma) * T

def expectation(self, T):
return math.exp(self.log_expectation(T))

def x_max(self, T):
return self.log_expectation(T) + 4.0 * self.sigma * math.sqrt(T)

def x_min(self, T):
return self.log_expectation(T) - 4.0 * self.sigma * math.sqrt(T)

class CallOption:

def __init__(self, strike):
self.k = strike

def ic(self, spot):
return max(spot - self.k, 0.0)

def bcl(self, spot, tau, model):
return 0.0

def bcr(self, spot, tau, model):
return spot - math.exp(-model.r*tau) * self.k

class BSMScheme:
2
def __init__(self, model, payoff, T, M, N):
3
self.model = model
4
self.T = T
5
self.M = M
6
self.N = N
7
self.dt = self.T / self.M
8
self.payoff = payoff
9
self.x_min = model.x_min(self.T)
10
self.x_max = model.x_max(self.T)
11
self.dx = (self.x_max - self.x_min) / self.N
12
self.C = np.zeros((self.N+1, self.M+1)) # 全部网格
13
self.xArray = np.linspace(self.x_min, self.x_max, self.N+1)
14
self.C[:,0] = map(self.payoff.ic, np.exp(self.xArray))
15

16
sigma_square = self.model.sigma*self.model.sigma
17
r = self.model.r
18

19
self.l_j = -(0.5*sigma_square*self.dt/self.dx/self.dx - 0.5 * (r - 0.5 * sigma_square)*self.dt/self.dx)
20
self.c_j = 1.0 + sigma_square*self.dt/self.dx/self.dx + r*self.dt
21
self.u_j = -(0.5*sigma_square*self.dt/self.dx/self.dx + 0.5 * (r - 0.5 * sigma_square)*self.dt/self.dx)
22

23
def roll_back(self):
24

25
for k in range(0, self.M):
26
udiag = np.ones(self.N-1) * self.u_j
27
ldiag =  np.ones(self.N-1) * self.l_j
28
cdiag =  np.ones(self.N-1) * self.c_j
29

30
mat = np.zeros((3,self.N-1))
31
mat[0,:] = udiag
32
mat[1,:] = cdiag
33
mat[2,:] = ldiag
34
rhs = np.copy(self.C[1:self.N,k])
35

36
# 应用左端边值条件
37
v1 = self.payoff.bcl(math.exp(self.x_min), (k+1)*self.dt, self.model)
38
rhs[0] -= self.l_j * v1
39

40
# 应用右端边值条件
41
v2 = self.payoff.bcr(math.exp(self.x_max), (k+1)*self.dt, self.model)
42
rhs[-1] -= self.u_j * v2
43

44
x = solve_banded((1,1), mat, rhs)
45
self.C[1:self.N, k+1] = x
46
self.C[0][k+1] = v1
47
self.C[self.N][k+1] = v2
48

49
def mesh_grids(self):
50
tArray = np.linspace(0, self.T, self.M+1)
51
tGrids, xGrids = np.meshgrid(tArray, self.xArray)
52
return tGrids, xGrids

model = BSMModel(100.0, 0.05, 0.2)
payoff = CallOption(105.0)
scheme = BSMScheme(model, payoff, 5.0, 100, 300)
scheme.roll_back()
from matplotlib import pylab
pylab.figure(figsize=(12,8))
pylab.plot(np.exp(scheme.xArray)[50:170], scheme.C[50:170,-1])
pylab.xlabel('$S$')
pylab.ylabel('$C$')

## 4. 收敛性测试

analyticPrice = BSMPrice(1, 105., 100., 0.05, 0.0, 0.2, 5.)
analyticPrice

xSteps = range(50,300,10)
finiteResult = []
for xStep in xSteps:
model = BSMModel(100.0, 0.05, 0.2)
payoff = CallOption(105.0)
scheme = BSMScheme(model, payoff, 5.0, 3000, xStep)
scheme.roll_back()

interp = CubicNaturalSpline(np.exp(scheme.xArray), scheme.C[:,-1])
price = interp(100.0)
finiteResult.append(price)

anyRes = [analyticPrice['price'][1]] * len(xSteps)

pylab.figure(figsize = (16,8))
pylab.plot(xSteps, finiteResult, '-.', marker = 'o', markersize = 10)
pylab.plot(xSteps, anyRes, '--')
pylab.legend([u'隐式差分格式', u'解析解（欧式）'], prop = font)
pylab.xlabel(u'价格方向网格步数', fontproperties = font)
pylab.title(u'Black - Scholes - Merton 有限差分法', fontproperties = font, fontsize = 20)

• 本文已收录于以下专栏：

举报原因： 您举报文章：量化分析师的Python日记【Q Quant兵器谱之偏微分方程3的具体金融学运用】 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)