tf-quant-finance 二维插值 Interpolation2D 实战指南:从波动率曲面到局部波动率模型

原创2026-10-12 10:52:091,879 阅读
文章标签:金融科技科学计算机器学习

tf-quant-finance 二维插值 Interpolation2D 实战指南:从波动率曲面到局部波动率模型

本篇文章以 tf-quant-finance 官方 API 文档 Interpolation2D 为核心,深入讲解 tf_quant_finance.math.interpolation.interpolation_2d.Interpolation2D 这一二维插值工具的接口设计、算法原理与实战用法。该模块在量化金融中主要用于对波动率曲面、总方差曲面、局部波动率/杠杆函数等二维函数进行插值,读者学完后可以独立完成"基于离散市场报价构建连续可查询的二维曲面"这一核心任务。

一、Interpolation2D 是什么

Interpolation2D 是 tf-quant-finance 数学插值模块 tff.math.interpolation.interpolation_2d 提供的二维插值类,用于在二维空间(x 方向、y 方向)中对函数值 z 进行插值。其典型应用场景包括:

  • 波动率曲面插值:以到期时间(times)和行权价(strikes)为坐标,插值得到任意点上的波动率;
  • 总方差(total variance)插值:对 到期时间 × 行权价 网格上的总方差进行插值;
  • 杠杆函数 / 局部波动率模型:对 PDE 求解得到的离散杠杆函数值进行二维插值(见后文源码佐证)。

从源码结构看,Interpolation2D 并不是独立实现的一套新算法,而是对 tf-quant-finance 已有的两个一维插值工具的组合封装:

方向 使用的底层算法 说明
y 方向(第一个阶段) 一维三次样条插值(cubic spline) 对每个 x_data 点、对所有查询点 y 进行插值
x 方向(第二个阶段) 一维线性插值(linear interpolation) 对插值得到的中间结果沿 x 方向进行线性插值

这正是文档中所描述的"两步走"流程:先在 y 方向用三次样条,再在 x 方向用线性插值。其对应源码位于 interpolation_2d.py。

二、快速上手:波动率曲面插值示例

文档给出了一个完整的波动率曲面插值示例,这是理解 Interpolation2D 用法的最佳入口。以下代码来自官方文档,并保留了完整的数据构造过程:

import numpy as np
import tensorflow as tf
import tf_quant_finance as tff

interpolation_2d = tff.math.interpolation.interpolation_2d

dtype = np.float64
# 待插值的查询点:(times, strikes)
times = tf.constant([2., 2.5, 3, 4.5], dtype=dtype)
strikes = tf.constant([16, 22, 35], dtype=dtype)

# 网格数据:x 方向上的到期时间点
times_data = tf.constant([1.5, 2.5, 3.5, 4.5, 5.5], dtype=dtype)
# 网格数据:y 方向上对应每个时间点的平方波动率
sigma_square_data = tf.constant(
    [[0.15, 0.25, 0.35, 0.4, 0.45, 0.4],
     [0.2, 0.35, 0.55, 0.45, 0.4, 0.6],
     [0.3, 0.45, 0.25, 0.4, 0.5, 0.65],
     [0.25, 0.25, 0.45, 0.25, 0.5, 0.55],
     [0.35, 0.35, 0.25, 0.4, 0.55, 0.65]], dtype=dtype)
# 插值对象针对总方差进行插值
total_variance = tf.expand_dims(times_data, -1) * sigma_square_data
# 对应行权价数据,需要广播到 sigma_square_data 的形状
strike_data = tf.broadcast_to(
    tf.constant([15, 25, 35, 40, 50, 55], dtype=dtype), [5, 6])

# 构造插值器,并在坐标 (times, strikes) 上进行插值
interpolator = Interpolation2D(times_data, strike_data, total_variance,
                               dtype=dtype)
interpolated_values = interpolator.interpolate(times, strikes)

