I am note sure if you can omit that loop in an efficient way, but when we do not use np.delete()
but just use the indices to shrink payoff
in every iteration I already got a big speed increase on my machine:
# ...
arr = np.full(N+1, d/u)
arr[0] = S*np.power(u, N)
arr[1:] = arr[0] * np.cumprod(arr[1:])
def get_payoff(s, k):
return np.maximum((s - k), 0)
payoff = get_payoff(arr, K)
def binomial_tree(payoff,S,K,T,r,sigma,N):
for i in range(0, N):
payoff = coeff*(p*payoff[:-1] + (1-p)*payoff[1:])
return payoff[0]
Note that I also changed the generation of arr
to be without a loop and changed the name of the payload()
function so that it does not interfere with the variable name.
EDIT
I asked a similar question because I thought your formula was interesting and the answer from Frank Yellin also applies here (so all credits to him):
import numpy as np
from scipy.stats import binom
binomial = binom(p=p, n=N)
pmf = binomial(np.arange(N+1))
res = coeff**n*np.sum(payoff * pmf)
In this form it is also clearer what is calculated in your loop:
the expected value of the binomial distributed random variable payoff.
0
solved What is wrong with this Binomial Tree Backwards Induction European Call Option Pricing Function?