目錄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