Skip to main content

Yield curve construction and fixed-income analytics for Python

Project description

ratecurves

Yield Curve Construction & Fixed Income Analytics for Python

PyPI Python CI License: MIT

Open In Colab


ratecurves is a lightweight Python library for building yield curves, pricing fixed-rate bonds, and computing interest rate risk metrics. It fetches live US Treasury data from FRED (free, no API key) and implements the core quantitative methods used in fixed-income desks.

Features

  • Yield Curve Construction — Build curves from zero rates, par rates, or raw instruments (T-bills + coupon bonds)
  • Bootstrapping — Iterative stripping of zero-coupon rates from par rates
  • Parametric Models — Nelson-Siegel (1987) and Svensson (1994) with least-squares calibration
  • Three Interpolation Methods — Linear, natural cubic spline, and log-linear on discount factors
  • Bond Pricing — From yield-to-maturity or from any yield curve; YTM solver; Z-spread computation
  • Risk Metrics — Macaulay/modified/effective duration, DV01, convexity, key rate durations
  • Scenario Analysis — Parallel shifts, key-rate (localized) shifts, portfolio P&L
  • Live Market Data — Fetch US Treasury CMT rates from FRED (no API key required)
  • Visualization — Built-in plotting for curves, price-yield, KRDs, and curve evolution

Installation

pip install ratecurves

With live data support (adds requests):

pip install ratecurves[all]

Quick Start

from ratecurves import YieldCurve, Bond, bootstrap_from_par_rates
from ratecurves import modified_duration, dv01, convexity

# 1. Build a yield curve from par rates
par_mats = [0.5, 1, 2, 5, 10, 30]
par_rates = [0.052, 0.050, 0.047, 0.043, 0.041, 0.039]
curve = bootstrap_from_par_rates(par_mats, par_rates)

# 2. Query the curve
print(f"5Y spot rate:     {curve.spot(5):.4%}")
print(f"5Y discount:      {curve.discount(5):.6f}")
print(f"Forward 2Y→5Y:    {curve.forward(2, 5):.4%}")

# 3. Price a bond
bond = Bond(coupon_rate=0.04125, maturity=10, freq=2)
price = bond.price_from_curve(curve)
ytm = bond.ytm(price)
print(f"Price: {price:.4f}  |  YTM: {ytm:.4%}")

# 4. Risk metrics
print(f"Modified Duration: {modified_duration(bond, ytm):.4f}")
print(f"DV01:              {dv01(bond, ytm):.4f}")
print(f"Convexity:         {convexity(bond, ytm):.2f}")

Tutorial Notebook

The full interactive tutorial is available as a Colab notebook:

Open In Colab

It covers yield curve construction, bootstrapping, parametric models, bond pricing, risk metrics, live FRED data, and visualization — all step by step.

Detailed Usage

Yield Curves

from ratecurves import YieldCurve

# From zero rates directly
curve = YieldCurve(
    maturities=[1, 2, 5, 10, 30],
    zero_rates=[0.048, 0.045, 0.042, 0.041, 0.040],
    method='cubic',  # 'linear', 'cubic', or 'log_linear'
)

# Spot rates, discount factors, forwards
curve.spot(7)          # interpolated 7Y rate
curve.discount(5)      # DF(5)
curve.forward(2, 5)    # forward rate from 2Y to 5Y
curve.par_rate(10)     # par coupon for a 10Y bond

# Curve shifts
curve.shift(25)                          # parallel +25bp
curve.key_rate_shift(5, bp=10, width=2)  # localized bump at 5Y

Bootstrapping

from ratecurves import bootstrap_from_par_rates, bootstrap_from_instruments

# From par rates (most common)
curve = bootstrap_from_par_rates(
    maturities=[0.5, 1, 2, 5, 10, 30],
    par_rates=[0.052, 0.050, 0.047, 0.043, 0.041, 0.039],
)

# From mixed instruments
curve = bootstrap_from_instruments(
    tbill_maturities=[0.25, 0.5],
    tbill_rates=[0.053, 0.052],
    bond_maturities=[2, 5, 10],
    bond_coupons=[0.047, 0.043, 0.041],
    bond_prices=[100.5, 101.2, 102.0],
)

Parametric Models

from ratecurves.models import fit_nelson_siegel, fit_svensson

mats = [0.25, 0.5, 1, 2, 5, 10, 30]
rates = [0.052, 0.051, 0.048, 0.045, 0.042, 0.041, 0.040]

# Nelson-Siegel
ns = fit_nelson_siegel(mats, rates)
print(ns.params)  # {'beta0': ..., 'beta1': ..., 'beta2': ..., 'lambda': ...}
ns.rate(7)         # evaluate at any maturity

# Svensson (extended)
sv = fit_svensson(mats, rates)
curve = sv.to_yield_curve()  # convert to YieldCurve object

