Skip to main content

Package to compute and price swap

Project description

Financial Toolkit Library (IRS_toolkit)

Poetry Linting - Ruff Code style - Black PyPI version Python

A comprehensive Python library for financial derivatives pricing, risk analysis, and fixed income calculations. The Financial Toolkit Library provides robust tools for interest rate swaps, bond valuation, options pricing, yield curve construction, and advanced financial analytics.

Table of Contents

  1. Installation
  2. Features
  3. Project Structure
  4. Usage Examples
  5. Testing
  6. Documentation
  7. API Reference
  8. Contributing
  9. Future Work

Installation

Requirements

  • Python 3.11 or higher (up to Python 3.13)
  • Dependencies: pandas, scipy, numpy, scikit-learn

Quick Install

The library is published on PyPI. To install the latest stable version:

pip install IRS_toolkit

Development Installation

For development or to use the latest features:

# Clone the repository
git clone https://github.com/your-repo/financial-toolkit-library.git
cd financial-toolkit-library

# Install with Poetry (recommended)
poetry install

# Or install with pip in development mode
pip install -e .

Optional Dependencies

For enhanced functionality, install additional dependencies:

# For documentation generation
pip install mkdocs mkdocs-material mkdocstrings[python]

# For Jupyter notebook support
pip install jupyter ipykernel ipywidgets

# For testing
pip install pytest

Features

The Financial Toolkit Library provides a comprehensive suite of tools for financial derivatives pricing, risk analysis, and advanced calculations:

๐Ÿ”„ Interest Rate Swap (IRS) Valuation

  • Swap Pricing (core/swap.py): Complete swap valuation including NPV, fair rate calculation, and risk metrics
  • Fixed Leg Pricing (core/leg/fix_leg.py): Fixed rate leg calculations with discount factor application
  • Floating Leg Pricing (core/leg/float_leg.py): Floating rate leg with forward rate projections and ESTR integration
  • Cash Flow Analysis (core/cash_flow.py): Detailed cash flow generation and analysis
  • Settlement Detection: Advanced settlement asymmetry handling for payment date offsets

๐Ÿ“ˆ Yield Curve & Market Data

  • Yield Curve Construction (core/curve/yield_curve.py): Advanced bootstrapping with multiple conventions and interpolation
  • Compounded Rates (core/curve/compounded.py): ESTR and other overnight rate compounding
  • Forward Rate Calculations: Multi-period forward rate extraction and projection
  • Zero-Coupon Curve Generation: Bootstrap zero-coupon rates from market instruments
  • Multiple Day Count Conventions: ACT/360, ACT/365, 30/360, ACT/ACT support

๐Ÿ’ฐ Bond Pricing & Fixed Income

  • Fixed Rate Bond Valuation (bonds_pricer.py): Comprehensive bond pricing with yield, duration, and risk metrics
  • Coupon Calculations: Regular and irregular coupon payment handling
  • Accrued Interest: Precise accrued interest calculations with multiple conventions
  • Duration & Convexity: Advanced risk metrics for bond portfolio management
  • Redemption Modeling: Maturity value and early redemption scenarios

๐Ÿ“Š Options & Derivatives

  • Black-Scholes Implementation (options/blackscholes.py): European option pricing with Greeks calculation
  • Implied Volatility: Advanced numerical methods for volatility extraction
  • Swaption Pricing (options/swaption.py): Interest rate option valuation framework
  • Options Risk Management: Delta, gamma, theta, vega calculations

๐Ÿ”ง Financial Utilities & Risk Management

  • Schedule Generation (utils/schedule.py): Flexible payment schedule creation with holiday calendars
  • Day Count Functions (utils/core.py): Comprehensive day count convention implementations
  • Financial Calculations (utils/financial.py): DV01, spread calculations, and risk metrics
  • Rate Conversions: Zero-coupon to simple rate conversions and compounding
  • Business Day Adjustments: Holiday calendar and business day convention handling

