For my thesis I need the implied volatility of options, I already created the following function for it:
#Implied volatility solver
def Implied_Vol_Solver(s_t,K,t,r_f,option,step_size):
#s_t=Current stock price, K=Strike price, t=time until maturity, r_f=risk-free rate and option=option price,stepsize=is precision in stepsizes
#sigma set equal to steps to make a step siz equal to the starting point
sigma=step_size
while sigma < 1:
#Regualar BlackScholes formula (current only call option, will also be used to calculate put options)
d_1=(np.log(s_t/K)+(r_f+(sigma**2)/2)*t)/(sigma*(np.sqrt(t)))
d_2=d_1-np.square(t)*sigma
P_implied=s_t*norm.cdf(d_1)-K*np.exp(-r_f*t)*norm.cdf(d_2)
if option-(P_implied)<step_size:
#convert stepts to a string to find the decimal point (couldn't be done with a float)
step_size=str(step_size)
#rounds sigma equal to the stepsize
return round(sigma,step_size[::-1].find('.'))
sigma+=step_size
return "Could not find the right volatility"
The variables I need are located in a Pandas DataFrame and I already created a loop for it, to test if it works (I will add the other variables when it works correctly):
for x in df_option_data['Settlement_Price']:
df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,x,0.001)
However when I run this loop I will get 0.539 for the whole Implied_Voltality Column and these numbers needs to be different, what do I wrong? Or are there any easier solutions?
I also tried the following:
df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,np.array(df_option_data['Settlement_Price']),0.001)
But than I get the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Essentially what I need is the following: A dataframe with 5 columns for the input variables and 1 column with the output variables (the implied volatility) which is calculated by the function.