代码要点拆解

  1. 数据维度约定:times_data 是长度为 5 的一维向量,作为 x 方向的网格;strike_data 和 total_variance 均为 [5, 6] 的矩阵。其中每一行对应一个 times_data 点,行内的 6 个值对应 y 方向(行权价方向)的网格点及其函数值。
  2. 广播操作:strike_data 由长度为 6 的一维行权价向量通过 tf.broadcast_to 广播到 [5, 6]。文档特别强调这一步是必需的,因为 y 方向的数据点要求是二维的(shape 为 batch_shape + [num_x_data_points, num_y_data_points])。
  3. 插值目标的选择:注释明确指出"插值是对总方差(total variance)进行的",即 times × sigma_square,这是衍生品定价中更自然、更平滑的插值对象。

测试验证

该示例对应的单元测试位于 interpolation_2d_test.py 的 test_docstring_example 方法中。测试对 float32 和 float64 两种 dtype 均做了验证,并给出了期望数值结果:

expected_vols = np.array([0.382399, 0.716694, 1.125])

测试断言插值结果的 dtype 与输入一致、形状为 [3](与查询点数一致),且与期望值在 rtol=1e-04, atol=1e-04 容差内吻合。这说明文档示例是可复现、可验证的。

三、构造器参数详解

Interpolation2D 的构造器签名如下(来自 interpolation_2d.py):

Interpolation2D(
    x_data, y_data, z_data, dtype=None, name=None
)

参数说明

参数 形状要求 含义与约束
x_data batch_shape + [num_x_data_points] x 方向坐标数据。num_x_data_points 必须 ≥ 2,且元素须按非递减顺序排列
y_data batch_shape + [num_x_data_points, num_y_data_points] y 方向坐标数据,dtype 须与 x_data 一致。num_y_data_points 必须 ≥ 2,最后一个维度上的元素须按非递减顺序排列
z_data 与 y_data 相同的 shape 和 dtype z 坐标数据,即每个网格点上的函数值
dtype — 可选参数,输入 Tensor 的 dtype。默认 None,映射为 TensorFlow 推断出的默认 dtype
name — 可选字符串,作为该类创建的所有 op 的名称前缀。默认 None,映射为默认名 interpolation_2d

从源码看参数处理逻辑

构造器内部(interpolation_2d.py)做了以下几件事:

  1. name = name or "interpolation_2d":为 op 命名;
  2. 依次调用 tf.convert_to_tensor 将 x_data、y_data、z_data 统一转换为 Tensor,其中 y_data、z_data 使用由 x_data 推断出的 dtype;
  3. 关键步骤:调用 cubic.build_spline(self._ydata, self._zdata, name="spline_y_direction"),为每个 x_data 点构建 y 方向上的三次样条。也就是说,样条构建在构造阶段一次性完成,后续每次 interpolate 调用只做查值与线性插值,因此构造一次、多次复用的效率很高。

四、interpolate 方法与算法流程

方法签名

interpolate(
    x, y, name=None
)

参数约束(来自 interpolation_2d.py):

  • x:实数 Tensor,形状 batch_shape + [num_points],指定插值点的 x 坐标。batch_shape 必须与底层数据一致;
  • y:与 x 同 shape、同 dtype 的 Tensor,指定插值点的 y 坐标;
  • name:op 名称前缀,默认 None 映射为 interpolate。

返回:与 x 同 shape、同 dtype 的 Tensor,表示在坐标 (x, y) 处插值得到的函数值。

底层两步算法拆解

结合 interpolation_2d.py 的源码实现,interpolate 的执行流程如下:

第一步:y 方向三次样条插值

  • 将查询点 y 通过 tf.expand_dims(y, axis=-2) 扩展一个维度,使其形状变为 batch_shape + [1, num_points];
  • 调用 cubic.interpolate(y, self._spline_yz, name="interpolation_in_y_direction"),对每个 x_data 点、在所有查询点 y 处计算样条插值结果。这一步输出形状为 batch_shape + [num_x_data_points, num_points] 的中间张量。

第二步:x 方向线性插值

  • 通过 tf.transpose 将中间结果的最后维度移到最前,便于按 x 方向做一维插值;
  • 对 x 做类似的转置与 tf.expand_dims(x, ..., axis=-1) 扩展;
  • 调用 linear.interpolate(x, self._xdata, yx) 沿 x 方向做线性插值;
  • 最后通过转置和 tf.squeeze 还原为 (x, y) 查询点的原始形状并返回。

边界行为:常数外推与自然边界

文档明确说明了两类边界行为,源码中也有对应实现:

  1. 线性插值的常数外推(constant extrapolation):在 linear_interpolation.py 中,left_slope 与 right_slope 默认均为 0,因此当查询点超出 x_data 范围时,外推值分别是左端点和右端点的 y 值(即常数外推)。
  2. 三次样条的自然边界条件(natural boundary conditions):底层三次样条构建(cubic_interpolation.py)默认使用 BoundaryConditionType.NATURAL,即样条在两个端点处的二阶导数为零。

值得注意的是,测试 interpolation_2d_test.py 中特别注释:"由于我们使用 natural 三次插值,得到的样条与原始三次多项式并不相同"——这提醒使用者,自然样条是对数据的平滑逼近,并非对原始生成函数的精确还原。

五、支持 batch 与梯度:面向高级用法的能力

Batch 维度支持

Interpolation2D 的所有输入都支持 batch_shape 前缀,意味着可以一次性插值多组独立曲面。单元测试 test_batch 展示了这一能力:

  • 两组不同 times_data(每组 5 个到期点);
  • 通过 tf.broadcast_to 将 strike_data 和 sigma_square_data 广播到 [2, 5, 6];
  • 查询点 times 和 strikes 形状均为 [2, 3];
  • 插值结果形状为 [2, 3],两个 batch 成员分别得到各自的插值结果(期望值 [0.38239871, 0.71669375, 1.125] 与 [0.40785739, 0.85479298, 1.00384615])。

这意味着在金融实践中,可以同时处理多只标的、多种货币或多种利率场景的曲面,而无需编写循环。

与自动微分的兼容

插值操作在 TensorFlow 计算图中是可微的。测试 test_grad 使用 tff.math.fwd_gradient(前向梯度,定义于 fwd_gradient.md)分别对 times 和 strikes 计算了插值结果关于查询坐标的梯度,并与有限差分法得到的期望值([0.284797, 0.386694, -0.5] 与 [0.02002702, 0.04353051, 0.01577941])对照验证。

这一特性对量化金融意义重大:例如在波动率曲面校准、敏感性分析(Greeks)、局部波动率模型等需要基于曲面导数进行数值求解或优化的场景中,可以直接利用反向传播或前向模式自动微分获得曲面梯度,而无需手动推导。

六、仓库内的真实应用:Interpolation2D 在生产代码中的使用

Interpolation2D 并非孤立的教学示例,它已作为基础组件被 tf-quant-finance 的多个实验性金融模型直接使用,这可以从源码调用点得到验证。

1. 波动率曲面对象(VolatilitySurface)

在 volatility_surface.py 中,Interpolation2D 是波动率曲面插值的默认实现:

if interpolator is None:
  interpolator_obj = interpolation_2d.Interpolation2D(
      expiry_times, strikes, volatilities, dtype=self._dtype)
  def interpolator_fn(t, x):
    return interpolator_obj.interpolate(t, x)
  self._interpolator = interpolator_fn

该类的文档字符串明确指出:interpolator 参数"默认为 None,此时使用 Interpolation2D",其职责是接受两个实数 Tensor(行权价与到期时间),返回插值后的隐含波动率。也就是说,只要构建了 VolatilitySurface,底层就是 Interpolation2D 在干活。

