Skip to main content

Reusable quantitative finance research library extracted from the Quantitative Finance Lab notebook projects

Project description

quantfinlab Library

quantfinlab is the reusable Python library extracted from the Quantitative Finance Lab project series. It is not a general-purpose finance library. It is a focused package covering the methods developed across the twenty projects: fixed income, options pricing, portfolio construction, risk reporting, volatility modeling, hedging, macro indicators, dependence networks, and ML/RL components for finance.

The test suite checks real model properties rather than notebook snapshots: weights summing to one, CVaR behavior, curve/discount consistency, American option engine fallbacks, implied-volatility diagnostics, and PSD matrix reconstruction. The current package checks pass with a clean ruff lint pass.

Installation

From the repository root:

pip install -e .

Source installs build the optional C++ extension (quantfinlab._kernels) automatically via scikit-build-core, CMake, and pybind11 when a C++ compiler is available. The extension accelerates the heaviest American-option, Fourier/COS, Monte Carlo, and calibration kernels, but the package also works from a pure-Python wheel when native builds are not available.

To disable native kernels during a source install:

pip install . --config-settings=cmake.define.quantfinlab_build_cpp=off

Functions that accept engine="auto" prefer C++ when available, then Numba when installed, then NumPy/SciPy fallback paths where implemented. If you explicitly request engine="cpp" without the extension installed, quantfinlab raises MissingKernelsError with installation and fallback guidance.

Most of the library works with just the core dependencies (NumPy, pandas, SciPy, cvxpy, and scikit-learn). A handful of modules need optional extras, installed as needed:

pip install -e ".[numerics]"   # JAX / Numba acceleration (autodiff Greeks, fast IV)
pip install -e ".[volatility]" # arch, statsmodels (GARCH, HAR)
pip install -e ".[hedging]"    # statsmodels (dynamic hedge ratios)
pip install -e ".[ml]"         # PyTorch (sequence models, RL policies)
pip install -e ".[network]"    # networkx (dependence networks)
pip install -e ".[plotting]"   # matplotlib, seaborn
pip install -e ".[all]"        # everything above

Optional dependencies are checked at the point of use. Functions either fall back to a pure NumPy/SciPy implementation, or raise a clear, specific error telling you which extra to install, rather than failing on package import. Tests that need optional dependencies use pytest.importorskip and skip cleanly rather than fail when the dependency is absent.

Module map

Module Covers
quantfinlab.dataio Source-normalized data loading: yield curves, equity/ETF panels, option chains, macro series, every loader returns a stable schema regardless of the underlying data vendor. See Data loading below.
quantfinlab.fixed_income Curve bootstrapping, discounting, forward rates, bond pricing and cashflows, duration/convexity/key-rate duration, short-rate/term-structure models, swaps, scenario generation, duration-targeted laddering.
quantfinlab.options Black–Scholes/Black-76 pricing, put-call parity, quote cleaning, implied volatility (Newton-bisection and "Let's Be Rational"-style solvers, with an optional Numba backend), analytic and autodiff Greeks (optional JAX), American option pricing (tree/PDE/LSM, C++ and numba backed), Fourier/COS pricing, Heston/SABR/SVI/SSVI/rough-volatility/Merton/variance-gamma models, local volatility, and model-risk diagnostics.
quantfinlab.portfolio Expected-return models, covariance estimation (sample/Ledoit-Wolf/OAS/EWMA), mean-variance/min-variance/max-Sharpe/ridge optimizers, constraints, transaction costs, walk-forward backtesting harness, Black-Litterman (with learned-confidence views and factor/regime conditioning), HRP/NCO clustering allocation, risk parity, CVaR and robust (box/ellipsoid/Wasserstein) optimization, factor construction, regime models, dependence-network construction and network-based signals, universe selection and position sizing.
quantfinlab.risk VaR/expected shortfall (historical, Cornish-Fisher, filtered historical simulation), VaR backtesting, drawdown analysis, performance metrics, CAPM beta, correlation diagnostics, stress testing, risk contribution/attribution.
quantfinlab.volatility Realized-volatility estimators, GARCH/HAR forecasting, rough-volatility estimation, variance risk premium analysis.
quantfinlab.hedging Dynamic hedge-ratio estimation, hedge policies, residual-spread construction, hedging performance metrics.
quantfinlab.macro Macro indicator construction (financial-conditions index, NFCI-style PCA), macro-conditioned allocation models.
quantfinlab.ml Feature engineering, forecasting evaluation (rank metrics, pinball loss, coverage), probabilistic/uncertainty models, sequence models (e.g. TCN-based forecasters), regime classifiers, RL environments, reward shaping (differential Sharpe ratio), and RL policies (PPO, recurrent PPO, SAC).
quantfinlab.backtest Shared backtesting engines for portfolios, fixed income, hedging, and options strategies, with cost models and overlay support.
quantfinlab.reports risk report generation, combining outputs from risk, portfolio, and plotting into a single executive summary.
quantfinlab.numerics Finite-difference schemes, Fourier transforms, interpolation, Monte Carlo path generation. Shared numerical primitives used across options and calibration.
quantfinlab.calibration Model calibration. American option numerics, FFT/COS calibration, jump-diffusion model fitting, LSM regression.
quantfinlab.plotting Consistent plotting utilities per domain (curves, options, portfolio, risk, volatility, macro, regimes, ML, hedging, fixed income) and explanatory diagrams.
quantfinlab.common Shared contracts/dataclasses (Curve, Bond, PortfolioState, BacktestResult, ...), error types, date utilities, and input validation used across every other module.

The optional C++ pricing kernels (cpp/, exposed as quantfinlab._kernels) implement the LSM regression solver, the PSOR finite-difference PDE solver, the binomial tree, Monte Carlo paths, and the Fourier/COS pricer. They are written in C++ and bound via pybind11 for speed; pure-Python installs keep the public APIs importable and use automatic fallbacks where those methods exist.

Data loading

quantfinlab.dataio is what every notebook uses to turn a raw downloaded file into a clean, analysis-ready dataset. It is also the boundary the project series treats most carefully. see the project README and data README for how raw data is obtained in the first place, dataio is what runs after having the data files for turning them into analysis ready dataframes.

from quantfinlab.dataio import load_par_yield_curve, load_yfinance_panel

us_curve = load_par_yield_curve("data/us_treasury_yields.csv", source="us_treasury")
jp_curve = load_par_yield_curve("data/japan_mof_yields.csv", source="japan_mof")

panel = load_yfinance_panel(
    "data/core_cross_asset_etfs.csv", fields=("close", "volume"),
    source="yfinance_export", start="2010-01-01")

close, volume = panel["close"], panel["volume"]

Every loader in dataio normalizes to the same shape. par-yield curves come back as a DatetimeIndex-sorted DataFrame with standard tenor columns (1M...30Y) in decimal form. equities and prices come back as {field: DataFrame} with tickers as columns, numeric-coerced, deduplicated, sorted. This is what makes the "secondary market" repeat at the end of most notebooks possible with no extra glue code. swap the path/source, get the same schema back.

Examples

A few representative examples. See the notebooks for the full derivations behind each of these and the full repeat of each project completely using the library.

Mean-variance portfolio optimization with turnover control

from quantfinlab.portfolio import covariance, optimizers

cov_ann = covariance.estimate_covariance(returns_window, method="LedoitWolf", return_df=True)

weights = optimizers.mean_variance(
    mu_excess_ann=expected_excess_returns,
    cov_ann=cov_ann, mv_lambda=6.0,
    w_max=0.25, turnover_penalty_bps=10.0,
    long_only=True)

optimizers also exposes equal_weight, minimum_variance, ridge_mean_variance, max_sharpe_slsqp, and max_sharpe_frontier_grid with the same calling convention, plus a walkforward module that runs any of these through a full rolling rebalance/backtest loop given a returns panel and rebalance schedule.

Implied volatility from a market quote

from quantfinlab.options import iv

sigma = iv.implied_vol(
    option_type="call", price=4.35, forward=101.2,
    strike=100.0, tau=30 / 365,
    engine="auto", solver="lbr_lite")

For a full option-chain DataFrame at once, iv.compute_iv_table(quotes, ...) runs the same solver vectorized across all rows and returns solver-status diagnostics alongside the implied vols (used in the notebooks to check solver success rate and pricing residuals before trusting a fitted surface).

Risk parity and CVaR-aware allocation

from quantfinlab.portfolio import risk_parity, cvar

erc_weights = risk_parity.equal_risk_contribution_weights(cov_ann, tickers=cov_ann.index, w_max=0.40)
contrib_table = risk_parity.risk_contribution_table(erc_weights, cov_ann)

cvar_weights = cvar.min_cvar_weights(returns_window, alpha=0.95, w_max=0.40)
loss = cvar.portfolio_cvar_loss(returns_window, cvar_weights, alpha=0.95)

Yield curve construction and bond pricing

from quantfinlab.dataio import load_par_yield_curve
from quantfinlab.fixed_income import bootstrap, bond_pricing

curve = load_par_yield_curve("data/us_treasury_yields.csv", source="us_treasury")
discount_curve = bootstrap.bootstrap_discount_factors(curve.loc["2024-06-01"])

price = bond_pricing.bond_price(coupon=0.045, maturity_years=10.0, df_func=discount_curve, freq=2)

A full risk report

from quantfinlab.reports import risk_report

report = risk_report.risk_report(
    returns=strategy_returns, benchmark_returns=benchmark_returns,
    weights=weights_history, cov_ann=cov_ann)

This produces the same VaR/ES, drawdown, CAPM, and risk-contribution summary used throughout Project 03 and applied to every backtest in later projects — one call instead of re-deriving the report each time.

Testing

pip install -e ".[dev]"
pytest

Tests are organized to mirror the package layout (tests/portfolio, tests/options, tests/cpp, ...) and use a small set of deterministic synthetic-data generators (tests/synthetic/generators.py) rather than real market data, so the suite is fast, reproducible, and has no external data dependency.

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

quantfinlab-0.6.0.tar.gz (717.4 kB view details)

Uploaded Source

Built Distributions

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

quantfinlab-0.6.0-py3-none-any.whl (722.8 kB view details)

Uploaded Python 3

quantfinlab-0.6.0-cp312-cp312-win_amd64.whl (1.1 MB view details)

Uploaded CPython 3.12Windows x86-64

quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (960.4 kB view details)

Uploaded CPython 3.12manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl (818.5 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

quantfinlab-0.6.0-cp311-cp311-win_amd64.whl (1.1 MB view details)

Uploaded CPython 3.11Windows x86-64

quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (961.5 kB view details)

Uploaded CPython 3.11manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl (817.0 kB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

File details

Details for the file quantfinlab-0.6.0.tar.gz.

File metadata

  • Download URL: quantfinlab-0.6.0.tar.gz
  • Upload date:
  • Size: 717.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for quantfinlab-0.6.0.tar.gz
Algorithm Hash digest
SHA256 ff91e6b2c982a9c1cacc2289a21f9e46c0a2f4490dc92afb46dcccf16c1ae21c
MD5 32ce8ac2f7170469bfffd2ed4ae5c51b
BLAKE2b-256 010443c5b5f2e0d54616a4e1b4fca301ea3b4f7ef34e52c80f506792931efc1f

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0.tar.gz:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-py3-none-any.whl.

File metadata

  • Download URL: quantfinlab-0.6.0-py3-none-any.whl
  • Upload date:
  • Size: 722.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for quantfinlab-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 462274716ea960d889b368576ab35adb028c11fdeff54412c3f7c721d9eb1f6f
MD5 568d2bb362b44550a02065dc0f99b8d1
BLAKE2b-256 e7b899f99d80dd1c13fcfd90877ed418b76894b249349b15f91b52fffde9eb36

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-py3-none-any.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 389b883a0c51ac092a1770466bb44600bb1837e8b5dc9ac75ebc3b5de8ab08c1
MD5 d6408f0c22d8cd7b32dde5bee1b23940
BLAKE2b-256 ba811277a88fa46cb9b9afbe93cf04ded2c4efc0513efec40733d2fbb95aa584

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp312-cp312-win_amd64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 e671f497e727b6fbbd579f463644df1df536f259693e27103de0029fe335004c
MD5 d6b9674f29d69d9a0da4c7befa878742
BLAKE2b-256 c2cacfecab9d01b2ce05e15132b32e60d94da1144c47b8892caf83e6aea5973e

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 ec33a4ceadec447ecbd2dbcffe6bfe94290acb99ff58a3432054f15748236488
MD5 0df2178df57133cf448d3f337c3dd33b
BLAKE2b-256 4552e92c13e3e77cff2f7c72599de69728cc830cfd798f4d2f98a2e6f58eb724

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 33f5c1bbadba6b8b117890fc44004fd52f1206894c8521c3243db3bf083970f6
MD5 3cec009e8f2f0c33de88cad5cb75842e
BLAKE2b-256 019e5d72a709966c0c44c369670a51c34645ee779f8275a40f2b77add6095ca7

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp311-cp311-win_amd64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 d6d00b68b04e4e8c49020930ab1780c57891f0ea1c7fbcc47b722cd4f692eda8
MD5 f494e4785ab709377eb58a53cd4f3b7c
BLAKE2b-256 8da78406c055e830c4ccbea3bf6469829d7183a85ea6b7a3050ba74bd61b7e14

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 22e6beb42375e2a6e8b1a860c93e42545d66ce8149c52e497b08f4cc0358b3b3
MD5 d991b02ca9ff79b8e864bbf5cb2d6b4a
BLAKE2b-256 8b3bcd806e2933003d699d5b326c5228b2b061d804e86affd1013650f0936763

See more details on using hashes here.

Provenance

The following attestation bundles were made for quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl:

Publisher: release.yml on ramtin-asadi/Quantitative-Finance-Lab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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