Skip to main content
 首页 » 编程设计

python之Python中的隐含波动率计算

2024年10月24日13Free-Thinker

根据答案的评论,我重写了下面的代码 (math.1p(x)->math.log(x)),现在它应该可以工作并给出波动率的良好近似值。

我正在尝试创建一个短代码来计算欧式看涨期权的隐含波动率。我写了下面的代码:

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) 

这产生:0.595 的波动率,应该在 0.3203 左右。这是一个巨大的差异...

我知道这无论如何都不是一个快速的方法,我只是想演示这个原理是如何工作的,但我无法计算出一个好的近似值。 出于某种原因,当我调用该函数时,它给出了我使用 Matlab 程序和以下网页计算的实际隐含波动率的非常糟糕的近似值:Implied Volatility .谁能帮我找出我哪里出错了?

请您参考如下方法:

我看到两个问题,没有一个直接与 python 相关:

  1. 您正在使用 log1p(x),它是 1+x 的自然对数,而您实际上想要 log(x),它是 x 的自然对数(参见 Wikipedia )。

  2. 考虑到其他参数,100 的期权价格过高。尝试计算价格为 10 的隐含波动率 - 根据您的程序和您链接的计算器,它应该约为 0.18。