目录python
若是未作特别说明,文中的程序都是 Python3 代码。函数
载入模块工具
import QuantLib as ql import scipy print(ql.__version__)
1.12
“插值”是量化金融中最经常使用的工具之一,已知一组离散点以及未知函数 \(f\) 在这些点上的值 \((x_i , f(x_i )) i \in \{0, \dots, n\}\),要近似求出任意一点 \(x \in [x_0 , x_n ]\) 上的函数值。标准的应用场景是对收益率曲线、波动率微笑曲线和波动率曲面的插值。quantlib-python 提供了下列一维和二维插值方法:spa
LinearInterpolation
(1-D)LogLinearInterpolation
(1-D)BackwardFlatInterpolation
(1-D)ForwardFlatInterpolation
(1-D)BilinearInterpolation
(2-D)BicubicSpline
(2-D)一维插值方法经常使用于收益率曲线、波动率微笑曲线,其对象的构造基本以下:code
myInt = XXXInterpolation(x, y)
x
:浮点数序列,若干离散的自变量y
:浮点数序列,自变量对应的函数值,与 x
等长插值类定义了 __call__
方法,一个插值类对象的使用方式以下,做为一个函数对象
myInt(x, allowExtrapolation)
x
:浮点数,要插值的点allowExtrapolation
:布尔型,allowExtrapolation
为 True
意味着容许外推,默认值是 False
。例子 1ip
def testingInterpolations1(): xVec = [0.0, 1.0, 2.0, 3.0, 4.0] yVec = [scipy.exp(x) for x in xVec] linInt = ql.LinearInterpolation(xVec, yVec) print("Exp at 0.0 ", linInt(0.0)) print("Exp at 0.5 ", linInt(0.5)) print("Exp at 1.0 ", linInt(1.0))
# Exp at 0.0 1.0 # Exp at 0.5 1.8591409142295225 # Exp at 1.0 2.718281828459045
二维插值方法经常使用于波动率曲面,其对象的构造基本以下:ci
myInt = XXXInterpolation(x, y, m)
x
:浮点数序列,x 轴上的若干离散的自变量y
:浮点数序列,y 轴上的若干离散的自变量,与 x
等长m
:矩阵,函数在 x
和 y
所张成的网格上的取值插值类定义了 __call__
方法,一个插值类对象的使用方式以下,做为一个函数数学
myInt(x, y, allowExtrapolation)
x
、y
:浮点数,分别是要插值的点在 x 和 y 轴上的坐标allowExtrapolation
:布尔型,allowExtrapolation
为 True
意味着容许外推,默认值是 False
。例子 2it
def testingInterpolations2(): xVec = [float(i) for i in range(10)] yVec = [float(i) for i in range(10)] M = ql.Matrix(len(xVec), len(yVec)) for rowIt in range(len(xVec)): for colIt in range(len(yVec)): M[rowIt][colIt] = scipy.sin(xVec[rowIt]) + scipy.sin(yVec[colIt]) bicubIntp = ql.BicubicSpline( xVec, yVec, M) x = 0.5 y = 4.5 print("Analytical Value: ", scipy.sin(x) + scipy.sin(y)) print("Bicubic Value: ", bicubIntp(x, y)) testingInterpolations4()
Analytical Value: -0.498104579060894 Bicubic Value: -0.49656170664824184