ValueError: The truth value of a Series is ambiguous. Using function and pandas df

103 Views Asked by At

Looking to run a function using dataframe elements to create a new column (IV) but the function is stuck on the line below.

Error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Line:if (abs(diff) < PRECISION):

from scipy.stats import norm
import pandas as pd
import numpy as np

N = norm.cdf

def bs_call(S, K, T, r, vol):
    d1 = (np.log(S/K) + (r + 0.5*vol**2)*T) / (vol*np.sqrt(T))
    d2 = d1 - vol * np.sqrt(T)
    return S * norm.cdf(d1) - np.exp(-r * T) * K * norm.cdf(d2)

def bs_vega(S, K, T, r, sigma):
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
    return S * norm.pdf(d1) * np.sqrt(T)

def find_vol(target_value, S, K, T, r, *args):
    MAX_ITERATIONS = 200
    PRECISION = 1.0e-5
    sigma = 0.5
    for i in range(0, MAX_ITERATIONS):
        price = bs_call(S, K, T, r, sigma)
        vega = bs_vega(S, K, T, r, sigma)
        diff = target_value - price  # our root


        if (abs(diff) < PRECISION):
            return sigma
        sigma = sigma + diff/vega # f(x) / f'(x)

    print(sigma)
    return sigma # value wasn't found, return best guess so far


S = df['ClosingPrice']
K= df['Strike']
T= df['RemainingDays']/365
r= df['RfRate']
vol = 0.2

V_market = bs_call(S, K, T, r, vol)

implied_vol = find_vol(V_market, S, K, T, r)

df.loc[df['OptionType'] == 'c', 'IV'] = implied_vol
1

There are 1 best solutions below

0
Yosher On

That error occurs because you compare pandas.core.series.Series with a float value. As the error suggests you need to change the if clause to the one like if any(abs(diff) < PRECISION) or if all(abs(diff) < PRECISION).

Though this is a bit off the topic, I recommend you to:

  1. Share your full error log in order to make other commiters understand your problem quickly and get answers faster :)
  2. Insert debugging break point clause (e.g. from IPython.core.debugger import Pdb; Pdb().set_trace()) just before the error point and investigate (i.e. checking their data type in this case)