Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implied volatility calculation in Python

With the comments from the answer, I rewrote the code below (math.1p(x)->math.log(x)), which now should work and give a good approximation of the volatility.

I am trying to create a short code to calculate the implied volatility of a European Call option. I wrote the code below:

from scipy.stats import norm
import math

norm.cdf(1.96)
#c_p - Call(+1) or Put(-1) option
#P - Price of option
#S - Strike price
#E - Exercise price
#T - Time to expiration
#r - Risk-free rate

#C = SN(d_1) - Ee^{-rT}N(D_2)


def implied_volatility(Price,Stock,Exercise,Time,Rf):
    P = float(Price)
    S = float(Stock)
    E = float(Exercise)
    T = float(Time)
    r = float(Rf)
    sigma = 0.01
    print (P, S, E, T, r)
    while sigma < 1:
        d_1 = float(float((math.log(S/E)+(r+(sigma**2)/2)*T))/float((sigma*(math.sqrt(T)))))
        d_2 = float(float((math.log(S/E)+(r-(sigma**2)/2)*T))/float((sigma*(math.sqrt(T)))))
        P_implied = float(S*norm.cdf(d_1) - E*math.exp(-r*T)*norm.cdf(d_2))
        if P-(P_implied) < 0.001:
            return sigma
        sigma +=0.001
    return "could not find the right volatility"

print implied_volatility(15,100,100,1,0.05)

This yields: 0.595 volatility which should be somewhere 0.3203. That is a huge difference...

I know this is not a fast method by any means, I just want to demonstrate how the principle works, but I am not able to calculate a good approximation. For some reason when I call the function it gives me really bad approximation of the actual implied volatility which I calculated using a Matlab Program and the following webpage: Implied Volatility. Could anyone please help me to figure out where I made the mistake?

like image 412
Gabor Bakos Avatar asked Jun 13 '26 13:06

Gabor Bakos


1 Answers

There are two problems I see, none of which are directly python related:

  1. You are using log1p(x), which is the natural logarithm of 1+x, while you actually want log(x), which is the natural logarithm of x (cf. Wikipedia).

  2. An option price of 100 is way to high considering the other parameters. Try to calculate the implied volatility for a price of 10 - which should be about 0.18 both by your program and the calculator you linked.

like image 93
Oliver Avatar answered Jun 15 '26 01:06

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!