python使用有限差分法求解欧式期权价格,并与解析解比较
时间: 2024-05-10 07:16:27 浏览: 230
使用有限差分法求解可压缩纳维-斯托克斯方程,.zip
5星 · 资源好评率100%
欧式期权在Black-Scholes模型下的解析解为:
$$
C(S,t) = S\Phi(d_1) - Ke^{-r(T-t)}\Phi(d_2)
$$
其中,$S$是标的资产价格,$K$是行权价格,$r$是无风险利率,$T-t$是剩余期限,$\Phi$是标准正态分布的累积分布函数,$d_1$和$d_2$分别为:
$$
d_1 = \frac{ln(\frac{S}{K}) + (r + \frac{\sigma^2}{2})(T-t)}{\sigma\sqrt{T-t}}
$$
$$
d_2 = d_1 - \sigma\sqrt{T-t}
$$
在有限差分法中,我们可以使用显式、隐式或Crank-Nicolson方法来数值求解欧式期权价格。以下是一个使用显式有限差分法求解欧式期权价格的Python代码:
```python
import numpy as np
from scipy.stats import norm
def european_call(S, K, r, sigma, T, M, N):
dt = T / N
dx = sigma * np.sqrt(3 * dt)
x_left = np.log(S / K) + (r - 0.5 * sigma ** 2) * T - 3 * sigma * np.sqrt(T)
x_right = np.log(S / K) + (r - 0.5 * sigma ** 2) * T + 3 * sigma * np.sqrt(T)
x = np.linspace(x_left, x_right, M)
v = np.zeros((M, N + 1))
v[:, 0] = np.maximum(np.exp(x) - K, 0)
for j in range(N):
v[0, j + 1] = np.exp(x_left + j * dx) - K * np.exp(-r * (j + 1) * dt)
v[M - 1, j + 1] = 0
for i in range(1, M - 1):
a = 0.5 * sigma ** 2 * (x[i] - r) / dx - 0.5 * r
b = 1 / dt - sigma ** 2 * (x[i] - r) ** 2 / dx ** 2 - r
c = 0.5 * sigma ** 2 * (x[i] - r) / dx + 0.5 * r
v[i, j + 1] = a * v[i - 1, j] + b * v[i, j] + c * v[i + 1, j]
return v
def main():
S = 100
K = 100
r = 0.05
sigma = 0.2
T = 1
M = 1000
N = 1000
v = european_call(S, K, r, sigma, T, M, N)
dt = T / N
dx = sigma * np.sqrt(3 * dt)
x_left = np.log(S / K) + (r - 0.5 * sigma ** 2) * T - 3 * sigma * np.sqrt(T)
x_right = np.log(S / K) + (r - 0.5 * sigma ** 2) * T + 3 * sigma * np.sqrt(T)
x = np.linspace(x_left, x_right, M)
i = np.argmin(np.abs(x))
t = np.linspace(0, T, N + 1)
j = np.argmin(np.abs(t - 0.5))
C_fd = v[i, j]
d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * (T - 0.5)) / (sigma * np.sqrt(T - 0.5))
d2 = d1 - sigma * np.sqrt(T - 0.5)
C_analytic = S * norm.cdf(d1) - K * np.exp(-r * (T - 0.5)) * norm.cdf(d2)
print(f"Finite difference price: {C_fd:.4f}")
print(f"Analytic price: {C_analytic:.4f}")
if __name__ == "__main__":
main()
```
这个代码使用了显式有限差分法来数值求解欧式期权价格,并将结果与解析解进行了比较。我们可以调整$M$和$N$的值来控制数值解的精度。
阅读全文