What is wrong with this Binomial Tree Backwards Induction European Call Option Pricing Function?

2024/7/6 21:52:44

The function below works perfectly and only needs one thing: Removal of the for loop that creates the 1000 element array arr.

Can you help me get rid of that for loop? Code is below

#Test with european call
import numpy as np
T = 1
N = 1000
sigma = 0.5
r = 0.02
S = 1
K = 0.7
u = np.exp(sigma*np.sqrt(T/N))
d = 1/uarr = np.zeros(N+1)    
arr[0] = S*np.power(u,N)coeff = np.exp(-r*(T/N))
p = (np.exp(r*(T/N))-d)/(u-d)       for i in range(1, N+1):arr[i] = arr[i-1] * (d/u)     def get_payoff(S=arr, K=K): payoff = np.maximum((S - K), 0)return payoffpayoff = get_payoff()def binomial_tree(payoff,S,K,T,r,sigma,N):for i in range(0, N):upper_vector = np.delete(payoff, N - i)lower_vector = np.delete(payoff, 0)payoff = coeff*(p*upper_vector + (1-p)*lower_vector)   return payoff[0]print(binomial_tree(payoff,1,0.7,1,0.02,0.5,1000))
Answer

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 binombinomial = 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.

https://en.xdnf.cn/q/119840.html

Related Q&A

Regex behaving weird when finding floating point strings [duplicate]

This question already has answers here:re.findall behaves weird(3 answers)Closed 4 years ago.So doing this (in python 3.7.3):>>> from re import findall >>> s = 7.95 + 10 pieces >&g…

how do i get this code to tell me what position a word in the sentence is

varSentence = ("The fat cat sat on the mat")print (varSentence)varWord = input("Enter word ")varSplit = varSentence.split()if varWord in varSplit:print ("Found word") else…

Reverse geocoding with Python/GoogleMaps API: How to parse response

Im attempting to use the Google Maps Geocoding API to find the State associated with a latitude and longitude with a Python script. I have no trouble getting back a response from the server, but when …

How to constantly generate random numbers inside for i in range loop

import random world_size=8 for i in range(world_size)chunk_type=random.randint(1,2)print(chunk_type)import randomclass chunk_type():chunk_type=random.randint(1,2)world_size=8for i in range(world_size):…

How to count IDs that have a given combination of flags?

I have dataframe like that. I need to choose and count all distinct users, who have title "banner_click" and "order". So I dont understand how to do it in pandas, in SQL you do like…

How to calculate quarterly wise churn and retention rate using python

How to calculate quarterly wise churn and retention rate with date column using python. with date column i want to group that quarterly using python.This is used to calculate the churn count groupby qu…

splitting a list into two lists based on a unique value

I have a text file that looks something like this:hello 12 hello 56 world 25 world 26Is there a way in python that I can somehow parse the list that I obtain from reading this data to obtain two separa…

Customize axes in Matplotlib

I am a beginner with Python, Pandas and Matplotlib. I would like to customize the entries at the axes of a scatter plot. I have the following data:So on the x-axis there should be 5 entries, with the f…

how to show the max and min from user input?

Nevermindif xmin == 1:print(ymin)I tried using the max and min but I get a typeerror which is int object not iterable.

To output a string without whitespce

My program:def string_splosion(str):j=1c=len(str)i=0s=while(i<c):s=s+(str[:i+j])i=i+1print sprint("Enter a string:") s=raw_input() string_splosion(s)Sample input:Code Expected output:CCoCo…