diff --git a/financepy/models/bachelier.py b/financepy/models/bachelier.py index 923235b0..16b6a385 100644 --- a/financepy/models/bachelier.py +++ b/financepy/models/bachelier.py @@ -55,7 +55,8 @@ def value( v = self.volatility root_t = np.sqrt(np.maximum(t, 0.0)) std = v * root_t - d = np.where(std > 0.0, (f - k) / std, 0.0) + # Use a safe denominator: np.where evaluates both branches. + d = (f - k) / np.where(std > 0.0, std, 1.0) if call_or_put == OptionTypes.EUROPEAN_CALL: values = df * ((f - k) * norm.cdf(d) + std * norm.pdf(d)) diff --git a/financepy/models/sabr_normal.py b/financepy/models/sabr_normal.py index a89d6d3a..7be9f407 100644 --- a/financepy/models/sabr_normal.py +++ b/financepy/models/sabr_normal.py @@ -3,7 +3,9 @@ import numpy as np from scipy.optimize import least_squares +from .bachelier import Bachelier from ..utils.error import FinError +from ..utils.global_types import OptionTypes def normal_sabr_vol(forward, strike, expiry, alpha, rho, nu): @@ -42,6 +44,27 @@ def normal_vol(self, forward: float, strike: float, expiry: float) -> float: forward, strike, expiry, self.alpha, self.rho, self.nu ) + def value( + self, + forward: float, + strike: float, + expiry: float, + df: float, + call_or_put: OptionTypes, + ) -> float: + """Price a scalar European call or put using the SABR normal vol. + + Rates may be negative. Expiry is in years, and df discounts the + payoff. This uses the implied-volatility approximation, not an exact + numerical solution of the SABR model. + """ + vol = self.normal_vol(forward, strike, expiry) + if not np.isfinite(vol) or vol <= 0.0: + raise FinError("Normal SABR approximation must give a positive volatility.") + if not np.isfinite(df): + raise FinError("Discount factor must be finite.") + return float(Bachelier(vol).value(forward, strike, expiry, df, call_or_put)) + @classmethod def calibrate(cls, forward, strikes, normal_vols, expiry, initial_guess=None): diff --git a/financepy/products/rates/ibor_cap_floor.py b/financepy/products/rates/ibor_cap_floor.py index ad7feb44..0428e06a 100644 --- a/financepy/products/rates/ibor_cap_floor.py +++ b/financepy/products/rates/ibor_cap_floor.py @@ -28,6 +28,7 @@ from ...models.black_shifted import BlackShifted from ...models.bachelier import Bachelier from ...models.sabr import SABR +from ...models.sabr_normal import NormalSABR from ...models.sabr_shifted import SABRShifted from ...models.hw_tree import HWTree from ...utils.global_types import CapFloorTypes, OptionTypes @@ -131,14 +132,15 @@ def _generate_dts(self): def value(self, value_dt: Date, libor_curve: DiscountCurve, model: Model): """Value the cap or floor using the chosen model which specifies - the volatility of the Ibor rate to the cap start date.""" + the volatility of the Ibor rate to the cap start date. Bachelier and + NormalSABR permit negative strikes.""" check_curve_dt(value_dt, libor_curve) num_options = len(self.caplet_floorlet_dates) strike_rate = self.strike_rate - if strike_rate < 0.0: + if strike_rate < 0.0 and not isinstance(model, (Bachelier, NormalSABR)): raise FinError("Strike < 0.0") if num_options <= 1: @@ -237,7 +239,7 @@ def value_caplet_floor_let(self, value_dt: Date, caplet_start_dt: Date, caplet_e k = self.strike_rate df = libor_curve.df(caplet_end_dt) - if k == 0.0: + if k == 0.0 and not isinstance(model, (Bachelier, NormalSABR)): k = 1e-10 caplet_floorlet_value = 0.0 @@ -256,7 +258,7 @@ def value_caplet_floor_let(self, value_dt: Date, caplet_start_dt: Date, caplet_e elif self.opt_type == CapFloorTypes.FLOOR: caplet_floorlet_value = model.value(fwd, k, t_exp, df, OptionTypes.EUROPEAN_PUT) - elif isinstance(model, Bachelier): + elif isinstance(model, (Bachelier, NormalSABR)): if self.opt_type == CapFloorTypes.CAP: caplet_floorlet_value = model.value(fwd, k, t_exp, df, OptionTypes.EUROPEAN_CALL) diff --git a/financepy/products/rates/ibor_swaption.py b/financepy/products/rates/ibor_swaption.py index 850e9ced..2cab0efa 100644 --- a/financepy/products/rates/ibor_swaption.py +++ b/financepy/products/rates/ibor_swaption.py @@ -26,9 +26,11 @@ from ...products.rates.ibor_swap import IborSwap +from ...models.bachelier import Bachelier from ...models.black import Black from ...models.black_shifted import BlackShifted from ...models.sabr import SABR +from ...models.sabr_normal import NormalSABR from ...models.sabr_shifted import SABRShifted from ...models.hw_tree import HWTree from ...models.bk_tree import BKTree @@ -110,10 +112,9 @@ def value(self, value_dt: Date, discount_curve: DiscountCurve, model: Model): """Valuation of a Ibor European-style swaption using a choice of - models on a specified valuation date. Models include FinModelBlack, - FinModelBlackShifted, SABR, SABRShifted, FinModelHW, - FinModelBK and FinModelBDT. The last two involved a tree-based - valuation.""" + models on a specified valuation date. Models include Black, BlackShifted, + Bachelier, SABR, SABRShifted, NormalSABR, HWTree, BKTree and BDTTree. + Bachelier and NormalSABR permit negative forwards and strikes.""" float_spread = 0.0 @@ -205,7 +206,7 @@ def value(self, value_dt: Date, elif self.fixed_leg_type == SwapTypes.RECEIVE: swaption_price = model.value(s, k, t_exp, df, OptionTypes.EUROPEAN_PUT) - elif isinstance(model, SABR): + elif isinstance(model, (SABR, Bachelier, NormalSABR)): if self.fixed_leg_type == SwapTypes.PAY: swaption_price = model.value(s, k, t_exp, df, OptionTypes.EUROPEAN_CALL) diff --git a/tests/unit/test_normal_rate_option_valuation.py b/tests/unit/test_normal_rate_option_valuation.py new file mode 100644 index 00000000..dbc40a1a --- /dev/null +++ b/tests/unit/test_normal_rate_option_valuation.py @@ -0,0 +1,160 @@ +"""Independent Gaussian payoff and cash-flow references for normal rate options.""" + +from math import exp, pi, sqrt + +import numpy as np +import pytest +from scipy.integrate import quad + +from financepy.market.curves.flat_discount_curve import FlatDiscountCurve +from financepy.models.bachelier import Bachelier +from financepy.models.black import Black +from financepy.models.sabr_normal import NormalSABR +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.error import FinError +from financepy.utils.frequency import FrequencyTypes +from financepy.utils.global_types import CapFloorTypes, OptionTypes, SwapTypes + + +VALUE_DT = Date(1, 1, 2025) +RATE = -0.01 +NOTIONAL = 1_000_000.0 +ALPHA, RHO, NU = 0.012, -0.40, 0.70 + + +def _years(dt): + return (dt - VALUE_DT) / 365.0 + + +def _discount(dt): + return exp(-RATE * _years(dt)) + + +def _normal_sabr_std(forward, strike, expiry, nu): + # Evaluate x(z)/z as an integral, not with the implementation's asinh + # difference or small-z Taylor series. + z = nu * (forward - strike) / ALPHA + average, _ = quad( + lambda u: 1.0 / sqrt(1.0 - 2.0 * RHO * z * u + (z * u) ** 2), 0.0, 1.0 + ) + correction = 1.0 + (2.0 - 3.0 * RHO**2) * nu**2 * expiry / 24.0 + return ALPHA * correction / average * sqrt(expiry) + + +def _normal_payoff(forward, strike, std, sign): + # Integrate the payoff directly in its exercise region, using symmetry + # for puts. No calls to the library pricing implementation or CDF. + intrinsic = sign * (forward - strike) + if std == 0.0: + return max(intrinsic, 0.0) + value, _ = quad( + lambda x: (intrinsic + std * x) * exp(-x * x / 2.0) / sqrt(2.0 * pi), + -intrinsic / std, + np.inf, + epsabs=1e-14, + ) + return value + + +@pytest.mark.parametrize("nu", [0.0, NU]) +@pytest.mark.parametrize( + "forward, strike, expiry", + [(-0.02, -0.01, 2.0), (-0.01, -0.01, 1.5), (-0.02, 0.01, 0.5), + (0.04, 0.035, 3.0), (-0.01, -0.012, 0.0)], +) +def test_normal_sabr_value_matches_gaussian_payoff(nu, forward, strike, expiry): + model = NormalSABR(ALPHA, RHO, nu) + std = _normal_sabr_std(forward, strike, expiry, nu) + df = 0.94 + for sign, option in [(1, OptionTypes.EUROPEAN_CALL), (-1, OptionTypes.EUROPEAN_PUT)]: + expected = df * _normal_payoff(forward, strike, std, sign) + assert model.value(forward, strike, expiry, df, option) == pytest.approx( + expected, abs=2e-14 + ) + + +def test_normal_sabr_rejects_negative_approximation(): + model = NormalSABR(ALPHA, 0.99, 3.0) + with pytest.raises(FinError, match="positive volatility"): + model.value(-0.01, -0.01, 5.0, 1.0, OptionTypes.EUROPEAN_CALL) + + +@pytest.mark.filterwarnings("error") +def test_bachelier_broadcasts_at_zero_expiry_without_warning(): + forward = np.array([[-0.02], [-0.01]]) + strike = -0.015 + expiry = np.array([0.0, 1.5]) + val = Bachelier(ALPHA).value(forward, strike, expiry, 0.97, OptionTypes.EUROPEAN_PUT) + expected = [ + [0.97 * _normal_payoff(f, strike, ALPHA * sqrt(t), -1) for t in expiry] + for f in forward[:, 0] + ] + np.testing.assert_allclose(val, expected, atol=2e-14, rtol=0.0) + + +@pytest.mark.parametrize("expiry", [VALUE_DT, Date(1, 1, 2027)]) +@pytest.mark.parametrize("sabr", [False, True]) +def test_physical_swaption_matches_cashflows_and_gaussian_payoff(expiry, sabr): + model = NormalSABR(ALPHA, RHO, NU) if sabr else Bachelier(ALPHA) + curve = FlatDiscountCurve(VALUE_DT, RATE) + settlement = VALUE_DT if expiry == VALUE_DT else Date(1, 2, 2025) + strike = -0.012 + dates = [Date(1, 1, expiry.y + i) for i in range(4)] + annuity = sum((d1 - d0) / 365.0 * _discount(d1) for d0, d1 in zip(dates, dates[1:])) + forward = (_discount(expiry) - _discount(dates[-1])) / annuity + assert forward < 0.0 + std = _normal_sabr_std(forward, strike, _years(expiry), NU if sabr else 0.0) + payer_receiver = [] + for sign, side in [(1, SwapTypes.PAY), (-1, SwapTypes.RECEIVE)]: + swaption = IborSwaption( + settlement, expiry, dates[-1], side, strike, FrequencyTypes.ANNUAL, + DayCountTypes.ACT_365F, notional=NOTIONAL, cal_type=CalendarTypes.NONE, + ) + value = swaption.value(VALUE_DT, curve, model) + multiplier = NOTIONAL * annuity / _discount(settlement) + # FlatDiscountCurve floors the anchor time at G_SMALL; allow its + # roughly 1e-8 cash impact on this notional. + assert value == pytest.approx( + multiplier * _normal_payoff(forward, strike, std, sign), abs=1e-7 + ) + payer_receiver.append(value) + assert payer_receiver[0] - payer_receiver[1] == pytest.approx( + NOTIONAL * (_discount(expiry) - _discount(dates[-1]) - strike * annuity) + / _discount(settlement), abs=1e-7 + ) + + +@pytest.mark.parametrize("strike", [-0.012, 0.0]) +@pytest.mark.parametrize("sabr", [False, True]) +def test_forward_cap_floor_matches_sum_of_caplet_payoffs(strike, sabr): + model = NormalSABR(ALPHA, RHO, NU) if sabr else Bachelier(ALPHA) + curve = FlatDiscountCurve(VALUE_DT, RATE) + dates = [Date(1, 1, 2026), Date(1, 4, 2026), Date(1, 7, 2026)] + for sign, side in [(1, CapFloorTypes.CAP), (-1, CapFloorTypes.FLOOR)]: + cap_floor = IborCapFloor( + dates[0], dates[-1], side, strike, accrual_dc_type=DayCountTypes.ACT_365F, + notional=NOTIONAL, cal_type=CalendarTypes.NONE, + ) + expected_legs = [] + for start, end in zip(dates, dates[1:]): + accrual = (end - start) / 365.0 + forward = (_discount(start) / _discount(end) - 1.0) / accrual + std = _normal_sabr_std(forward, strike, _years(start), NU if sabr else 0.0) + expected_legs.append( + _discount(end) * accrual * NOTIONAL * _normal_payoff(forward, strike, std, sign) + ) + total = cap_floor.value(VALUE_DT, curve, model) + assert total == pytest.approx(sum(expected_legs), abs=1e-8) + np.testing.assert_allclose( + cap_floor.caplet_floorlet_values[1:], expected_legs, atol=1e-8, rtol=0.0 + ) + + +def test_black_cap_floor_still_rejects_negative_strike(): + cap = IborCapFloor(Date(1, 1, 2026), Date(1, 7, 2026), CapFloorTypes.CAP, -0.01) + with pytest.raises(FinError, match="Strike < 0.0"): + cap.value(VALUE_DT, FlatDiscountCurve(VALUE_DT, RATE), Black(0.2))