Stack Overflow Asked by Wayne2 on December 9, 2021
Here is the situation:
I have a function which needs 8 Parameters:
def BlackScholes(typ, cp ,S0, K, r, q, sigma, T):
d1 = (np.log(S0 / K) + (r - q + sigma**2 / 2) * T) / (sigma * np.sqrt(T))
d2 = d1 - (sigma * np.sqrt(T))
if typ=='value':
return cp * np.exp(-q * T) * S0 * ss.norm.cdf(cp * d1) - cp * K * np.exp(-r * T) * ss.norm.cdf(cp* d2))
Now I call the def function in another script with:
K = WU
while K-BlackScholes('value', -1, S0, K, 0, 0, sigma, T ) < WU:
K = K+0.01
strikes = [K]
With the above mentioned function I get one Value for the strike. But I have a sigma array with a shape (8,500,1)
I want to iterate over the function with every value from the sigma array. So that I get a array of strikes with the same shape of the sigma array . Can I do it with a simple loop or do I have tu unpack the array in the function?
I already tried it with:
for i in sigma[1,i,:]:
while K-BlackScholes('value', -1, S0, K, 0, 0, sigma[1,i,:], T ) < WU:
K = K+0.01
i = i + 1
strikes = [K]
But it does not work either
I get the following error message:
IndexError: only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices
If I insert one single sigma value I get one strike. But I want to iterate over the array and insert every single sigma value into the function. So I get a array of strikes corresponding to the list of sigma.
sigma.shape(8,500,1) –> strike.shape(8,500,1)
Your for loop is wrong. It should be:
for i in range(sigma.shape[1]):
K = WU
while K - BlackScholes('value', -1, S0, K, 0, 0, sigma[1,i,:], T ) < WU:
K = K + 0.01
strikes = [K]
Now you get slices of size 8. If you want to iterate over all, you need another for loop to account for your second dimension:
(Edited)
K = np.empty_like(sigma)
for j in range(sigma.shape[0]):
for i in range(sigma.shape[1]):
K[j, i, :] = WU
while K - BlackScholes('value', -1, S0, K[j, i, :], 0, 0, sigma[j,i,:], T ) < WU:
K[j, i, :] += 0.01
strikes = K # not sure what this is for.
But I'm not sure if this is what you want.
Answered by Dorian on December 9, 2021
If the function cannot be vectorized, it has to be applied to every value from the sigma
ndarray (do not call it a list
unless it is 1D). You can just use plain Python loops:
strikes = np.ndarray(sigma.shape)
for i in range(sigma.shape[0]): # or for i in range(8)
for j in range(sigma.shape[1]): # ibidem...
# eventually for k in range...
K = WU
while K-BlackScholes('value', -1, S0, K, 0, 0, sigma[i, j, 1], T ) < WU:
K = K+0.01
strikes[i, j, 1] = K
Answered by Serge Ballesta on December 9, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP