Skip to content

About

Quantitative-finance toolkit for learning and teaching: options, fixed income, rates, credit, Monte Carlo, PDE, stochastic volatility, risk, portfolios -- built on numpy/scipy.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

financialkit

Package PyPI version Python versions DOI
Quality License CI Coverage
Documentation Docs
Code style Ruff
Downloads Downloads Downloads/Month
Community GitHub Stars GitHub Forks Contributors Last Commit
Try it online Open in Colab JupyterLite

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.

A binomial tree converging to Black-Scholes, Heston smiles and skews, and the efficient frontier, all drawn with financialkit

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

Install

pip install "financialkit[fast]"   # with numba JIT acceleration (recommended)
pip install financialkit           # pure numpy/scipy/matplotlib, e.g. for Pyodide/JupyterLite

Then 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).

Quick start

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

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

Subpackages

Domain subpackages, grouped as in the docs, each with runnable examples linked below.

Foundations

  • 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 every DayCount convention.

    Compounding toward e, an NPV profile with two IRRs, and a mortgage amortization schedule

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

    The price-yield curve of a bond, a Nelson-Siegel zero curve, and yield-curve principal components

Derivatives

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

    Black-Scholes call values, the Greeks of a call, and implied volatility smiles

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

    GBM paths knocked out by a double barrier, Merton's down-and-out call, and the Longstaff-Schwartz exercise boundary

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

    Heston volatility paths, Heston smiles by vol of vol, and Dupire local volatility

Numerical Methods

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

    Sobol points, quasi-Monte Carlo error convergence, and Monte Carlo option prices with error bars

  • financialkit.pde_methods -- the Black-Scholes PDE by explicit, implicit and Crank-Nicolson schemes with Rannacher smoothing (scipy.sparse and scipy.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.

    A Crank-Nicolson value surface, von Neumann amplification factors, and the PSOR exercise boundary

Rates & Credit

  • financialkit.interest_rate_models -- Merton, Vasicek and CIR short rates (with the Feller condition) and closed-form bonds checked against Monte Carlo through integrators; Ho-Lee, Hull-White, G2++ and Black-Derman-Toy fitted to a fixed_income curve; Jamshidian bond options and swaptions; caps, floors and swaptions through the options Black-76; futures convexity adjustments; and the HJM drift condition.

    Vasicek yield curves, mean-reverting short-rate paths, and a Black-Derman-Toy tree

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

    A survival curve bootstrapped from CDS spreads, a CreditRisk+ loss distribution, and a rating transition matrix

Portfolios & Asset Pricing

  • financialkit.portfolio -- Markowitz frontiers and the minimum-variance and tangency portfolios (closed forms, plus scipy.optimize.minimize with 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 via scipy.optimize.linprog); maximum diversification, risk parity and hierarchical risk parity; and the Sharpe, Sortino and information ratios.

    Risk-parity weights, the most diversified portfolio, and CPPI wealth paths

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

    The security market line, the Hansen-Jagannathan bound, and Shiller's excess volatility

Risk & Markets

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

    Monte Carlo VaR of a straddle book, a VaR backtest, and a t copula

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

    Power-law tails of returns, GARCH conditional volatility, and the autocorrelation of squared returns

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

    Almgren-Chriss liquidation trajectories, Glosten-Milgrom quotes, and Avellaneda-Stoikov market making

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, the DayCount enum and default numerical tolerances.

Design

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.

Test

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.

Coverage

MPLBACKEND=Agg pytest -q --cov=financialkit --cov-report=
NUMBA_DISABLE_JIT=1 MPLBACKEND=Agg pytest -q --cov=financialkit --cov-append --cov-report=term

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

Docs

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 html

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

Citation

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.

Contributing

See CONTRIBUTING.md. Please note that this project follows the Contributor Covenant.

License

MIT -- see LICENSE.

About

Quantitative-finance toolkit for learning and teaching: options, fixed income, rates, credit, Monte Carlo, PDE, stochastic volatility, risk, portfolios -- built on numpy/scipy.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages