这是我所有的代码:
def zeros(n, m = 0):
if m == 0:
m = n
"""creates matrix[n][m] of zeros """
mat = [[0 for col in range(m)] for row in range (n)];
return mat
def get_binomial_factors(sigma, rf, div, h):
'''binomial factors given sigma, rf, div, h'''
u = math.exp((rf-div)*h+sigma*math.sqrt(h))
d = math.exp((rf-div)*h-sigma*math.sqrt(h))
ans = (u, d)
return ans
def get_risk_neutral_probability(sigma, rf, div, h):
'''risk neutral probability given sigma, rf, div, h'''
tuple = get_binomial_factors(sigma, rf, div, h)
u = tuple[0]
d = tuple[1]
p = (math.exp((rf - div)*h)-d)/(u-d)
return p
def build_euro_call_value_tree(s, x, sigma, rf, div, T, n):
'''Builds a binomial call option pricing tree using the underlying stock tree'''
h = T/n
tuple = get_binomial_factors(sigma, rf, div, h)
p = get_risk_neutral_probability(sigma, rf, div, h)
u = tuple[0]
d = tuple[1]
stock_tree = build_binomial_stock_price_tree(s, sigma, rf, div, T, n)
option_tree = zeros(n+1)
for i in range(n, -1, -1):
for j in range(i + 1):
if i == n:
option_tree[j][i] = max(0, stock_tree[j][i] - x)
else:
option_tree[j][i] = (1 / (1 + rf*h)) * (p * option_tree[j][i+1] + (1 - p) * option_tree[j+1][i+1])
return option_tree
我尝试包括 Decimal 并在那里做一些事情,但它并没有真正解决它