我正在努力 在 Python 中实现三叉树。我为二叉树找到了非常好的解决方案 (和矢量化版本),我正在尝试将其更改为三项式情况。
这是我所拥有的:
def Trinomial(type, S0, K, r, sigma, T, N=2000):
import numpy as np
t = float(T) / N
#fixed lambda
lam = np.sqrt(5)
# up and down factor will be constant for the tree so we calculate outside the loop
u = np.exp(lam * sigma * np.sqrt(t))
d = 1.0 / u
#to work with vector we need to init the arrays using numpy
fs = np.asarray([0.0 for i in xrange(2*N + 1)])
#we need the stock tree for calculations of expiration values
fs2 = np.asarray([(S0 * u**j) for j in xrange(-N, N+1)])
#we vectorize the strikes as well so the expiration check will be faster
fs3 =np.asarray( [float(K) for i in xrange(2*N + 1)])
#formulas, that can be found in the pdf document
a = np.exp(r*t/2.0)
b = np.exp(-sigma * np.sqrt(t/2.0))
c = np.exp(sigma * np.sqrt(t/2.0))
p_u = ( ( a - b ) / ( c - d ) )**2
p_d = ( ( c - a ) / ( c - b ) )**2
p_m = 1 - p_u - p_d
# Compute the leaves, f_{N, j}
if type =="C":
fs[:] = np.maximum(fs2-fs3, 0.0)
else:
fs[:] = np.maximum(-fs2+fs3, 0.0)
#calculate backward the option prices
for i in xrange(N-1, -1, -1):
fs[:-1] = np.exp(-r * t) * (p_u * fs[1:] + p_d * fs[:-1] + p_m*fs[-1])
return fs[0]
当然,它不会按预期工作,例如调用
print Trinomial("C",100, 100, 0.1, 0.1, 5, 3)
应该输出 39 到 40 之间的东西。
我最关心的行是:
fs2 = np.asarray([(S0 * u**j) for j in xrange(-N, N+1)])
和
fs[:-1] = np.exp(-r * t) * (p_u * fs[1:] + p_d * fs[:-1] + p_m*fs[-1])
我不确定我是否正确填充了初始树,并且我 100% 确定,反向计算期权价格不起作用。我不知道如何从我一开始链接的pdf中实现公式[10]。
也许它不能在矢量化版本上完成,但我尝试了简单的树并且也失败了。
在这种情况下,我没有使用二项式或 BS 价格,因为我的任务是使用三项式树来完成。