| Package | |
| Quality | |
| Documentation | |
| Code style | |
| Downloads | |
| Community | |
| Try it online |
See how the models of quantitative finance actually work. financialkit is a Python toolkit for learning and teaching quantitative finance: the time value of money, bonds and yield curves, option pricing, interest-rate and credit models, Monte Carlo and PDE methods, stochastic volatility, financial time series, risk, portfolios, asset pricing and market microstructure. No black boxes: every result is an inspectable dataclass, every domain ships plotting helpers, and each domain's docs walk through the field's breakthroughs in historical order, each one linked to runnable code that reproduces it.
Disclaimer. financialkit is educational and research software. It is not investment advice, and it is not a production pricing or risk system. Its examples use synthetic data, and nothing in it should be relied on for trading, valuation or regulatory decisions.
- For students: watch a binomial tree converge to Black-Scholes, see where the volatility smile comes from, and bootstrap a yield curve, all in a few lines each.
- For instructors: 14 domains, one consistent API, and over 200 gallery examples, each downloadable as a notebook or runnable in the browser, ready to hand out as course material.
- Built on numpy/scipy: production-grade library routines under the hood, with algorithms hand-written only where the steps themselves are what you're learning (see Design).
financialkit is part of a family of packages, with mathematicskit, physicskit and chemistrykit, that share the same architecture, API conventions and history-driven documentation.
pip install "financialkit[fast]" # with numba JIT acceleration (recommended)
pip install financialkit # pure numpy/scipy/matplotlib, e.g. for Pyodide/JupyterLiteThen import financialkit as fk. The fast extra adds
numba, which compiles the node-by-node loops
of the pde_methods solvers (PSOR, Brennan-Schwartz, Thomas), making
American options on a grid about 10-35x faster. Without it those kernels
run as plain Python: same results, slower. Everything else, including the
SDE schemes, is vectorised NumPy and runs at the same speed either way
(see the docs' Benchmarks page).
For development: pip install -e ".[dev]" (see CONTRIBUTING.md).
One European call, four pricers:
import financialkit as fk
S, K, T, r, sigma = 100.0, 95.0, 1.0, 0.05, 0.2
print(fk.options.black_scholes_price(S, K, T, r, sigma)) # 13.3465 closed form
print(fk.options.CRRTree(1000).price(S, K, T, r, sigma).price) # 13.3454 binomial tree
print(fk.pde_methods.CrankNicolson(400, 200).price(S, K, T, r, sigma).price) # 13.3441 finite differences
mc = fk.monte_carlo.european_option_mc(S, K, T, r, sigma, n_paths=200_000, rng=0)
print(mc.estimate, mc.std_error) # 13.361 +/- 0.036The quickstart notebook tours six domains in ten minutes. Open it in Colab using the badge above, or in the browser with JupyterLite.
Conventions are the same everywhere: time in years, rates and volatilities
as decimals, continuous compounding unless a parameter says otherwise, and
an rng argument (a numpy.random.Generator, a seed or None) on every
stochastic function.
Domain subpackages, grouped as in the docs, each with runnable examples linked below.
-
financialkit.time_value-- discrete and continuous compounding and equivalent rates, present value and NPV, annuities, perpetuities and life annuities, IRR (scipy.optimize.brentq, with a warning when the cash flows admit several roots) and MIRR, amortization schedules and the APR, sinking funds, and day counts, year fractions and accrued interest for everyDayCountconvention. -
financialkit.fixed_income-- bond prices, yields to maturity and STRIPS; Macaulay, modified, Fisher-Weil, effective and key rate durations and convexity; Redington immunization and the Fong-Vasicek bound; hand-written curve bootstrapping, McCulloch splines, and Nelson-Siegel and Svensson fits (scipy.optimize.least_squares); principal components of yield changes; interest rate and currency swaps; OIS discounting with separate forecasting curves and SOFR compounded in arrears; Treasury bond futures and the cheapest to deliver; and mortgage pass-throughs under the PSA prepayment benchmark.
-
financialkit.options-- Bachelier, Black-Scholes-Merton, Black-76 and Garman-Kohlhagen prices that broadcast over strikes and maturities; put-call parity and no-arbitrage bounds; analytic Greeks checked against finite differences, and delta hedging; implied volatility (a vectorized safeguarded Newton solver, after a bounds check), the smile and the Breeden-Litzenberger density; hand-written CRR, Rendleman-Bartter, Leisen-Reimer and trinomial trees with American exercise; and the Barone-Adesi-Whaley approximation. -
financialkit.exotic_options-- Merton and Reiner-Rubinstein barriers, double and discretely monitored barriers, binaries and one-touches, geometric (Kemna-Vorst) and arithmetic (Turnbull-Wakeman, Monte Carlo with a geometric control variate) Asians, lookbacks, variance swaps, Geske compounds, forward starts and choosers, Margrabe, Stulz and quanto options, and American options by Longstaff-Schwartz. -
financialkit.stochastic_volatility-- CEV and Dupire local volatility; Hull-White and Heston stochastic volatility; Merton, Kou and Bates jumps and variance gamma; Fourier pricing by Carr-Madan FFT (scipy.fft), Lewis and COS; SABR, SVI, arbitrage-free SSVI and Lee's moment formula; Heston simulation by full-truncation Euler and Andersen's QE scheme; and rough volatility: rough Bergomi by Cholesky or the hybrid scheme, and the roughness of volatility.
-
financialkit.monte_carlo-- crude Monte Carlo with standard errors and confidence intervals; stratification, importance sampling, antithetic, control and moment-matched variates, and Latin hypercubes; Halton and Sobol quasi-Monte Carlo (scipy.stats.qmc), randomized for error estimates, with discrepancy measures; pathwise and likelihood-ratio Greeks; and Giles's multilevel Monte Carlo. -
financialkit.pde_methods-- the Black-Scholes PDE by explicit, implicit and Crank-Nicolson schemes with Rannacher smoothing (scipy.sparseandscipy.linalg.solve_banded, plus a hand-written Thomas solver); CFL and von Neumann stability; Richardson extrapolation and Tavella-Randall grids; the heat-equation transform and the trinomial equivalence; American options by PSOR, Brennan-Schwartz and the penalty method; and two-factor Peaceman-Rachford ADI.
-
financialkit.interest_rate_models-- Merton, Vasicek and CIR short rates (with the Feller condition) and closed-form bonds checked against Monte Carlo throughintegrators; Ho-Lee, Hull-White, G2++ and Black-Derman-Toy fitted to afixed_incomecurve; Jamshidian bond options and swaptions; caps, floors and swaptions through theoptionsBlack-76; futures convexity adjustments; and the HJM drift condition. -
financialkit.credit-- Altman's Z-score; Merton, Black-Cox and Leland structural models and the KMV distance to default; hazard rates and survival curves; CDS pricing, upfronts and ISDA-style hazard bootstrapping; CreditMetrics migrations and generator matrices (scipy.linalg.expm); Vasicek's large pool and the Basel IRB formula; CreditRisk+ by Panjer recursion; Li's Gaussian copula; CDO tranches, the Andersen-Sidenius-Basu recursion and base correlation; and CVA, DVA and FVA from exposure profiles simulated by regression on Hull-White paths.
-
financialkit.portfolio-- Markowitz frontiers and the minimum-variance and tangency portfolios (closed forms, plusscipy.optimize.minimizewith constraints); Tobin's two-fund separation; Kelly and Merton's portfolio problem; CPPI; single-index and Ledoit-Wolf covariances; Black-Litterman and resampled frontiers; CVaR optimization (Rockafellar-Uryasev viascipy.optimize.linprog); maximum diversification, risk parity and hierarchical risk parity; and the Sharpe, Sortino and information ratios. -
financialkit.asset_pricing-- the dividend discount and Gordon growth models; Modigliani-Miller, WACC and Shiller's variance bound; the CAPM, the security market line, Jensen's alpha, the zero-beta CAPM and the GRS test; Fama-MacBeth and time-series factor regressions (numpy.linalg.lstsq) on synthetic Fama-French three- and five-factor and Carhart factors, with multiple-testing hurdles for the factor zoo; the APT; Hansen's GMM and the Hansen-Singleton Euler equation; Lucas's tree, the consumption CAPM, the Mehra-Prescott equity premium puzzle, Campbell-Cochrane habit and Bansal-Yaron long-run risk; the Campbell-Shiller log-linear present value; and state prices and the Hansen-Jagannathan bound.
-
financialkit.risk-- historical, parametric, Cornish-Fisher, Monte Carlo, hybrid and filtered historical VaR; Rouvinez's exact delta-gamma VaR and liquidity-adjusted VaR; expected shortfall, coherence checks, Euler allocation and the FRTB liquidity-horizon cascade; extreme value theory by block maxima and peaks over threshold (scipy.stats.genextreme/genpareto); Kupiec, Christoffersen and Basel traffic-light VaR backtests and Acerbi-Szekely ES backtests; Gaussian and t copulas and tail dependence; safety first; and drawdowns. -
financialkit.time_series-- returns and their stylized facts, fat tails and the Hill estimator; runs, Ljung-Box and Lo-MacKinlay variance-ratio tests; Yule-Walker and ARMA by conditional maximum likelihood with AIC order selection; the Dickey-Fuller test with MacKinnon critical values and Engle-Granger cointegration; the Hurst exponent; ARCH, GARCH, EGARCH and GJR by maximum likelihood (scipy.optimize.minimize) and RiskMetrics EWMA; and range-based and realized volatility. -
financialkit.market_microstructure-- quoted, effective and realized spreads; the Roll and Corwin-Schultz estimators; Lee-Ready and bulk-volume trade classification; Garman, Ho-Stoll and Avellaneda-Stoikov dealers; Kyle and Glosten-Milgrom; Hasbrouck's VAR; PIN and VPIN; square-root impact; Bertsimas-Lo and Almgren-Chriss optimal execution and Obizhaeva-Wang transient impact; Amihud illiquidity; and Hawkes order flow, the Cont-Stoikov-Talreja order book and order-flow imbalance.
Shared infrastructure, used across the subpackages above rather than standalone toolkits:
financialkit.integrators-- the shared SDE schemes: Euler-Maruyama and Milstein, exact GBM and Ornstein-Uhlenbeck sampling, the Brownian bridge, correlated (Cholesky), antithetic and Sobol (Brownian-bridge ordered) increments, and strong and weak convergence tests. Every domain that simulates paths calls it.financialkit.constants-- trading and calendar days per year, theDayCountenum and default numerical tolerances.
financialkit calls numpy/scipy directly for anything they already
implement (distributions, root finding, optimization, linear programming,
quadrature, FFTs, quasi-random sequences, sparse solvers and matrix
exponentials), and hand-writes an algorithm only where no numpy/scipy
equivalent exists (binomial and trinomial trees, Longstaff-Schwartz, curve
bootstrapping, PSOR, the ARMA and GARCH likelihoods, the ADF test with
MacKinnon critical values, Ledoit-Wolf shrinkage) or where the iteration
itself is the lesson. There is no dependency on pandas, statsmodels,
scikit-learn, arch or QuantLib, and nothing touches the network: every
example runs on seeded synthetic data. Path simulation lives in one place,
financialkit.integrators, and each shared model has one implementation
(Black-76 lives in options, year fractions in time_value).
The public API follows the stability and deprecation policy.
Tests live alongside each subpackage, at financialkit/<name>/tests/.
pytest # everything
pytest financialkit/options/tests # a single subpackage
# docstring examples, across every subpackage:
MPLBACKEND=Agg pytest --doctest-modules financialkit --ignore-glob="*/tests/*"Monte Carlo tests are seeded and assert agreement within a few standard
errors; deterministic tests check closed forms, parity relations and
published values from Hull, Haug and the original papers. Both commands,
plus ruff check/ruff format --check and mypy, run in CI on every PR
(.github/workflows/ci.yml) across Python 3.10-3.15 on Linux and macOS.
See CONTRIBUTING.md before opening a PR.
MPLBACKEND=Agg pytest -q --cov=financialkit --cov-report=
NUMBA_DISABLE_JIT=1 MPLBACKEND=Agg pytest -q --cov=financialkit --cov-append --cov-report=termCoverage cannot trace @njit-compiled code, so the kernel bodies are only
covered by the second run, where they execute as plain Python. CI does the
same: the numba and no-numba jobs both upload to Codecov, which merges them.
The no-numba run alone reaches every line, so CI's no-numba job runs with
--cov-fail-under=100 and fails if any line goes untested. The one
exclusion is the HAS_NUMBA = True branch of financialkit/_jit.py, which
only runs when numba is installed.
Built docs are hosted at https://cpoli.github.io/financialkit/, served from
the gh-pages branch. To build locally:
pip install -e ".[docs]"
cd docs && make htmlFive tutorials follow one problem across several domains: One option, five pricers, The yield curve, end to end, Where the smile comes from, From returns to risk and Credit risk, from one firm to a portfolio.
See docs/source/history/ for a chronology of each domain's breakthroughs,
from Fibonacci's present values to VPIN, each linked to the code that
reproduces it.
If you use financialkit in your research, please cite it; see CITATION.cff. Each release is archived on Zenodo with its own DOI; version 0.2.0 is 10.5281/zenodo.23795067.
See CONTRIBUTING.md. Please note that this project follows the Contributor Covenant.
MIT -- see LICENSE.














