绘制波动率表面时的 QuantLib 错误

问题描述

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

        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,plot_years)
    ----> 6 Z = np.array([black_var_surface.blackVol(y,x) 
          7               for xr,Y)
          8                   for x,yr) ]
    
    <ipython-input-55-8132b1b292ed> in <listcomp>(.0)
          4 ax = fig.gca(projection='3d')
          5 X,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,bool) const
        BlackVolTermStructure::blackVol(Time,Real) const

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

感谢您的帮助!

解决方法

QuantLib 函数和类方法通过包装器从 C++ 公开,这些包装器执行从 Python 类型到底层 C++ 类型的类型转换。明显的定义(Python ffmpeg -i ../source/vid.mp4 -r 25 -vsync 0 -an ../frames/frame%d.png 到 C++ int,Python int 到 C++ float,如果需要,甚至 Python double 到 C++ int ) 但其他人不是。

在您的情况下,C++ 函数需要两个双打,但 doublex 是 numpy 类型(您可以使用 yprint(type(x)) 进行检查)。 print(type(x)) 来自 y,属于 np.arange(0,2,0.1) 类型,可以转换为 np.float64 和 C++ floatdouble 来自 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 的数组。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...