Skip to content
All library documents

Building Yield Curves with QuantLib Interpolation Methods

Article Quant Q&A · Author: InnocentR

Summary

The answer shows how to construct a government-bond yield curve in QuantLib Python using bond helpers and several piecewise interpolation choices. It prepares Portuguese government bond data with maturities, coupons, and prices, sets a valuation date and conventions, creates fixed-rate bond helpers, and uses them as input to curve constructors. The example then obtains zero rates at each bond maturity for each curve method.

The methods illustrated include log-linear and cubic interpolation of discount factors, linear and cubic zero-rate curves, linear forward rates, and spline-cubic discount factors. The answer also points to fitted discount curves as an alternative, naming cubic B-splines, polynomial, Nelson-Siegel, Svensson, and exponential-spline fitting approaches. This is an implementation example rather than a comparison of model quality: it does not report which interpolation performs best, discuss stability between sparse maturities, or assess out-of-sample pricing. Results depend on the supplied bond quotes, schedules, day-count basis, and conventions.

Key ideas

  • QuantLib Python offers piecewise yield-curve constructors with different interpolation variables and schemes.
  • Fixed-rate bond helpers can turn bond prices and contractual details into curve calibration instruments.
  • Zero rates can be queried from each constructed curve at selected dates and compared.
  • Fitted discount curves provide a separate approach using parametric or spline-based fitting methods.
  • The example demonstrates setup and usage but does not evaluate the methods’ relative accuracy or stability.

Tags

Full text
# Quantlib Natural Cubic spline yield curve


# Quantlib Natural Cubic spline yield curve












Is there an example to use Natural Cubic spline interpolation for yield curves in Quantlib python? I can see from the SWIG file that the interpolation is exposed but not sure how to use it.

I can see that some interpolation methods exposed in piecewiseyieldcurve file. Are the ones that I should be using?

## Answer by David Duarte (score 1, accepted)

https://quant.stackexchange.com/a/50387

QuantLib has several interpolation methods for yield curves. Here is an example of a few methods for Portuguese Government Bonds to get you started.

```
import QuantLib as ql
import pandas as pd

pgbs = pd.DataFrame(
    {'maturity': ['15-06-2020', '15-04-2021', '17-10-2022', '25-10-2023',
                  '15-02-2024', '15-10-2025', '21-07-2026', '14-04-2027',
                  '17-10-2028', '15-06-2029', '15-02-2030', '18-04-2034',
                  '15-04-2037', '15-02-2045'],
     'coupon': [4.8, 3.85, 2.2, 4.95,  5.65, 2.875, 2.875, 4.125,
                2.125, 1.95, 3.875, 2.25, 4.1, 4.1],
     'px': [102.532, 105.839, 107.247, 119.824, 124.005, 116.215, 117.708,
            128.027, 115.301, 114.261, 133.621, 119.879, 149.427, 159.177]})

calendar = ql.TARGET()
today = calendar.adjust(ql.Date(19, 12, 2019))
ql.Settings.instance().evaluationDate = today

bondSettlementDays = 2
bondSettlementDate = calendar.advance(
    today,
    ql.Period(bondSettlementDays, ql.Days))
frequency = ql.Annual
dc = ql.ActualActual(ql.ActualActual.ISMA)
accrualConvention = ql.ModifiedFollowing
convention = ql.ModifiedFollowing
redemption = 100.0

instruments = []
for idx, row in pgbs.iterrows():
    maturity = ql.Date(row.maturity, '%d-%m-%Y')
    schedule = ql.Schedule(
        bondSettlementDate,
        maturity,
        ql.Period(frequency),
        calendar,
        accrualConvention,
        accrualConvention,
        ql.DateGeneration.Backward,
        False)
    helper = ql.FixedRateBondHelper(
            ql.QuoteHandle(ql.SimpleQuote(row.px)),
            bondSettlementDays,
            100.0,
            schedule,
            [row.coupon / 100],
            dc,
            convention,
            redemption)

    instruments.append(helper)

params = [bondSettlementDate, instruments, dc]

methods = {
    'logLinearDiscount': ql.PiecewiseLogLinearDiscount(*params),
    'logCubicDiscount': ql.PiecewiseLogCubicDiscount(*params),
    'linearZero': ql.PiecewiseLinearZero(*params),
    'cubicZero': ql.PiecewiseCubicZero(*params),
    'linearForward': ql.PiecewiseLinearForward(*params),
    'splineCubicDiscount': ql.PiecewiseSplineCubicDiscount(*params),
}

pgbs.index = pd.to_datetime(pgbs.maturity)
for method in methods:
    pgbs[method] = pgbs.maturity.apply(
        lambda x: methods[method].zeroRate(
                                         ql.Date(x, '%d-%m-%Y'),
                                         dc,
                                         ql.Compounded,
                                         frequency
                                       ).rate()*100
    )

pgbs
```

Besides interpolation, you can also check out the FittedBondDiscountCurve class where you have several fitting methods (CubicBSplinesFitting, SimplePolynomialFitting, NelsonSiegelFitting, SvenssonFitting, ExponentialSplinesFitting)

Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.