tf-quant-finance 实战:用 swap_curve_fit 优化法构建零利率互换曲线
tf-quant-finance 实战:用 swap_curve_fit 优化法构建零利率互换曲线
导读
本文深入讲解 tf-quant-finance(TFF)中 tff.rates.swap_curve_fit 的完整用法与底层原理:它通过共轭梯度(conjugate gradient)优化最小化加权最小二乘损失,从一组已知市场价格的利率互换(IRS)反推出零利率互换曲线(zero swap curve),可独立用于折现,也可借助 OIS 等外部折现曲线实现双曲线估值。读完本文,你将掌握完整的参数语义、一段可直接运行的 4 笔 LIBOR 互换建曲线示例,以及自定插值器、自定义优化器、结算日与批量输入等进阶用法。
一、什么是"用优化法构建零互换曲线"
1.1 零互换曲线的定义
在 swap_curve_fit.py 的文档字符串中,零互换曲线被定义为时间的函数:给定任意时刻 t,该函数给出可用于投影(project)远期利率的利率,从而为利率证券估值。
1.2 问题建模
假设市场上有 N 笔到期日递增的利率互换 S_i(i = 1,...,N),其市场价格已知:
- 第
i笔互换在时刻T_{ij}(1 <= j <= n_i)产生现金流,其中n_i为该互换的现金流个数(含到期日); - 记
T_i = T_{i,n_i}为第i笔互换的最后一笔支付时间(即到期时间)。
swap_curve_fit 的目标是估计一组利率 r(T_i),使得这些利率被插值到所有其他现金流时间后,计算出的互换价值与市场价格一致(在给定容差内)。中间时刻的利率由用户指定的插值方法确定,默认采用利率的线性插值。
1.3 与 bootstrap 法的区别
TFF 在 rates/init.py 中同时导出两种建曲线方法:
swap_curve_fit:优化法,一次拟合整条曲线,天然支持批量与外部折现曲线;swap_curve_bootstrap:逐点剥靴法,逐笔期限依次求解。
两者在 swap_curve_test.py 中对同一组平价互换数据得到几乎一致的结果(1.0, 2.0, ..., 30.0 期限上的零利率误差在 1e-5 以内),可以互为校验。本文聚焦优化法 swap_curve_fit。
二、函数签名与整体流程
2.1 完整签名
tf_quant_finance.rates.swap_curve_fit(
float_leg_start_times, float_leg_end_times, float_leg_daycount_fractions,
fixed_leg_start_times, fixed_leg_end_times, fixed_leg_daycount_fractions,
fixed_leg_cashflows, present_values, initial_curve_rates,
present_values_settlement_times=None, float_leg_discount_rates=None,
float_leg_discount_times=None, fixed_leg_discount_rates=None,
fixed_leg_discount_times=None, optimizer=None, curve_interpolator=None,
instrument_weights=None, curve_tolerance=1e-08, maximum_iterations=50,
dtype=None, name=None
)
前 9 个参数为必填(其中 initial_curve_rates 虽在签名中为位置参数,但若传 None 会直接抛出 ValueError,见下文"异常处理")。
2.2 源码中的执行流程
从 swap_curve_fit.py 可以看到,函数主体按如下顺序组织:
- 确定优化器:
optimizer为None时默认使用optimizers.conjugate_gradient_minimize(即 conjugate_gradient.py 中的minimize); - 统一 dtype:通过内部
_convert_to_tensors将所有输入转为同一dtype的Tensor,并以present_values的 dtype 为准(swap_curve_fit.py); - 处理结算时间:未提供
present_values_settlement_times时,为每笔互换生成零结算时间(swap_curve_fit.py); - 初始化权重:
instrument_weights为None时调用_initialize_instrument_weights生成默认权重(见 4.3 节); - 设置插值器:
curve_interpolator为None时默认使用linear.interpolate(swap_curve_fit.py); - 判断折现方式:若未指定任何外部折现曲线,则浮端、固端均使用被构建的曲线自折现(
self_discounting_float_leg = True、self_discounting_fixed_leg = True); - 校验初始曲线:
initial_curve_rates为None时抛ValueError; - 最终调用内部函数
_build_swap_curve完成优化与结果组装。
三、核心算法原理:加权最小二乘 + 共轭梯度
在内部函数 _build_swap_curve(swap_curve_fit.py)中,拟合过程被注释清晰地概括为三步:
- 从初始曲线状态出发;
- 定义损失函数,度量模型价格与输入现值(市场价)的偏差;
- 用数值优化(默认共轭梯度)最小化损失,得到拟合曲线。
3.1 损失函数(源码级解读)
损失函数由 @make_val_and_grad_fn 装饰(swap_curve_fit.py),其计算链路为:
-
投影浮动现金流:在浮端计息区间起点/终点处插值得到
rates_start、rates_end,浮动现金流按下式计算(连续复利下的远期利率):float_cashflows = exp(end * rates_end - start * rates_start) - 1 -
折现:若自折现,浮端与固端都用被拟合曲线插值;否则使用外部折现曲线插值(
exp(-r(t)*t),并考虑结算时间的exp(r(t_s)*t_s)修正); -
分组加总 PV:浮端 PV 为
float_cashflows * 折现因子按互换分组求和,固端 PV 为daycount_fraction * 固定现金流 * 折现因子分组求和,swap_pv = float_pv + fixed_pv; -
损失值:
value = sum_i [ instrument_weights_i * (swap_pv_i - present_values_i)^2 ]即带权重的均方误差,其中求和沿最后一维(各笔互换)进行。
值得说明的是,代码中分组求和通过 tf.one_hot 构造的分组矩阵 calc_groups_float、calc_groups_fixed 配合 tf.linalg.matvec 完成,而不是直接使用 tf.math.segment_sum(源码注释 TODO(b/178173737) 说明这是为了绕开当时 segment_sum 的性能问题)。
3.2 优化器接口
默认的共轭梯度优化器接口约定如下:
result = optimizer(value_and_gradients_function, initial_position, tolerance, max_iterations)
value_and_gradients_function:接受一个实数Tensor点,返回(函数值, 梯度)元组;initial_position:优化起点;tolerance:停止容差(实数标量Tensor);max_iterations:最大迭代次数。
优化器返回一个命名元组,至少包含:position(最优值)、converged(是否按准则收敛)、failed(是否失败)、num_iterations(迭代次数)、objective_value(最优处的目标函数值)。TFF 的共轭梯度实现基于 Hager-Zhang 的 CG_DESCENT 算法(见 conjugate_gradient.py 头部引用的文献),其 OptimizerResult 还额外提供 objective_gradient 与 num_objective_evaluations 字段。
四、参数详解(完整参考表)
以下参数说明完整继承自 API 文档,并结合源码给出补充解释。
4.1 必填参数
| 参数 | 类型与形状 | 含义 |
|---|---|---|
float_leg_start_times |
Tensor 列表,形状 batch_shape + [k_i] 或 [k_i] |
每笔互换浮端确定浮动支付的远期利率的计息期起点;列表每个元素对应一笔互换,k_i 可各不相同 |
float_leg_end_times |
与上兼容 | 浮端计息期终点 |
float_leg_daycount_fractions |
与上兼容 | 浮端远期利率对应的 daycount fraction(计息天数比例) |
fixed_leg_start_times |
Tensor 列表,形状 batch_shape + [n_i] 或 [n_i] |
固端固定票息计息期起点;n_i 可各不相同,dtype 须与 float_leg_start_times 一致 |
fixed_leg_end_times |
与上兼容 | 固端计息期终点 |
fixed_leg_daycount_fractions |
与上兼容 | 固端支付对应的 daycount fraction |
fixed_leg_cashflows |
与上兼容 | 每个票息支付时点的固定现金流(含本金,若有);符号约定:负值表示净流出,正值表示净流入 |
present_values |
与 fixed_leg_cashflows 同 dtype,形状兼容 batch_shape |
底层工具的市场价格;列表长度必须与 fixed_leg_cashflows 一致 |
initial_curve_rates |
形状 [batch_shape, num_instruments] |
迭代过程的初始折扣率猜测值;num_instruments 即 float_leg_start_times 的长度 |
4.2 可选参数(含默认值)
| 参数 | 默认值 | 含义 |
|---|---|---|
present_values_settlement_times |
None(等价于全部为 0) |
从交易日到购买价格实际交付的结算时间;None 视为所有互换零结算 |
float_leg_discount_rates |
None |
用于折现浮端现金流的连续复利折扣率;用于以独立折现曲线(如 OIS)建曲线 |
float_leg_discount_times |
None |
与 float_leg_discount_rates 对应的时刻 |
fixed_leg_discount_rates |
None |
用于折现固端现金流的连续复利折扣率;作用同上 |
fixed_leg_discount_times |
None |
与 fixed_leg_discount_rates 对应的时刻 |
optimizer |
None → 共轭梯度 |
自定义最小化算法(接口见 3.2 节) |
curve_interpolator |
None → 线性插值 |
自定义曲线插值器,接口 yi = curve_interpolator(xi, x, y) |
instrument_weights |
None → 到期日的倒数 |
各工具在目标函数中的权重 |
curve_tolerance |
1e-8 |
迭代停止的绝对容差:当各到期时点估计折扣值单次迭代变化小于该值时停止 |
maximum_iterations |
50 |
允许的最大迭代次数 |
dtype |
None → 由 TensorFlow 推断 |
统一输入的 tf.Dtype |
name |
None → 'swap_curve' |
创建 op 的名称 |
4.3 默认权重的源码实现
若未指定 instrument_weights,_initialize_instrument_weights(swap_curve_fit.py)会取浮端与固端最后一笔支付时间(即各互换到期日),按 1 / 到期时间 计算权重,并用 tf.minimum(1, weight) 限制权重不超过 1。也就是说:到期越短的互换在拟合中权重越大——这与"短端市场报价更可信"的行业惯例一致。
4.4 折现方式的三个分支(源码细节)
在 swap_curve_fit.py 中,折现方式按如下规则确定:
- 浮端、固端均未提供外部折现曲线:两条腿都自折现(
self_discounting_float_leg = True、self_discounting_fixed_leg = True),内部将折扣率/时间占位为[0.]; - 仅提供了浮端折现曲线:固端复用浮端的折现曲线;
- 仅提供了固端折现曲线:浮端改为自折现。
五、完整可运行示例:由 4 笔 LIBOR 互换构建隐含互换曲线
以下示例完整继承自 API 文档(即 swap_curve_fit.py 中的 docstring 示例),利用 4 笔即期起息的浮动/固定 LIBOR 互换构建曲线,其中 LIBOR 期限跨度为 6M:
import numpy as np
import tf_quant_finance as tff
dtype = np.float64
# 4 笔即期起息互换,期限分别为 1Y、2Y、3Y、4Y;LIBOR 期限跨度为 6M。
float_leg_start_times = [
np.array([0., 0.5], dtype=dtype),
np.array([0., 0.5, 1., 1.5], dtype=dtype),
np.array([0., 0.5, 1.0, 1.5, 2.0, 2.5], dtype=dtype),
np.array([0., 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5], dtype=dtype)
]
float_leg_end_times = [
np.array([0.5, 1.0], dtype=dtype),
np.array([0.5, 1., 1.5, 2.0], dtype=dtype),
np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0], dtype=dtype),
np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], dtype=dtype)
]
# 半年付息的固定票息计息期。
fixed_leg_start_times = [
np.array([0., 0.5], dtype=dtype),
np.array([0., 0.5, 1., 1.5], dtype=dtype),
np.array([0., 0.5, 1.0, 1.5, 2.0, 2.5], dtype=dtype),
np.array([0., 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5], dtype=dtype)
]
fixed_leg_end_times = [
np.array([0.5, 1.0], dtype=dtype),
np.array([0.5, 1., 1.5, 2.0], dtype=dtype),
np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0], dtype=dtype),
np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], dtype=dtype)
]
# 简单的 daycount:浮端与固端每期均为 0.5。
float_leg_daycount = [
np.array([0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], dtype=dtype)
]
fixed_leg_daycount = [
np.array([0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5], dtype=dtype),
np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], dtype=dtype)
]
fixed_leg_cashflows = [
# 1 年期互换,2.855% 半年付息。
np.array([-0.02855, -0.02855], dtype=dtype),
# 2 年期互换,3.097% 半年付息。
np.array([-0.03097, -0.03097, -0.03097, -0.03097], dtype=dtype),
# 3 年期互换,3.1% 半年付息。
np.array([-0.031, -0.031, -0.031, -0.031, -0.031, -0.031], dtype=dtype),
# 4 年期互换,3.2% 半年付息。
np.array([-0.032, -0.032, -0.032, -0.032, -0.032, -0.032, -0.032,
-0.032], dtype=dtype)
]
# 上述 IRS 的现值(平价互换,PV 均为 0)。
pvs = np.array([0., 0., 0., 0.], dtype=dtype)
# 曲线初始状态。
initial_curve_rates = np.array([0.01, 0.01, 0.01, 0.01], dtype=dtype)
results = tff.rates.swap_curve_fit(
float_leg_start_times, float_leg_end_times,
float_leg_daycount, fixed_leg_start_times,
fixed_leg_end_times, fixed_leg_cashflows,
fixed_leg_daycount, pvs, dtype=dtype,
initial_curve_rates=initial_curve_rates)
六、返回值:SwapCurveBuilderResult
函数返回 SwapCurveBuilderResult 实例,其定义位于 swap_curve_common.py,包含以下属性:
| 属性 | 说明 |
|---|---|
times |
Rank 1 实数 Tensor,计算折扣率对应的时刻,取各互换的到期时间(浮端与固端末次支付时间的较大者,见 swap_curve_fit.py) |
rates |
与 times 同 dtype 的 Rank 1 Tensor,推断出的零利率(连续复利折扣率) |
discount_factors |
与 times 同 dtype 的 Rank 1 Tensor,推断出的折现因子(exp(-rates * times)) |
initial_rates |
与 times 同 dtype 的 Rank 1 Tensor,初始猜测利率 |
converged |
标量布尔 Tensor,是否收敛(相邻两次迭代折现因子最大绝对差低于 curve_tolerance) |
failed |
标量布尔 Tensor,是否失败(折扣率或折现因子出现 NaN 即视为失败) |
iterations |
标量 int32 Tensor,实际迭代次数 |
objective_value |
标量实数 Tensor,用拟合曲线计算的目标函数值 |
注意:上述 SwapCurveBuilderResult 的 rates 字段在文档中也被称为 discount_rates(原 API 文档 Returns 一节使用了 discount_rates 名称),两者指代同一内容——拟合得到的连续复利折扣率。
七、进阶用法(来自测试用例的实战验证)
7.1 使用独立折现曲线(OIS 双曲线)
当需要以独立折现曲线(如 OIS)折现现金流时,传入 float_leg_discount_rates / float_leg_discount_times(或同时传固端版本)。测试 test_OIS_discounting(swap_curve_test.py)展示了这一用法:
discount_rates = np.array([0.0, 0.0, 0.0, 0.0], dtype=dtype)
discount_times = np.array([1.0, 5.0, 10.0, 30.0], dtype=dtype)
results = tff.rates.swap_curve_fit(
float_leg_start_times, float_leg_end_times, float_leg_dc,
fixed_leg_start_times, fixed_leg_end_times, fixed_leg_cashflows,
fixed_leg_dc, pvs,
float_leg_discount_rates=discount_rates,
float_leg_discount_times=discount_times,
curve_tolerance=curve_tolerance,
dtype=dtype,
initial_curve_rates=initial_curve_rates)
在批量场景下(test_OIS_discounting_batch,swap_curve_test.py),discount_rates 可提供形状为 [batch, n] 的折扣率矩阵,initial_curve_rates 相应取形状 [batch, num_instruments],一次调用即可同时拟合多条曲线。
7.2 自定义插值器(constant forward)
默认线性插值之外的常见选择是 constant forward 插值。测试 test_interpolation_const_fwd(swap_curve_test.py)将 constant_fwd.interpolate 作为 curve_interpolator 传入:
def curve_interpolator(xi, x, y):
return tff.rates.constant_fwd.interpolate(xi, x, y, dtype=dtype)
results = tff.rates.swap_curve_fit(
..., curve_tolerance=1e-5, dtype=dtype,
curve_interpolator=curve_interpolator,
initial_curve_rates=initial_curve_rates)
constant forward 插值的含义是:区间 <a href="https://link.gitcode.com/i/ebcea8f05515ed53201a944f1e758895" target="_blank">t_{i-1}, t] 内的远期利率与 [t_{i-1}, t_i] 内的远期利率相同,数学上等价于对 t*y_t 做线性插值(见 [constant_fwd_interpolation.py)。测试结果显示,采用 constant forward 插值后拟合出的曲线与线性插值结果非常接近,但每个期限点的具体数值有细微差异(例如 2Y 处为 0.03076991 vs 0.03077457),这验证了 curve_interpolator 可插拔的设计。
7.3 结算时间与双向外部折现
测试 test_settlement_times(swap_curve_test.py)同时使用了:
present_values_settlement_times:如3./365.(3 个交易日),用于修正 PV 的交付时点;- 浮端与固端各自独立的外部折现曲线(如浮端 1% 折现、固端 2% 折现)。
这说明 swap_curve_fit 支持"浮端用一条曲线、固端用另一条曲线"的完全分离折现配置,且结算时间可批量作用于每笔互换。
7.4 自定义优化器
optimizer 接受任何符合 3.2 节接口的可调用对象。TFF 的 math.optimizer 模块还提供 bfgs_minimize、lbfgs_minimize、nelder_mead_minimize、differential_evolution_minimize 等优化器(见 optimizer/init.py),它们均返回包含 position、converged、failed、num_iterations、objective_value 的结果对象,可直接替换默认的共轭梯度。
八、异常处理与工程注意事项
8.1 必须提供初始曲线
函数签名中 initial_curve_rates 为位置参数,但源码明确要求其非空:在 swap_curve_fit.py 中,若 initial_curve_rates is None,会直接抛出:
ValueError: Initial state of the curve is not specified.
(源码中的 TODO(b/144600429) 表明"自动生成有意义的初始曲线"逻辑尚未实现,因此调用方必须自行给出合理的初始猜测,例如统一取 0.01。)
8.2 精度与容差建议
- 测试用例对
np.float32/np.float64双精度均做了验证(如 swap_curve_test.py),实际生产中建议使用np.float64以减小插值与优化误差; - 默认
curve_tolerance=1e-8、maximum_iterations=50在测试中通常一次收敛;若拟合未收敛(results.converged为False),可适当放宽curve_tolerance(如1e-5)或增大迭代上限。
8.3 关于收敛与失败标志
converged:相邻两次迭代中,各到期时点折现因子的最大绝对变化小于curve_tolerance时视为收敛;failed:优化过程中折扣率或折现因子出现 NaN 即视为失败(如 swap_curve_fit.py 的组装逻辑以及文档中对失败的定义)。调用后建议同时检查这两个标志再使用rates。
九、参考与延伸阅读
- 算法理论依据:Leif B.G. Andersen 与 Vladimir V. Piterbarg 的《Interest Rate Modeling, Volume I: Foundations and Vanilla Models》第 6 章(swap_curve_fit.py 顶部引用);
- 曲线构建辅助数据结构 SwapCurveBuilderResult;
- 同模块的逐点剥靴法 swap_curve_bootstrap,可与本文优化法互为校验;
- 默认线性插值实现 linear_interpolation.py 与 constant forward 插值 constant_fwd_interpolation.py;
- 完整测试套件 swap_curve_test.py,覆盖正确性、OIS 折现、批量输入、自定义插值、结算时间等场景,可作为上手模板。