Bond Pricing

from ratecurves import Bond

bond = Bond(face=100, coupon_rate=0.05, maturity=10, freq=2)

bond.price_from_ytm(0.04)       # price at given YTM
bond.price_from_curve(curve)    # price from yield curve
bond.ytm(105.0)                 # solve for YTM
bond.z_spread(98.5, curve)      # Z-spread over the curve

Risk Metrics

from ratecurves import (
    macaulay_duration, modified_duration, effective_duration,
    dv01, convexity, key_rate_durations, price_change_estimate,
)

# All standard metrics
macaulay_duration(bond, ytm)
modified_duration(bond, ytm)
effective_duration(bond, curve)
dv01(bond, ytm)
convexity(bond, ytm)

# Key Rate Durations
krd = key_rate_durations(bond, curve)
# {0.5: 0.001, 1.0: 0.012, 2.0: 0.089, ..., 10.0: 7.234}

# Duration + Convexity price change estimate
est = price_change_estimate(bond, ytm, dy_bp=50)
# {'duration_effect': -3.82, 'convexity_effect': 0.07, 'total_estimate': -3.75, ...}

Live Market Data (FRED)

from ratecurves.data import fetch_treasury_rates, get_latest_curve

# Latest yield curve
curve, rates = get_latest_curve()

# Historical data
df = fetch_treasury_rates(start_date='2024-01-01')

# Historical curves (quarterly)
from ratecurves.data import fetch_historical_curves
curves = fetch_historical_curves('2023-01-01', freq='Q')

Visualization

from ratecurves.plot import (
    plot_yield_curve,
    plot_multiple_curves,
    plot_price_yield,
    plot_key_rate_durations,
    plot_curve_evolution,
)

plot_yield_curve(curve, show_forwards=True)
plot_price_yield(bond, current_ytm=0.04)
plot_key_rate_durations(bond, curve)

Docker

Run tests, examples, or an interactive shell in a container:

# Run all tests
docker compose run test

# Run the quick-start demo
docker compose run demo

# Run the bond analysis example
docker compose run bond-analysis

# Interactive Python with ratecurves loaded
docker compose run shell

Build manually:

docker build -t ratecurves .
docker run ratecurves                          # runs tests
docker run ratecurves python examples/quick_start.py  # run demo

Project Structure

ratecurves/
├── ratecurves/
│   ├── __init__.py       # Public API
│   ├── curve.py          # YieldCurve, bootstrapping
│   ├── models.py         # Nelson-Siegel, Svensson
│   ├── bond.py           # Bond pricing, YTM, Z-spread
│   ├── risk.py           # Duration, convexity, DV01, KRDs
│   ├── data.py           # FRED data fetching
│   └── plot.py           # Visualization utilities
├── tests/                # pytest suite
├── examples/             # Runnable example scripts
├── notebooks/
│   └── tutorial.ipynb    # Colab tutorial notebook
├── .github/workflows/
│   ├── ci.yml            # CI: test on push/PR
│   └── publish.yml       # CD: publish to PyPI on release
├── Dockerfile
├── docker-compose.yml
├── pyproject.toml        # Package metadata & dependencies
└── README.md

Development

git clone https://github.com/DGallardoL/ratecurves.git
cd ratecurves
pip install -e ".[dev]"
pytest tests/ -v

License

MIT

References

  • Nelson, C.R. & Siegel, A.F. (1987). Parsimonious Modeling of Yield Curves. Journal of Business.
  • Svensson, L.E.O. (1994). Estimating and Interpreting Forward Interest Rates. IMF Working Paper.
  • Fabozzi, F.J. (2007). Fixed Income Analysis. CFA Institute.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ratecurves-0.1.0.tar.gz (26.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ratecurves-0.1.0-py3-none-any.whl (21.5 kB view details)

Uploaded Python 3

File details

Details for the file ratecurves-0.1.0.tar.gz.

File metadata

  • Download URL: ratecurves-0.1.0.tar.gz
  • Upload date:
  • Size: 26.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for ratecurves-0.1.0.tar.gz
Algorithm Hash digest
SHA256 fa07a20d37960bfc962f5f2a71d04c2a242a8f8448a7646f3989ba9faf97e3ad
MD5 03cd25cf7822bbb97ad6016acedd65d2
BLAKE2b-256 41eb7d0ffd2a769878372be6008c088fda9735e3b42b2dc31645296d85b86509

See more details on using hashes here.

File details

Details for the file ratecurves-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: ratecurves-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 21.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for ratecurves-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 defbc7da3882a51f674fa3c482ec826e35f6437d6948c30ea19132edee8d1656
MD5 6d37b01c5cdaf6d7fd5611202f1e5fa7
BLAKE2b-256 8f6d88c55bcfac09a9c8d03202685a1fa4d5184300bc576e85ec2dc1e15e9547

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page