用Python模拟Black Scholes期权定价模型

理论模型

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Black-Scholes Put Option Price Simulation
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# 参数
S0 = 40
mu = 0.05
sigma = 0.25
K = 40
T = 1
r = 0.05 # 此处采用风险中性假设,即无风险利率 r = mu

N = 252 * 10 # 一年交易日
dt = T / N

# 时间轴
t = np.linspace(0, T, N)

# 模拟股价路径
np.random.seed(99) # 随机数种子使结果可复现
Z = np.random.normal(0, 1, N)

S = np.zeros(N)
S[0] = S0

for i in range(1, N):
S[i] = S[i-1] * np.exp((mu - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * Z[i])

# Black-Scholes 看跌期权
def put_option_price(S, K, T, t, r, sigma):
tau = T - t
tau = np.maximum(tau, 1e-8) # 防止除零

d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * tau) / (sigma * np.sqrt(tau))
d2 = d1 - sigma * np.sqrt(tau)

P = K * np.exp(-r * tau) * norm.cdf(-d2) - S * norm.cdf(-d1)
return P

# 计算期权路径
P = put_option_price(S, K, T, t, r, sigma)

# 绘图
fig, ax1 = plt.subplots(figsize=(10,6))

ax1.plot(t, S, color='blue', linewidth=2, label='Stock Price')
ax1.set_xlabel('Time')
ax1.set_ylabel('Stock Price S', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')

ax2 = ax1.twinx()
ax2.plot(t, P, color='red', linestyle='--', linewidth=2,
label='Put Option Price')
ax2.set_ylabel('Put Option Price P', color='red')
ax2.tick_params(axis='y', labelcolor='red')

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')

plt.title('GBM Stock Price and Black-Scholes Put Option Price')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

运行结果

上述代码的运行结果如下图所示:

1