如果未做特別說明,文中的程序都是 Python3 代碼。
QuantLib 金融計算——數學工具之插值
載入模塊
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 提供了下列一維和二維插值方法:
LinearInterpolation
(1-D)LogLinearInterpolation
(1-D)BackwardFlatInterpolation
(1-D)ForwardFlatInterpolation
(1-D)BilinearInterpolation
(2-D)BicubicSpline
(2-D)
一維插值方法
一維插值方法常用於收益率曲線、波動率微笑曲線,其對象的構造基本如下:
myInt = XXXInterpolation(x,
y)
x
:浮點數序列,若干離散的自變量y
:浮點數序列,自變量對應的函數值,與x
等長
插值類定義了 __call__
方法,一個插值類對象的使用方式如下,作為一個函數
myInt(x, allowExtrapolation)
x
:浮點數,要插值的點allowExtrapolation
:布爾型,allowExtrapolation
為True
意味着允許外推,默認值是False
。
例子 1
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
二維插值方法
二維插值方法常用於波動率曲面,其對象的構造基本如下:
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
。
例子 2
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