title: Implied volatility calculation in Python
body: <p>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.</p>
  
  <p>I am trying to create a short code to calculate the implied volatility of a European Call option. I wrote the code below:  </p>
  
  <pre><code>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 &lt; 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) &lt; 0.001:
              return sigma
          sigma +=0.001
      return "could not find the right volatility"
  
  print implied_volatility(15,100,100,1,0.05)
  </code></pre>
  
  <p>This yields: 0.595 volatility which should be somewhere 0.3203. That is a huge difference...</p>
  
  <p>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: <a href="http://www.option-price.com/implied-volatility.php" rel="nofollow">Implied Volatility</a>. Could anyone please help me to figure out where I made the mistake?</p>