I'm trying to code functions, that compute financial greeks for B-S model.
I started with something like this:
def greeks_vanilla(S, K, r, q, t, T, sigma):
import numpy as np
from scipy.stats import norm
tau = np.linspace(t, T, num = T)
d1 = ( np.log(S/K) + (r - q + sigma**2 /2)*tau ) / (sigma * np.sqrt(tau))
d2 = d1 - sigma*np.sqrt(tau)
delta_call = np.exp(-q*tau) * norm.cdf(d1)
delta_put = -np.exp(-q*tau) * norm.cdf(-d1)
...
return {'d1':d1, 'd2': d2, 'delta_call': delta_call, 'delta_put': delta_put, ...}
'...' means, there are more greeks being computed, but it's not important here.
It was working fine, I had reasonable values, nice plots, etc.; however, my teacher told me, that he want to see those values versus not only time (tau on x-axis), but also versus S (S - stock price, on x-axis). In other words, I have to compute greeks for both tau and S changing.
I've tried following:
def greeks_vanilla(S, K, r, q, t, T, sigma):
import numpy as np
from scipy.stats import norm
S = np.linspace(1, S, num = S)
tau = np.linspace(t, T, num = T)
d1 = ( np.log(S/K) + (r - q + sigma**2 /2)*tau ) / (sigma * np.sqrt(tau))
d2 = d1 - sigma*np.sqrt(tau)
delta_call = np.exp(-q*tau) * norm.cdf(d1)
delta_put = -np.exp(-q*tau) * norm.cdf(-d1)
...
For both versions I initialized following params and run (a-variable):
S = 30.0 #Stock price
K = 50.0 #Strike price
r = 0.05 #Risk-free rate
q = 0.01 #also called delta, annual dividend yield
t = 1.0
T = 100.0
sigma = 0.15
a = greeks_vanilla(S, K, r, q, t, T, sigma)
It works fine in the first case, but when I want to vary S (second function), I'm getting following error:
File "greeks.py", line 11, in greeks_vanilla
d1 = ( np.log(S/K) + (r - q + sigma**2 /2)*tau ) / (sigma * np.sqrt(tau))
ValueError: operands could not be broadcast together with shapes (30,) (100,)
I googled a bit, and it's look like there is something with Numpy library and it's data types (arrays). I'm not very skilled or experienced programmer (still learning), so I wasn't able to figure it by myself.
It looks like it works now only with S == 100 (S = T), but that's not desirable solution.
I've tried:
S = list(S)
But it only outputs:
File "greeks.py", line 11, in greeks_vanilla
d1 = ( np.log(S/K) + (r - q + sigma**2 /2)*tau ) / (sigma * np.sqrt(tau))
TypeError: unsupported operand type(s) for /: 'list' and 'float'
Please, help me find working solution of this. I don't know if I should try to loop overs S (I tried and failed...), do some data type tricks, calculate it other way (how?) or anything else.