๐Ÿงฎ Advanced Analytics

  • Scenario Analysis: Multi-scenario swap and bond valuations
  • Risk Metrics: DV01, duration, convexity, and sensitivity analysis
  • Optimization: Fair rate solving using advanced numerical methods
  • Stress Testing: Parallel and non-parallel curve shift analysis
  • Settlement Analysis: Payment timing and settlement date optimization

๐Ÿ› ๏ธ Developer Tools

  • Comprehensive Type Hints: Full typing support for better IDE integration
  • Extensive Testing: 100+ unit tests covering all major functionality
  • Flexible Configuration: Customizable conventions, calendars, and calculation methods
  • Performance Optimized: Efficient pandas and numpy operations
  • Documentation: Detailed docstrings and usage examples

Project Structure

financial-toolkit-library/
โ”œโ”€โ”€ IRS_toolkit/                    # Main package source code
โ”‚   โ”œโ”€โ”€ core/                      # Core financial instruments
โ”‚   โ”‚   โ”œโ”€โ”€ cash_flow.py          # Cash flow generation and analysis
โ”‚   โ”‚   โ”œโ”€โ”€ swap.py               # Interest rate swap pricing
โ”‚   โ”‚   โ”œโ”€โ”€ curve/                # Yield curve implementations
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ yield_curve.py    # Yield curve construction and bootstrapping
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ compounded.py     # Compounded rate calculations (ESTR, etc.)
โ”‚   โ”‚   โ””โ”€โ”€ leg/                  # Swap leg implementations
โ”‚   โ”‚       โ”œโ”€โ”€ fix_leg.py        # Fixed rate leg pricing
โ”‚   โ”‚       โ””โ”€โ”€ float_leg.py      # Floating rate leg pricing
โ”‚   โ”œโ”€โ”€ options/                   # Derivatives and options pricing
โ”‚   โ”‚   โ”œโ”€โ”€ blackscholes.py       # Black-Scholes option pricing
โ”‚   โ”‚   โ””โ”€โ”€ swaption.py           # Interest rate swaption pricing
โ”‚   โ””โ”€โ”€ utils/                     # Utility functions and helpers
โ”‚       โ”œโ”€โ”€ constants.py          # Financial constants and type definitions
โ”‚       โ”œโ”€โ”€ core.py               # Day count conventions and date utilities
โ”‚       โ”œโ”€โ”€ financial.py          # Financial calculations (DV01, spreads)
โ”‚       โ””โ”€โ”€ schedule.py           # Payment schedule generation
โ”œโ”€โ”€ bonds_pricer.py                # Fixed income bond pricing module
โ”œโ”€โ”€ docs/                          # Comprehensive documentation
โ”‚   โ”œโ”€โ”€ index.md                  # Main documentation index
โ”‚   โ”œโ”€โ”€ curve_toolkit/            # Yield curve documentation
โ”‚   โ”œโ”€โ”€ swap_toolkit/             # Swap pricing documentation
โ”‚   โ”œโ”€โ”€ testing/                  # Testing guidelines
โ”‚   โ””โ”€โ”€ utils/                    # Utility function documentation
โ”œโ”€โ”€ examples/                      # Usage examples and tutorials
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ example.py                # Basic usage examples
โ”œโ”€โ”€ tests/                         # Comprehensive test suite
โ”‚   โ”œโ”€โ”€ test_cashflow.py          # Cash flow testing
โ”‚   โ”œโ”€โ”€ test_fix_leg.py           # Fixed leg testing
โ”‚   โ”œโ”€โ”€ test_float_leg.py         # Floating leg testing
โ”‚   โ”œโ”€โ”€ test_swap.py              # Swap pricing testing
โ”‚   โ”œโ”€โ”€ test_yield_curve.py       # Yield curve testing
โ”‚   โ”œโ”€โ”€ test_utils_*.py           # Utility function testing
โ”‚   โ””โ”€โ”€ test_different_schedules.py # Schedule generation testing
โ”œโ”€โ”€ pyproject.toml                 # Project configuration and dependencies
โ”œโ”€โ”€ mkdocs.yml                     # Documentation configuration
โ”œโ”€โ”€ Makefile                       # Build and development commands
โ”œโ”€โ”€ ruff.toml                      # Linting configuration
โ””โ”€โ”€ README.md                      # This documentation

