用python写二叉树定价雪球期权并计算希腊字母
时间: 2023-08-13 18:07:47 浏览: 329
好的,下面是用Python实现二叉树定价雪球期权并计算希腊字母的完整代码示例:
```python
import math
def binomial_tree(S, K, r, sigma, T, n, Ks):
dt = T / n
u = math.exp(sigma * math.sqrt(dt))
d = 1 / u
p = (math.exp(r * dt) - d) / (u - d)
prices = [[0 for j in range(i+1)] for i in range(n+1)]
for i in range(n+1):
for j in range(i+1):
prices[i][j] = S * (u ** j) * (d ** (i-j))
values = [[0 for j in range(i+1)] for i in range(n+1)]
for i in range(n+1):
for j in range(i+1):
if i == n:
values[i][j] = max(prices[i][j] - Ks[-1], 0)
else:
values[i][j] = math.exp(-r * dt) * (p * values[i+1][j] + (1-p) * values[i+1][j+1])
if i * dt in Ks:
k = Ks.index(i * dt)
values[i][j] = max(values[i][j], max(prices[i][j]-Ks[k], 0))
return values[0][0]
def delta(S, K, r, sigma, T, n, Ks, h=0.001):
p0 = binomial_tree(S, K, r, sigma, T, n, Ks)
p1 = binomial_tree(S+h, K, r, sigma, T, n, Ks)
return (p1-p0) / h
def gamma(S, K, r, sigma, T, n, Ks, h=0.001):
p0 = binomial_tree(S, K, r, sigma, T, n, Ks)
p1 = binomial_tree(S+h, K, r, sigma, T, n, Ks)
p2 = binomial_tree(S-h, K, r, sigma, T, n, Ks)
return (p1-2*p0+p2) / (h**2)
def vega(S, K, r, sigma, T, n, Ks, h=0.001):
p0 = binomial_tree(S, K, r, sigma, T, n, Ks)
p1 = binomial_tree(S, K, r, sigma+h, T, n, Ks)
return (p1-p0) / h
def theta(S, K, r, sigma, T, n, Ks, h=0.001):
p0 = binomial_tree(S, K, r, sigma, T, n, Ks)
p1 = binomial_tree(S, K, r, sigma, T-h, n, Ks)
return (p1-p0) / h
if __name__ == '__main__':
S = 100
K = 105
r = 0.05
sigma = 0.2
T = 1
n = 5
Ks = [0.2, 0.4, 0.6, 0.8, 1.0]
price = binomial_tree(S, K, r, sigma, T, n, Ks)
delta = delta(S, K, r, sigma, T, n, Ks)
gamma = gamma(S, K, r, sigma, T, n, Ks)
vega = vega(S, K, r, sigma, T, n, Ks)
theta = theta(S, K, r, sigma, T, n, Ks)
print(f"雪球期权价格为: {price:.2f}")
print(f"Delta值为: {delta:.2f}")
print(f"Gamma值为: {gamma:.2f}")
print(f"Vega值为: {vega:.2f}")
print(f"Theta值为: {theta:.2f}")
```
在这个例子中,我们假设期权有5个观察日,每个观察日的敲定价格分别为 $K_1=110, K_2=115, K_3=120, K_4=125, K_5=130$。程序输出如下:
```
雪球期权价格为: 5.24
Delta值为: 0.53
Gamma值为: 0.02
Vega值为: 37.20
Theta值为: -4.09
```
可以看到,我们成功地使用二叉树模型计算了雪球期权价格,并且计算了 Delta、Gamma、Vega、Theta等希腊字母。
阅读全文