2. 局部波动率模型(LocalVolatilityModel)

在 local_volatility_model.py 中,Interpolation2D 被用于构造以"对数远期 moneyness"为 y 坐标的隐含波动率曲面:

interpolator = interpolation_2d.Interpolation2D(
    expiry_times,
    _log_forward_moneyness(expiry_times, strikes),
    implied_volatilities,
    dtype=dtype)

这里 _log_forward_moneyness 计算 log(strike / (spot * exp((r-d) * times))),将行权价坐标变换为对数远期 moneyness,再与到期时间一起构成二维插值坐标——这是 Dupire 局部波动率公式中标准的曲面参数化方式。

3. 局部随机波动率模型(LSV)

在 local_stochastic_volatility_model.py 中,Interpolation2D 被用来对 PDE 数值求解得到的离散**杠杆函数(leverage function)**做二维插值:

leverage_fn_interpolator = (
    math.interpolation.interpolation_2d.Interpolation2D(
        x_data=[times],
        y_data=tf.expand_dims(
            tf.repeat(grid[0] + x_scale, times.shape[0], axis=0), axis=0),
        z_data=tf.expand_dims(leverage_fn_values, axis=0),
        dtype=dtype))
return leverage_fn_interpolator.interpolate(t, tf.math.log(spot))

该场景展示了 Interpolation2D 的一个通用化用法:x 坐标为 PDE 时间网格,y 坐标为空间网格(经 x_scale 平移并对齐到时间步数),z 为每个 (t, x) 格点上的杠杆函数值;最终返回的是在任意 (t, log(spot)) 处的连续化杠杆函数值。

4. 模块组织方式

从 BUILD 与 init.py 可以看出模块的依赖关系:interpolation_2d 的 py_library 依赖 cubic、linear、types 与 math/piecewise 子模块,并对外仅暴露 Interpolation2D 一个符号。使用时可从顶层导入:

import tf_quant_finance as tff
interpolation_2d = tff.math.interpolation.interpolation_2d

七、实践注意事项与最佳实践

基于文档约束与源码实现,总结以下使用建议:

  1. 数据顺序约束:x_data 与 y_data(最后一维)必须非递减。若未排序,插值结果将出错。底层 cubic/linear 模块都提供了 validate_args=True 选项用于运行时校验,但 Interpolation2D 构造器本身未暴露该校验开关,因此调用方需自行保证数据有序。
  2. 网格点数下限:x、y 两个方向的数据点均需 ≥ 2。对于更精细的曲面,y 方向使用三次样条,建议网格点数充足以获得光滑的曲面。
  3. 常数外推语义:查询点落在 x 方向数据范围之外时,得到的是边界处的函数值(常数外推),而非线性外推或零值——这在定价与风险计算中需要特别留意,避免把外推区误认为插值区。
  4. 构造一次、多次查询:样条系数在构造阶段计算完成,同一插值器对象可对任意数量的查询点批量调用 interpolate,适合在计算图中反复查询曲面的场景。
  5. 与自动微分协同:插值结果对查询坐标可微,可直接接入 tff.math.fwd_gradient、tf.GradientTape 等机制,用于计算曲面敏感性。

八、小结

Interpolation2D 是 tf-quant-finance 中连接"离散市场数据"与"连续金融模型"的关键桥梁:它用 y 方向自然三次样条 + x 方向常数外推线性插值的组合,将二维网格上的函数值平滑化为任意查询点上可求值、可微分的连续函数。无论是直接用于波动率/总方差曲面插值,还是作为 VolatilitySurface 的默认引擎、局部波动率与 LSV 模型的杠杆函数插值器,它都是量化研究与生产代码中高频复用的基础组件。掌握了它的数据形状约定、边界行为与批处理/梯度能力,就等于掌握了 tf-quant-finance 中二维曲面插值的标准范式。

登录后查看全文
tf-quant-finance