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.
Metadata
Release files for quantfinlab 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| quantfinlab-0.6.0.tar.gz | 717.4 kB | Details |
Built distributions (wheels)
| File | Reset | |||
|---|---|---|---|---|
| quantfinlab-0.6.0-py3-none-any.whl | Python 3 | none | any | Details |
| quantfinlab-0.6.0-cp312-cp312-win_amd64.whl | CPython 3.12 | CPython 3.12 | Windows x86-64 | Details |
| quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl | CPython 3.12 | CPython 3.12 | Linux glibc 2.28+ x86-64, Linux glibc 2.24+ x86-64 | Details |
| quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl | CPython 3.12 | CPython 3.12 | macOS 11.0+ ARM64 | Details |
| quantfinlab-0.6.0-cp311-cp311-win_amd64.whl | CPython 3.11 | CPython 3.11 | Windows x86-64 | Details |
| quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl | CPython 3.11 | CPython 3.11 | Linux glibc 2.28+ x86-64, Linux glibc 2.24+ x86-64 | Details |
| quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl | CPython 3.11 | CPython 3.11 | macOS 11.0+ ARM64 | Details |
Total release size: 7.3 MB
Release files / quantfinlab-0.6.0.tar.gz
| Download URL | quantfinlab-0.6.0.tar.gz |
|---|---|
| Size | 717.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ff91e6b2c982a9c1cacc2289a21f9e46c0a2f4490dc92afb46dcccf16c1ae21c
|
|
BLAKE2b-256 checksum How to use checksums |
010443c5b5f2e0d54616a4e1b4fca301ea3b4f7ef34e52c80f506792931efc1f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-py3-none-any.whl
| Download URL | quantfinlab-0.6.0-py3-none-any.whl |
|---|---|
| Size | 722.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
462274716ea960d889b368576ab35adb028c11fdeff54412c3f7c721d9eb1f6f
|
|
BLAKE2b-256 checksum How to use checksums |
e7b899f99d80dd1c13fcfd90877ed418b76894b249349b15f91b52fffde9eb36
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp312-cp312-win_amd64.whl
| Download URL | quantfinlab-0.6.0-cp312-cp312-win_amd64.whl |
|---|---|
| Size | 1.1 MB |
| Tags | CPython 3.12 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
389b883a0c51ac092a1770466bb44600bb1837e8b5dc9ac75ebc3b5de8ab08c1
|
|
BLAKE2b-256 checksum How to use checksums |
ba811277a88fa46cb9b9afbe93cf04ded2c4efc0513efec40733d2fbb95aa584
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | quantfinlab-0.6.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 960.4 kB |
| Tags | CPython 3.12 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
e671f497e727b6fbbd579f463644df1df536f259693e27103de0029fe335004c
|
|
BLAKE2b-256 checksum How to use checksums |
c2cacfecab9d01b2ce05e15132b32e60d94da1144c47b8892caf83e6aea5973e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl
| Download URL | quantfinlab-0.6.0-cp312-cp312-macosx_11_0_arm64.whl |
|---|---|
| Size | 818.5 kB |
| Tags | CPython 3.12 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
ec33a4ceadec447ecbd2dbcffe6bfe94290acb99ff58a3432054f15748236488
|
|
BLAKE2b-256 checksum How to use checksums |
4552e92c13e3e77cff2f7c72599de69728cc830cfd798f4d2f98a2e6f58eb724
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp311-cp311-win_amd64.whl
| Download URL | quantfinlab-0.6.0-cp311-cp311-win_amd64.whl |
|---|---|
| Size | 1.1 MB |
| Tags | CPython 3.11 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
33f5c1bbadba6b8b117890fc44004fd52f1206894c8521c3243db3bf083970f6
|
|
BLAKE2b-256 checksum How to use checksums |
019e5d72a709966c0c44c369670a51c34645ee779f8275a40f2b77add6095ca7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | quantfinlab-0.6.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 961.5 kB |
| Tags | CPython 3.11 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
d6d00b68b04e4e8c49020930ab1780c57891f0ea1c7fbcc47b722cd4f692eda8
|
|
BLAKE2b-256 checksum How to use checksums |
8da78406c055e830c4ccbea3bf6469829d7183a85ea6b7a3050ba74bd61b7e14
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency logRelease files / quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl
| Download URL | quantfinlab-0.6.0-cp311-cp311-macosx_11_0_arm64.whl |
|---|---|
| Size | 817.0 kB |
| Tags | CPython 3.11 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
22e6beb42375e2a6e8b1a860c93e42545d66ce8149c52e497b08f4cc0358b3b3
|
|
BLAKE2b-256 checksum How to use checksums |
8b3bcd806e2933003d699d5b326c5228b2b061d804e86affd1013650f0936763
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 8, 2026.
Transparency log