From fcd95eee48175f5682f56c73f1726342c0859c7c Mon Sep 17 00:00:00 2001 From: Kiril1Shevtsov Date: Sat, 21 Nov 2026 00:30:09 -0500 Subject: [PATCH] Use supplied curve discounts and stabilize the Ho-Lee limit in analytic Hull-White rate options --- financepy/models/hw_tree.py | 11 +- financepy/products/rates/ibor_cap_floor.py | 16 ++- financepy/products/rates/ibor_swaption.py | 24 +++- .../unit/test_hw_option_curve_consistency.py | 112 ++++++++++++++++++ 4 files changed, 151 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_hw_option_curve_consistency.py diff --git a/financepy/models/hw_tree.py b/financepy/models/hw_tree.py index 1cfc657c..f2645031 100644 --- a/financepy/models/hw_tree.py +++ b/financepy/models/hw_tree.py @@ -67,13 +67,14 @@ def p_fast(t, t_mat, r_t, delta, pt, ptd, p_mat, _sigma, _a): if abs(_a) < SMALL: _a = SMALL - bt_t = (1.0 - np.exp(-_a * (t_mat - t))) / _a - bt_delta = (1.0 - np.exp(-_a * delta)) / _a + # Keep the Ho-Lee limit accurate even for tiny a * delta. + bt_t = -np.expm1(-_a * (t_mat - t)) / _a + bt_delta = -np.expm1(-_a * delta) / _a term1 = np.log(p_mat / pt) - (bt_t / bt_delta) * np.log(ptd / pt) term2 = ( - (_sigma**2) * (1 - np.exp(-2 * _a * t)) * bt_t * (bt_t - bt_delta) / (4 * _a) + (_sigma**2) * (-np.expm1(-2 * _a * t)) * bt_t * (bt_t - bt_delta) / (4 * _a) ) log_ahat = term1 - term2 @@ -975,8 +976,8 @@ def option_on_zcb( if abs(a) < SMALL: a = SMALL - sigmap = (sigma / a) * (1.0 - np.exp(-a * (t_mat - t_exp))) - sigmap = sigmap * np.sqrt((1.0 - np.exp(-2.0 * a * t_exp)) / 2.0 / a) + sigmap = -(sigma / a) * np.expm1(-a * (t_mat - t_exp)) + sigmap = sigmap * np.sqrt(-np.expm1(-2.0 * a * t_exp) / (2.0 * a)) if abs(sigmap) < SMALL: sigmap = SMALL diff --git a/financepy/products/rates/ibor_cap_floor.py b/financepy/products/rates/ibor_cap_floor.py index ad7feb44..941084c7 100644 --- a/financepy/products/rates/ibor_cap_floor.py +++ b/financepy/products/rates/ibor_cap_floor.py @@ -11,6 +11,8 @@ from enum import Enum +import numpy as np + from ...utils.date import Date from ...utils.calendar import Calendar from ...utils.calendar import CalendarTypes @@ -33,6 +35,7 @@ from ...utils.global_types import CapFloorTypes, OptionTypes from ...utils.check_values import check_curve_dt from ...market.curves.discount_curve import DiscountCurve +from ...market.curves.interpolator import InterpTypes from ...models.model import Model from ...utils.valuation_log import log_value, log_table, log_row @@ -287,8 +290,17 @@ def value_caplet_floor_let(self, value_dt: Date, caplet_start_dt: Date, caplet_e notional_adj = 1.0 + self.strike_rate * alpha face_amount = 1.0 - df_times = libor_curve._times - df_values = libor_curve._dfs + if getattr(libor_curve, "_interp_type", None) == InterpTypes.FLAT_FWD_RATES: + df_times, df_values = libor_curve._times, libor_curve._dfs + else: + # The ZCB pricer interpolates flat-forward; make both + # required discounts from the supplied curve knots. + if t_exp > 0.0: + df_times = np.array([0.0, t_exp, t_mat]) + df_values = np.array([1.0, libor_curve.df(caplet_start_dt), df]) + else: + df_times = np.array([0.0, t_mat]) + df_values = np.array([1.0, df]) v = model.option_on_zcb(t_exp, t_mat, strike_price, face_amount, df_times, df_values) diff --git a/financepy/products/rates/ibor_swaption.py b/financepy/products/rates/ibor_swaption.py index 850e9ced..8ee92dba 100644 --- a/financepy/products/rates/ibor_swaption.py +++ b/financepy/products/rates/ibor_swaption.py @@ -23,6 +23,7 @@ from ...utils.helpers import label_to_string, check_argument_types from ...utils.date import Date from ...market.curves.discount_curve import DiscountCurve +from ...market.curves.interpolator import InterpTypes from ...products.rates.ibor_swap import IborSwap @@ -158,6 +159,7 @@ def value(self, value_dt: Date, # For the tree models we need to generate a vector of the cpns ####################################################################### + cpn_dates = [self.exercise_dt] cpn_times = [t_exp] cpn_flows = [0.0] @@ -173,15 +175,13 @@ def value(self, value_dt: Date, if flow_dt > self.exercise_dt: cpn_time = (flow_dt - value_dt) / G_DAYS_IN_YEAR cpn_flow = swap.fixed_leg.payments[i_flow] / self.notional + cpn_dates.append(flow_dt) cpn_times.append(cpn_time) cpn_flows.append(cpn_flow) cpn_times = np.array(cpn_times) cpn_flows = np.array(cpn_flows) - df_times = discount_curve._times - df_values = discount_curve._dfs - if np.any(cpn_times < 0.0): raise FinError("No cpn times can be before the value date.") @@ -221,6 +221,20 @@ def value(self, value_dt: Date, elif isinstance(model, HWTree): + if ( + getattr(discount_curve, "_interp_type", None) == InterpTypes.FLAT_FWD_RATES + and discount_curve.curve_dc_type == DayCountTypes.ACT_365F + ): + df_times, df_values = discount_curve._times, discount_curve._dfs + else: + # The analytic HW routine interpolates flat-forward. Make + # the supplied curve's actual exercise and coupon DFs knots + # in the model's ACT/365F clock. + df_times, df_dates = cpn_times, cpn_dates + if t_exp > 0.0: + df_times = np.r_[0.0, cpn_times] + df_dates = [value_dt, *cpn_dates] + df_values = discount_curve.df(df_dates) swaption_px = model.european_bond_option_jamshidian( t_exp, strike_price, @@ -243,7 +257,7 @@ def value(self, value_dt: Date, elif isinstance(model, BKTree): - model.build_tree(t_mat, df_times, df_values) + model.build_tree(t_mat, discount_curve._times, discount_curve._dfs) swaption_px = model.bermudan_swaption( t_exp, t_mat, @@ -263,7 +277,7 @@ def value(self, value_dt: Date, elif isinstance(model, BDTTree): - model.build_tree(t_mat, df_times, df_values) + model.build_tree(t_mat, discount_curve._times, discount_curve._dfs) swaption_px = model.bermudan_swaption( t_exp, t_mat, diff --git a/tests/unit/test_hw_option_curve_consistency.py b/tests/unit/test_hw_option_curve_consistency.py new file mode 100644 index 00000000..eaf8a75d --- /dev/null +++ b/tests/unit/test_hw_option_curve_consistency.py @@ -0,0 +1,112 @@ +"""Hull-White rate option PVs must use the supplied curve at cash-flow dates.""" + +from math import exp, expm1, pi, sqrt + +import numpy as np +import pytest +from scipy.integrate import quad +from scipy.optimize import brentq + +from financepy.market.curves.discount_curve import DiscountCurve +from financepy.market.curves.interpolator import InterpTypes +from financepy.models.hw_tree import HWTree +from financepy.products.rates.ibor_cap_floor import IborCapFloor +from financepy.products.rates.ibor_swaption import IborSwaption +from financepy.utils.calendar import CalendarTypes +from financepy.utils.date import Date +from financepy.utils.day_count import DayCountTypes +from financepy.utils.frequency import FrequencyTypes +from financepy.utils.global_types import CapFloorTypes, SwapTypes + + +VALUE_DT = Date(1, 1, 2025) +EXERCISE_DT = Date(1, 7, 2027) +NOTIONAL = 1_000_000.0 +A = 0.07 +CURVE_TYPES = [ + InterpTypes.LINEAR_ZERO_RATES, + InterpTypes.MONOTONE_CONVEX, + InterpTypes.FLAT_FWD_RATES, +] + + +def _time(date): + return (date - VALUE_DT) / 365.0 + + +def _curve(interp_type): + knots = [VALUE_DT, Date(1, 1, 2026), Date(1, 1, 2029), Date(1, 1, 2033)] + times = np.array([_time(date) for date in knots]) + dfs = np.exp(-0.01 * times - 0.004 * times**2) + return DiscountCurve(VALUE_DT, knots, dfs, interp_type) + + +def _expiry_measure_payoffs(curve, expiry_dt, flow_dates, amounts, strike, sigma, a=A): + # Under the expiry forward measure, every P(T,U) is a lognormal + # multiple of the same N(0,1), and E[P(T,U)]=P(0,U)/P(0,T). + expiry_t = _time(expiry_dt) + expiry_df = curve.df(expiry_dt) + std_x = sigma * sqrt(-expm1(-2 * a * expiry_t) / (2 * a) if a else expiry_t) + dfs = np.array([curve.df(d) / expiry_df for d in flow_dates]) + dt = np.array([_time(d) - expiry_t for d in flow_dates]) + std = (-np.expm1(-a * dt) / a if a else dt) * std_x + weights = np.asarray(amounts) * dfs * np.exp(-0.5 * std**2) + + def payoff(z): + return np.dot(weights, np.exp(-std * z)) - strike + + if std_x == 0.0: + deterministic = payoff(0.0) + return expiry_df * max(deterministic, 0.0), expiry_df * max(-deterministic, 0.0) + + # Integrate max(payoff, 0) directly, not a sum of ZCB Black prices. + lo, hi = -12.0, 12.0 + root = brentq(payoff, lo, hi) + + def integrand(z): + return payoff(z) * exp(-z * z / 2.0) / sqrt(2.0 * pi) + + positive = quad(integrand, lo, root, epsabs=1e-13)[0] + negative = -quad(integrand, root, hi, epsabs=1e-13)[0] + return expiry_df * positive, expiry_df * negative + + +@pytest.mark.parametrize("interp_type", CURVE_TYPES) +@pytest.mark.parametrize("a", [A, 1e-11, 0.0]) +@pytest.mark.parametrize("sigma", [0.0, 0.018]) +def test_hw_swaption_respects_off_knot_discounts(interp_type, sigma, a): + curve = _curve(interp_type) + model = HWTree(sigma, a) + dates = [Date(1, 7, 2027 + i) for i in range(4)] + rate = 0.04 + amounts = np.array([rate * (d1 - d0) / 365.0 for d0, d1 in zip(dates, dates[1:])]) + amounts[-1] += 1.0 + call, put = _expiry_measure_payoffs(curve, dates[0], dates[1:], amounts, 1.0, sigma, a) + for side, expected in [(SwapTypes.RECEIVE, call), (SwapTypes.PAY, put)]: + product = IborSwaption( + VALUE_DT, dates[0], dates[-1], side, rate, FrequencyTypes.ANNUAL, + DayCountTypes.ACT_365F, notional=NOTIONAL, cal_type=CalendarTypes.NONE, + ) + assert product.value(VALUE_DT, curve, model) == pytest.approx( + NOTIONAL * expected, abs=1.0 + ) + + +@pytest.mark.parametrize("interp_type", CURVE_TYPES) +@pytest.mark.parametrize("a", [A, 1e-11, 0.0]) +@pytest.mark.parametrize("sigma", [0.0, 0.018]) +def test_hw_caplet_respects_off_knot_discounts(interp_type, sigma, a): + curve = _curve(interp_type) + model = HWTree(sigma, a) + start, end = EXERCISE_DT, Date(1, 10, 2027) + rate = 0.033 + scale = 1.0 + rate * (end - start) / 365.0 + call, put = _expiry_measure_payoffs(curve, start, [end], [1.0], 1.0 / scale, sigma, a) + for side, expected in [(CapFloorTypes.CAP, put), (CapFloorTypes.FLOOR, call)]: + cap_floor = IborCapFloor( + start, end, side, rate, accrual_dc_type=DayCountTypes.ACT_365F, + notional=NOTIONAL, cal_type=CalendarTypes.NONE, + ) + assert cap_floor.value(VALUE_DT, curve, model) == pytest.approx( + NOTIONAL * scale * expected, abs=0.15 + )