Metadata-Version: 2.4
Name: ratecurves
Version: 0.1.1
Summary: Yield curve construction and fixed-income analytics for Python
Author-email: Damian Gallardo <damiangallardoloya@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/DGallardoL/ratecurves
Project-URL: Documentation, https://github.com/DGallardoL/ratecurves#readme
Project-URL: Repository, https://github.com/DGallardoL/ratecurves
Project-URL: Issues, https://github.com/DGallardoL/ratecurves/issues
Keywords: yield-curve,fixed-income,bonds,finance,nelson-siegel,bootstrapping,duration,convexity,quantitative-finance,treasury
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20
Requires-Dist: scipy>=1.7
Requires-Dist: pandas>=1.3
Requires-Dist: matplotlib>=3.4
Provides-Extra: data
Requires-Dist: requests>=2.25; extra == "data"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=3.0; extra == "dev"
Requires-Dist: requests>=2.25; extra == "dev"
Provides-Extra: all
Requires-Dist: requests>=2.25; extra == "all"
Requires-Dist: pytest>=7.0; extra == "all"
Requires-Dist: pytest-cov>=3.0; extra == "all"
Dynamic: license-file

# ratecurves

**Yield Curve Construction & Fixed Income Analytics for Python**

[![PyPI](https://img.shields.io/pypi/v/ratecurves)](https://pypi.org/project/ratecurves/)
[![Python](https://img.shields.io/pypi/pyversions/ratecurves)](https://pypi.org/project/ratecurves/)
[![CI](https://github.com/DGallardoL/ratecurves/actions/workflows/ci.yml/badge.svg)](https://github.com/DGallardoL/ratecurves/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DGallardoL/ratecurves/blob/main/notebooks/tutorial.ipynb)

---

`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

```bash
pip install ratecurves
```

With live data support (adds `requests`):

```bash
pip install ratecurves[all]
```

## Quick Start

```python
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](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DGallardoL/ratecurves/blob/main/notebooks/tutorial.ipynb)

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

```python
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

```python
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

```python
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

```python
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

```python
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)

```python
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

```python
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:

```bash
# 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:

```bash
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

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

## License

[MIT](LICENSE)

## 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.
