'Python round error define __round__ method

Hi Guys I have this code and this error message. Could you help me please :) I am trying to calculate the price of an option using Black Scholes model but when I run the code I am stuck with the error message at the bottom.

r = 0.01
S = 30
K = 40
T = 240/365
sigma = 0.30


def blackScholes(r, S, K, T, sigma, type="C"):
    "Calculate the BS option price for a call or put"
    d1 = (np.log(S/K)+(r+sigma**2/2)*T)/(sigma*np.sqrt(T))
    d2 = d1 - sigma*np.sqrt(T)
    try:
        if type == "C":
            price = S*norm.cdf(d1, 0, 1) - K*np.exp(-r*T)*norm.cdf(d2, 0, 1)
        elif type == "P":
            price = K*np.exp(-r*T)*norm.cdf(-d2, 0, 1) - S*norm.cdf(-d1, 0, 1)
            return price
    except:
        print("Please confirm option parameters above ma gueule")


print("Option price is :", round(blackScholes(r, S, K, T, sigma, type="C"),2))


 print("Option price is :", round(blackScholes(r, S, K, T, sigma, type="C"),2))
TypeError: type NoneType doesn't define __round__ method


Many thanks in advance !


Solution 1:[1]

You are only returning price in your function if type == 'P'. But for the branch type == 'C' there is no return statement. Maybe you mean:

try:
    if type == "C":
        price = S*norm.cdf(d1, 0, 1) - K*np.exp(-r*T)*norm.cdf(d2, 0, 1)
    elif type == "P":
        price = K*np.exp(-r*T)*norm.cdf(-d2, 0, 1) - S*norm.cdf(-d1, 0, 1)
    return price  # see the lack of an extra indent here

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Mark Dickinson