Skip to content

Deprecate fitting-method constructors taking constrainAtZero - #3086

Merged
lballabio merged 7 commits into
lballabio:masterfrom
Allan-dq:reject-unconstrained-fit
Dec 1, 2026
Merged

lballabio merged 7 commits into
lballabio:masterfrom
Allan-dq:reject-unconstrained-fit

Conversation

@Allan-dq

Copy link
Copy Markdown
Contributor

With constrainAtZero = false, fitting a FittedBondDiscountCurve can't give a usable curve. Bond prices only depend on ratios of discount factors (the NPV is divided by the discount at settlement), so the level of an unconstrained discount function is not determined by the fit. What happens today, on every release I tried from 1.28 to 1.44:

  • without a guess, the fit starts from all-zero parameters, i.e., a null discount function; the cost is NaN at the starting point, the optimizer never moves, and the curve returns a discount factor of 0 everywhere with no error;
  • with a guess, the fit converges to the same cost as the constrained one, but the level is arbitrary. For ten annual bonds priced off a flat 3% curve, SimplePolynomialFitting(3, false) with guess (1, 0, 0, 0) gives d(0) = 3.4875 and a 5-year zero rate of -22%, while d(5)/d(0) = 0.8607 is correct.

This PR makes the fit raise an error in that case and says why in the class docs. Building a curve from given parameters with constrainAtZero = false is not affected (the fixed-kappa test added in #3056 does that and still passes).

I went for an error because, once the level is normalized, an unconstrained fit spans the same curves as the constrained one, so nothing is lost by requiring the constraint. If you'd rather keep unconstrained fits working, the alternative is to divide the fitted discount function by its value at t = 0 and to start from a non-null curve; I can change the PR to do that.

A short Python script that reproduces the numbers above:

"""constrainAtZero=False in FittedBondDiscountCurve: what a fit returns (QuantLib Python).

Ten annual 3% bonds priced off a flat 3% continuous curve, so the right answer is
d(t) = exp(-0.03 t). Run with any released QuantLib (same output on 1.28 through 1.44).
"""
import math
import QuantLib as ql

today = ql.Date(16, 9, 2015)
ql.Settings.instance().evaluationDate = today
dc = ql.Actual365Fixed()
flat = ql.FlatForward(today, 0.03, dc, ql.Continuous)
engine = ql.DiscountingBondEngine(ql.YieldTermStructureHandle(flat))


def helpers(settlement_days):
    result = []
    for years in range(1, 11):
        schedule = ql.Schedule(today, today + ql.Period(years, ql.Years), ql.Period(ql.Annual),
                               ql.NullCalendar(), ql.Unadjusted, ql.Unadjusted,
                               ql.DateGeneration.Backward, False)
        bond = ql.FixedRateBond(settlement_days, 100.0, schedule, [0.03], dc)
        bond.setPricingEngine(engine)
        result.append(ql.BondHelper(ql.QuoteHandle(ql.SimpleQuote(bond.cleanPrice())), bond))
    return result


def report(label, method, guess, settlement_days=0):
    curve = ql.FittedBondDiscountCurve(today, helpers(settlement_days), dc, method, 1e-10, 10000, guess)
    d0, d5 = curve.discount(0.0), curve.discount(5.0)
    ratio = d5 / d0 if d0 else float("nan")
    print(f"{label:46s} cost {curve.fitResults().minimumCostValue():9.3g}  d(0) {d0:8.4f}  "
          f"d(5) {d5:8.4f}  d(5)/d(0) {ratio:.4f}  5y zero rate {curve.zeroRate(5.0, ql.Continuous).rate():8.4f}")


print(f"QuantLib {ql.__version__}; exact: d(5) = {math.exp(-0.15):.4f}, 5y zero rate = 0.0300")
report("polynomial, constrained, no guess", ql.SimplePolynomialFitting(3, True), ql.Array())
report("polynomial, unconstrained, no guess", ql.SimplePolynomialFitting(3, False), ql.Array())
report("polynomial, unconstrained, guess (1,0,0,0)", ql.SimplePolynomialFitting(3, False), ql.Array([1.0, 0, 0, 0]))
report("polynomial, unconstrained, guess (2,0,0,0)", ql.SimplePolynomialFitting(3, False), ql.Array([2.0, 0, 0, 0]))
report("polynomial, unconstrained, guess, T+2 settle", ql.SimplePolynomialFitting(3, False), ql.Array([1.0, 0, 0, 0]), 2)

I used an AI assistant while preparing this and have reviewed and run all of it myself.

@lballabio

Copy link
Copy Markdown
Owner

I agree that the curve should be constrained at 1 for t=0, but people might still be getting decent unconstrained curves by passing a L2 term or an additional constraint that makes them well behaved. Instead of starting to reject them via the QL_REQUIRE, I would add constructors that don't take the constrainAtZero parameter and set it to true, and deprecate the existing constructors that take it. This might also give us the opportunity to prune the several convenience constructors we defined in the past.

@Allan-dq Allan-dq changed the title Reject fitting a bond curve without the constraint at zero Deprecate fitting-method constructors taking constrainAtZero Nov 21, 2026
@Allan-dq

Copy link
Copy Markdown
Contributor Author

Thanks, that makes sense. I checked the L2 case and you're right: with an L2 term and a guess that has d(0) = 1, the unconstrained polynomial fit from my example gives d(0) = 0.9991 and a 5-year zero rate of 3.02%, so the check would have broken curves that work.

I reworked the PR as you suggested and renamed it:

  • ExponentialSplinesFitting, CubicBSplinesFitting and SimplePolynomialFitting each get a constructor without constrainAtZero;
  • the seven existing constructors that take it are deprecated. The flag no longer has a default value in them, otherwise calls like SimplePolynomialFitting(3) would be ambiguous; those calls now use the new constructors, and only calls that pass the flag get the warning;
  • as for pruning, I didn't add new versions of the overloads without the optimization method. I kept one shortcut, ExponentialSplinesFitting(numCoeffs, fixedKappa, weights, constraint), because the example and the tests use it; I can drop it if you prefer;
  • the QL_REQUIRE and its test are gone. The example and the tests use the new constructors, and a new test checks that they give d(0) = 1 and the same discount factors as the deprecated ones with constrainAtZero = true.

I left the FittingMethod base-class constructor and the constrainAtZero() inspector as they are. The SWIG interface still passes the flag; I can follow up there once this is settled.

I also merged master into the branch.

@lballabio

Copy link
Copy Markdown
Owner

Thanks. I would do the same with the FittingMethod base-class constructor, to avoid a double deprecation cycle.

@Allan-dq

Copy link
Copy Markdown
Contributor Author

Done: FittingMethod now has a constructor without constrainAtZero, and the one taking it is deprecated.

The fitting methods that always passed true use the new constructor. SpreadFittingMethod is the one place in the library that still calls the deprecated one: it copies the flag from the method it wraps, which can still be unconstrained while the deprecated constructors exist. I left the constrainAtZero() inspector and the data member in place for the same reason.

@lballabio

Copy link
Copy Markdown
Owner

Thanks. I also deprecated the data member and the inspector, let's see what the CI builds say (different compilers might issue warnings in different places, unfortunately).

@coveralls

coveralls commented Dec 1, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.759% (+0.3%) from 80.458% — Allan-dq:reject-unconstrained-fit into lballabio:master

@lballabio
lballabio merged commit ae271bd into lballabio:master Dec 1, 2026
51 of 52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants