'apply my created function to a data frame

I have the following function to calculate the black scholes model, where I paste the necessary data from S0, K , K , T , r and market_price in the function manually.

I would like to apply this same function to a pandas data frame There I have the values ​​needed to perform the calculation

Data frame example

data = {'Name':['BOVAE115', 'BOVAE119', 'BBDCE251', 'BBDCE246'],
        'Valor':[110.050003, 110.050003, 19.500000, 19.500000],
        'Strike Value':[15.00, 19.00, 24.67, 25.19],
        'Temp':[0.119048, 0.119048, 0.119048, 0.119048],
        'Taxa':[11.65, 11.65, 11.65, 11.65],
        'Market Price':[0.391968, 0.391968, 0.391968, 0.391968],
        'Order':['c','c','c','c']
       
       }
 
# Create DataFrame
df = pd.DataFrame(data)
df

How do I apply the created function to this list of values Function

See the code

 S0 = df['Valor']
 K = df['Strike Value']
 T = df['Temp']
 r = df['Taxa']
 market_price = df['Price']
 flag = df['Order']


from py_vollib.black_scholes import black_scholes as bs
from py_vollib.black_scholes.greeks.analytical import vega


def implied_vol(S0, K, T, r, market_price, flag='c', tol=0.00001):
    
    #"""Calculating the implied volatility of an European option
    #    S0: stock price
    #    K: strike price
    #    T: time to maturity
    #    r: risk-free rate
    #    market_price: option price in market
    #"""
    
    max_iter = 500 #max no. of iterations
    vol_old = 0.3 #initial guess 
    
    for k in range(max_iter):
        bs_price = bs(flag, S0, K, T, r, vol_old)
        Cprime = vega(flag, S0, K, T, r, vol_old)*100
        C = bs_price - market_price

        vol_new = vol_old - C/Cprime
        new_bs_price = bs(flag, S0, K, T, r, vol_new)
        if (abs(vol_old-vol_new) < tol or abs(new_bs_price-market_price) < tol):
            break
        vol_old = vol_new

    implied_vol = vol_new
    return implied_vol

S0 = 14.73
K =  15.04
T =  20/252
r = 0.1165
market_price = 0.41


print(implied_vol(S0, K, T, r, market_price)*100)

I wanted to return the implied vol value in a data frame column

How can I apply this function in my dataframe



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source