Usage Examples

1. Yield Curve Construction

Build and bootstrap a yield curve from market data:

from IRS_toolkit.core.curve import yield_curve
from datetime import datetime

# Market data: tenors and corresponding rates
list_tenor = ['1D', '2D', '1W', '2W', '3W', '1M', '2M', '3M', '6M', '9M', '1Y', '2Y', '3Y', '5Y', '10Y']
rates = [0.035, 0.0355, 0.036, 0.0365, 0.037, 0.0375, 0.038, 0.0385, 0.039, 0.040, 0.041, 0.042, 0.043, 0.044, 0.045]
curve_date = datetime(2025, 3, 10)

# Construct yield curve
curve = yield_curve.YieldCurve(
    list_tenor=list_tenor,
    list_rate=rates,
    date_curve=curve_date,
    date_convention="ACT/360",
)

# Bootstrap the curve to get zero-coupon rates
curve.bootstrap("quarterly")

# Access the resulting curve data
print(curve.df)  # View complete curve with discount factors and zero rates

2. Interest Rate Swap Pricing

Price a 5-year EUR interest rate swap:

from IRS_toolkit.core import swap
from IRS_toolkit.utils import schedule
from IRS_toolkit.utils.constants import pay_frequency
from datetime import datetime
from dateutil.relativedelta import relativedelta

# Swap parameters
notional = 100_000_000  # โ‚ฌ100M
fixed_rate = 0.035      # 3.5%
start_date = datetime(2025, 3, 15)
maturity_date = start_date + relativedelta(years=5)

# Create payment schedules
fixed_schedule = schedule.Schedule(
    start_date=start_date,
    maturity_date=maturity_date,
    periodicity=pay_frequency["annual"],  # Annual fixed payments
    date_convention="ACT/360"
)

floating_schedule = schedule.Schedule(
    start_date=start_date,
    maturity_date=maturity_date,
    periodicity=pay_frequency["quarterly"],  # Quarterly floating payments
    date_convention="ACT/360"
)

# Create swap object (assuming curve from previous example)
swap_deal = swap.Swap(
    nominal=notional,
    fix_rate=fixed_rate,
    yield_curve_fix=curve,
    yield_curve_float=curve,
    schedule_fix=fixed_schedule,
    schedule_float=floating_schedule,
)

# Price the swap
valuation_date = datetime(2025, 3, 10)
npv = swap_deal.npv(valuation_date)
fair_rate = swap_deal.fair_rate(valuation_date)

print(f"Swap NPV: โ‚ฌ{npv:,.2f}")
print(f"Fair Rate: {fair_rate[1]*100:.4f}%")

3. Bond Pricing

Price a fixed-rate bond:

from bonds_pricer import FixedRateBond
from datetime import datetime

# Bond parameters
face_value = 1_000_000    # โ‚ฌ1M face value
coupon_rate = 0.04        # 4% annual coupon
issue_date = datetime(2023, 1, 15)
maturity_date = datetime(2028, 1, 15)
valuation_date = datetime(2025, 3, 10)

# Create bond object
bond = FixedRateBond(
    face_value=face_value,
    issue_date=issue_date,
    maturity_date=maturity_date,
    curve=curve,  # Using curve from previous example
    coupon_rate=coupon_rate,
    coupon_frequency="annual"
)

# Price the bond
bond.pricing(valuation_date)

print(f"Bond NPV: โ‚ฌ{bond.NPV:,.2f}")
print(f"Accrued Interest: โ‚ฌ{bond.accrued_coupon:,.2f}")
print(f"Clean Price: โ‚ฌ{(bond.NPV - bond.accrued_coupon):,.2f}")

