繁体   English   中英

绘制波动率表面时出现 QuantLib 错误

[英]QuantLib error while Plotting Volatility Surface

我正在尝试使用以下代码 plot 波动率表面:

        plot_years = np.arange(0, 2, 0.1)
    plot_strikes = np.arange(535, 750, 1)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X, Y = np.meshgrid(plot_strikes, plot_years)
    Z = np.array([black_var_surface.blackVol(y, x) 
                  for xr, yr in zip(X, Y) 
                      for x, y in zip(xr,yr) ]
                 ).reshape(len(X), len(X[0]))
    
    surf = ax.plot_surface(X,Y,Z, rstride=1, cstride=1, cmap=cm.coolwarm, 
                    linewidth=0.1)
    fig.colorbar(surf, shrink=0.5, aspect=5)

但我得到这个错误:


    TypeError                                 Traceback (most recent call last)
    <ipython-input-55-8132b1b292ed> in <module>
          4 ax = fig.gca(projection='3d')
          5 X, Y = np.meshgrid(plot_strikes, plot_years)
    ----> 6 Z = np.array([black_var_surface.blackVol(y, x) 
          7               for xr, yr in zip(X, Y)
          8                   for x, y in zip(xr,yr) ]
    
    <ipython-input-55-8132b1b292ed> in <listcomp>(.0)
          4 ax = fig.gca(projection='3d')
          5 X, Y = np.meshgrid(plot_strikes, plot_years)
    ----> 6 Z = np.array([black_var_surface.blackVol(y, x) 
          7               for xr, yr in zip(X, Y)
          8                   for x, y in zip(xr,yr) ]
    
    ~\anaconda3\lib\site-packages\QuantLib\QuantLib.py in blackVol(self, *args)
       7566 
       7567     def blackVol(self, *args):
    -> 7568         return _QuantLib.BlackVolTermStructure_blackVol(self, *args)
       7569 
       7570     def blackVariance(self, *args):
    
    TypeError: Wrong number or type of arguments for overloaded function 'BlackVolTermStructure_blackVol'.
      Possible C/C++ prototypes are:
        BlackVolTermStructure::blackVol(Date const &,Real,bool) const
        BlackVolTermStructure::blackVol(Date const &,Real) const
        BlackVolTermStructure::blackVol(Time,Real,bool) const
        BlackVolTermStructure::blackVol(Time,Real) const

我使用的是旧版本的 package 吗? 因为我正在使用 Goutham Balaraman 在 2016 年分享的笔记本。

谢谢您的帮助 !

The QuantLib functions and class methods are exposed from C++ through wrappers that perform type conversion from Python types to the underlying C++ types. The obvious ones are defined (Python int to C++ int , Python float to C++ double , even Python int to C++ double if needed) but others are not.

在您的情况下, C++ function 需要两个双打,但是xy是 numpy 类型(您可以使用print(type(x))print(type(x))进行检查) y来自np.arange(0, 2, 0.1)并且是np.float64类型,它可以转换为float然后 C++ double x相反,来自np.arange(535, 750, 1)并且是np.int64类型,它不会自动转换为float ,因此出现错误。

使这项工作的一种方法是显式转换变量,即

black_var_surface.blackVol(y, float(x))

另一种是使用

plot_strikes = np.arange(535.0, 750.0, 1.0)

它生成一个np.float64而不是np.int64的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM