Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions financepy/models/hw_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
16 changes: 14 additions & 2 deletions financepy/products/rates/ibor_cap_floor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)

Expand Down
24 changes: 19 additions & 5 deletions financepy/products/rates/ibor_swaption.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]

Expand All @@ -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.")

Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
112 changes: 112 additions & 0 deletions tests/unit/test_hw_option_curve_consistency.py
Original file line number Diff line number Diff line change
@@ -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
)