4. Options Pricing

Price European options using Black-Scholes:

from IRS_toolkit.options.blackscholes import Call

# Option parameters
option = Call(
    Stock_price=100,    # Current underlying price
    Strike=105,         # Strike price
    r=0.05,            # Risk-free rate
    T=0.25,            # Time to expiry (3 months)
    volatility=0.20    # Implied volatility
)

# Calculate option price
option.price()
print(f"Call Option Price: {option.call_price:.4f}")

# Calculate implied volatility (if you have market price)
option_with_market_price = Call(
    Stock_price=100,
    Strike=105, 
    r=0.05,
    T=0.25,
    call_price=2.5  # Market price
)

implied_vol = option_with_market_price.compute_implied_volatility()
print(f"Implied Volatility: {implied_vol[0]:.4f}")

5. Financial Calculations & Risk Metrics

Calculate DV01 and other risk metrics:

from IRS_toolkit.utils.financial import dv01_two_sided, spread_amount
from IRS_toolkit.utils.core import day_count

# DV01 calculation for a swap (requires base and shifted scenarios)
base_npv = 150_000
up_npv = 148_500     # NPV with +1bp shift
down_npv = 151_500   # NPV with -1bp shift

dv01 = dv01_two_sided(base_npv, up_npv, down_npv, shift_size_bp=1.0)
print(f"DV01: โ‚ฌ{dv01:,.2f}")

# Day count calculations
start = datetime(2025, 1, 15)
end = datetime(2025, 7, 15)
day_count_fraction = day_count(start, end, "ACT/360")
print(f"Day count fraction (ACT/360): {day_count_fraction:.6f}")

6. Schedule Generation

Generate flexible payment schedules:

from IRS_toolkit.utils.schedule import Schedule
from IRS_toolkit.utils.constants import pay_frequency

# Create a quarterly payment schedule
quarterly_schedule = Schedule(
    start_date=datetime(2025, 3, 15),
    maturity_date=datetime(2030, 3, 15),
    periodicity=pay_frequency["quarterly"],
    type_fill="Forward",
    date_convention="ACT/360"
)

print("Payment Schedule:")
print(quarterly_schedule.df[['start_date', 'end_date', 'day_count']])

Testing

The library includes a comprehensive test suite covering all major functionality:

Running Tests

# Run all tests
poetry run pytest

# Run with coverage
poetry run pytest --cov=IRS_toolkit --cov-report=html

# Run specific test modules
poetry run pytest tests/test_swap.py
poetry run pytest tests/test_yield_curve.py

Test Coverage

The test suite includes:

  • Core Functionality Tests:

    • test_swap.py: Comprehensive swap pricing validation
    • test_yield_curve.py: Curve construction and bootstrapping
    • test_fix_leg.py & test_float_leg.py: Individual leg pricing
    • test_cashflow.py: Cash flow generation and analysis
  • Utility Function Tests:

    • test_utils_core.py: Day count conventions and date handling
    • test_utils_financial.py: Financial calculations and risk metrics
    • test_utils_schedule.py: Payment schedule generation
  • Edge Case Testing:

    • test_different_schedules.py: Various schedule configurations
    • Boundary conditions and error handling
    • Performance benchmarks for large datasets

Testing Best Practices

  • All public methods have corresponding unit tests
  • Edge cases and error conditions are explicitly tested
  • Financial accuracy validated against known benchmarks
  • Performance tests ensure scalability

Documentation

Comprehensive Documentation

The library provides extensive documentation built with MkDocs:

# Install documentation dependencies
pip install mkdocs mkdocs-material mkdocstrings[python]

# Serve documentation locally
mkdocs serve

# Build static documentation
mkdocs build

Documentation Structure

