QuantLib 金融计算——数学工具之插值

如果未做特别说明,文中的程序都是 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:布尔型,allowExtrapolationTrue 意味着允许外推,默认值是 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:矩阵,函数在 xy 所张成的网格上的取值

插值类定义了 __call__ 方法,一个插值类对象的使用方式如下,作为一个函数

myInt(x, y, allowExtrapolation)
  • xy:浮点数,分别是要插值的点在 x 和 y 轴上的坐标
  • allowExtrapolation:布尔型,allowExtrapolationTrue 意味着允许外推,默认值是 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

扩展阅读

《QuantLib 金融计算》系列合集

posted @ 2018-10-29 22:43  xuruilong100  阅读(2127)  评论(0编辑  收藏  举报