Available Documentation

  • API Reference: Complete function and class documentation
  • Tutorial Notebooks: Step-by-step usage examples
  • Mathematical Background: Financial models and methodologies
  • Performance Guidelines: Optimization tips and best practices

API Reference

Core Modules

Swap Pricing

from IRS_toolkit.core.swap import Swap
from IRS_toolkit.core.leg.fix_leg import FixLeg
from IRS_toolkit.core.leg.float_leg import FloatLeg

Yield Curves

from IRS_toolkit.core.curve.yield_curve import YieldCurve
from IRS_toolkit.core.curve.compounded import Compounded

Bond Pricing

from bonds_pricer import FixedRateBond

Options Pricing

from IRS_toolkit.options.blackscholes import Call
from IRS_toolkit.options.swaption import Swaption

Utilities

from IRS_toolkit.utils.schedule import Schedule
from IRS_toolkit.utils.financial import dv01_two_sided
from IRS_toolkit.utils.core import day_count
from IRS_toolkit.utils.constants import pay_frequency, VALID_CONVENTIONS

Contributing

Development Setup

  1. Clone the repository:
git clone https://github.com/your-repo/financial-toolkit-library.git
cd financial-toolkit-library
  1. Install development dependencies:
poetry install --with dev,tests,lint
  1. Set up pre-commit hooks:
pre-commit install

Code Quality

  • Linting: Use ruff for code linting and formatting
  • Type Hints: All public functions must include type hints
  • Documentation: Add docstrings for all public methods
  • Testing: Include tests for all new functionality

Contribution Guidelines

  • Follow existing code patterns and naming conventions
  • Add comprehensive tests for new features
  • Update documentation for API changes
  • Ensure all tests pass before submitting PRs

Future Work

Planned Enhancements

Yield Curve Improvements:

  • Multi-curve framework support (OIS, LIBOR, SOFR)
  • Additional interpolation methods (cubic spline, Nelson-Siegel)
  • Curve risk metrics and sensitivity analysis

Derivatives Expansion:

  • Complete swaption pricing implementation
  • Interest rate caps and floors
  • Cross-currency swaps
  • Inflation-linked derivatives

Risk Management:

  • Value-at-Risk (VaR) calculations
  • Expected Shortfall metrics
  • Stress testing frameworks
  • Portfolio optimization tools

Performance & Integration:

  • GPU acceleration for large portfolios
  • Market data connector integration
  • Real-time pricing capabilities
  • Database integration for historical analysis

Documentation & Usability:

  • Interactive web documentation
  • Video tutorials and examples
  • Integration with popular data sources
  • Enhanced error handling and validation

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

irs_toolkit-0.2.2.tar.gz (24.8 kB view details)

Uploaded Source

Built Distribution

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

irs_toolkit-0.2.2-py3-none-any.whl (31.5 kB view details)

Uploaded Python 3

File details

Details for the file irs_toolkit-0.2.2.tar.gz.

File metadata

  • Download URL: irs_toolkit-0.2.2.tar.gz
  • Upload date:
  • Size: 24.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.3 Darwin/25.0.0

File hashes

Hashes for irs_toolkit-0.2.2.tar.gz
Algorithm Hash digest
SHA256 2eba60e5d35493c035813b9b9a9f4dc44c543ee77ce669ecbb42eed67c116e32
MD5 43fec9d4478511eaad44d3069fe070ef
BLAKE2b-256 391202171adf49625ccd56bce3a582461f8abe2dfede20da979f43deb0eb5372

See more details on using hashes here.

File details

Details for the file irs_toolkit-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: irs_toolkit-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 31.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.3 Darwin/25.0.0

File hashes

Hashes for irs_toolkit-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 3afb0ce9c01391144a7d9c33594ca8c15e494dfffb7006a3fccf914ee1551fbb
MD5 6d8abc18a9bc24d199168649c4171c4b
BLAKE2b-256 16ad183f129a52aed7fe3cac667b90c0d0b0efbd090228268a008f96a6bf8816

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