formal-mathfin
A library of mathematical finance in Lean 4, built on Mathlib and BrownianMotion. It covers stochastic calculus (the Itô integral, Itô's formula, Girsanov's theorem, martingale representation, stochastic differential equations), no-arbitrage theory, derivative pricing, fixed income, portfolio theory, risk measures and actuarial mathematics.
The corpus records 804 results from the literature in benchmarks/, each with a
Lean statement and proof. Of these, 766 are proved in full, 18 restate a lemma from Mathlib or
BrownianMotion, and 19 are reduced cores that prove less than the result they are named after.
Each entry records its status and what it leaves out. The library contains no sorry, and a
build-time audit checks that every library theorem the benchmark's proofs cite depends only on the
axioms propext, Classical.choice and Quot.sound.
Here, for example, is the convergence of the Cox–Ross–Rubinstein call price to the Black–Scholes
price, from CRRClosedForm.lean:
theorem binomialPrice_call_tendsto_bs_closed {r σ T S₀ K : ℝ}
(hσ : 0 < σ) (hT : 0 < T) (hS₀ : 0 < S₀) (hK : 0 < K)
(hna : ∀ n, 0 < n → BinomialNoArb (crrUp σ T n) (crrDown σ T n) (crrPerStepRate r T n)) :
Tendsto (fun n : ℕ ↦ binomialPrice (crrUp σ T n) (crrDown σ T n) (crrPerStepRate r T n)
(fun x ↦ max (x - K) 0) n S₀) atTop
(𝓝 (S₀ * Phi (bsd1 S₀ K r σ T)
- K * Real.exp (-(r * T)) * Phi (bsd2 S₀ K r σ T)))
The hypothesis hna, that the binomialNoArb_crr).
Main results
-
Itô's formula. For
with continuous , , and , and no growth condition, the process is a continuous local martingale for the augmented Brownian filtration ( ito_formula_unrestricted). For an Itô processwith continuous adapted coefficients and no bounds on them or on , almost surely, at every at once, and the stochastic integral has a version that is a continuous local martingale for the augmented Brownian filtration (
ito_formula_adapted_unbounded_process,exists_localMartingale_ito_formula). -
Lévy's characterization. A continuous adapted process
with such that and are local martingales for a filtration is an -Brownian motion ( isFilteredPreBrownian_of_localMartingale). -
Girsanov's theorem. For bounded predictable
and a horizon , let . Under the process (an adapted modification, which has the same finite-dimensional laws) is a Brownian motion for the Brownian filtration : it starts at , has increments, and each increment is independent of , on all of (past it moves as does, plus the drift frozen at ) ( Btheta_isFilteredPreBrownian_predictable_of_bdd). Ifhas continuous paths, so does the new process ( Btheta_isBrownianReal_predictable_of_bdd). The finite-dimensional laws onare Btheta_isQBrownianMotion_predictable_of_bdd. -
Martingale representation. Every square-integrable
-measurable is for a unique : each such claim is replicated from initial wealth by a unique strategy ( exists_replicating_strategy). -
Stochastic differential equations. For Lipschitz
and and any horizon , the Picard map of has a unique fixed point in the space of predictable processes on ( picardMap_exists_unique_fixedPoint_any_horizon). The Picard map is itself a contraction only when( picardMap_exists_unique_fixedPoint); for any horizon some iterate is, because the energy ofon decays like . The Black–Scholes path solves , almost surely at every at once ( pathAssets_solves_sde); it is not identified with the fixed point. -
Black–Scholes delta hedge. Let
be a Brownian motion with continuous paths, , the Black–Scholes call price with maturity , and . Almost surely, for all at once, with the delta ( bs_delta_hedge_replication): the discounted call value is its initial value, which is the call's contract value, plus the gains of holding the delta of shares (europeanCall_deltaHedge). At maturity,as along any path continuous at ( tendsto_bsV_gbm_payoff), stated separately: the integral identity is onwith . The portfolio of shares and the bank position is self-financing in the integral sense: on ( europeanCall_selfFinancing), where the gainis spelled as its drift and Brownian integrals, not as an integral against the semimartingale . The hedge is an integrand, not a strategy structure. -
Fundamental theorem of asset pricing. A discrete-time, finite-horizon market with one discounted risky asset on a finite probability space of full support has no arbitrage if and only if it has an equivalent martingale measure (
ftap_discrete); the one-period theorem holds on any probability space with finitely many assets (ftap_one_period_vector). On a general probability space, multi-period no arbitrage is equivalent to no arbitrage in each one-period market conditional on( noArbitrage_iff_noArbitrageLocal), and one-period densities with conditional mean one that make the price a conditional martingale paste into an equivalent martingale measure (LocalEMMDensities.isEMM_pastedMeasure); so the Dalang–Morton–Willinger theorem follows once conditional no arbitrage produces such a density, which is the hypothesisConditionalOnePeriodFTAP, not proved (noArbitrage_iff_exists_isEMM). In continuous time only the easy direction is proved: an equivalent martingale measure precludes arbitrage by simple strategies. -
Coherent risk measures. On a finite state space a coherent risk measure of losses is
, the supremum over the probability vectors that price every acceptable loss nonpositively ( coherentRisk_isLUB). It and the finite FTAP both come from the cone-separation lemmas inConvexDuality.lean. -
The Black–Scholes PDE from Feynman–Kac. The call price is a heat-kernel (Gaussian) integral of the payoff, and the PDE for the closed-form price follows from the heat equation for the kernel, without differentiating the closed form. This is the Gaussian-integral form of Feynman–Kac; no SDE enters (
bsV_satisfies_bs_pde_via_feynmanKac). -
Jump-diffusions. Let
be adapted, start at , and have increments over independent of the past and distributed as , with , and i.i.d. jumps of law , all independent. If and , the discounted price is a martingale exactly when ( JumpDiffusionProcess.martingale_iff). With Gaussian jumps and, at that drift and reading as the pricing measure, the conditional discounted payoff of the call at every date before maturity is Merton's 1976 series ( condExp_call_eq_mertonCallPrice). -
The American put. A bounded continuous supermartingale dominating the discounted reward bounds the value, and a stopping rule whose expected reward equals its initial value attains it (
value_eq_of_attained; a verification principle, the supermartingale is a hypothesis). Separately, for the value defined as the supremum over stopping times of the completed Brownian filtration, withand dividend yield , the early-exercise boundary is strictly convex in the time to expiry and is convex ( PhysicalBoundaryConvexity.lean,docs/american-put-boundary.md). -
Raw SVI. A fixed Boolean combination of polynomial signs in
holds exactly when , , the total variance is positive and the Black–Scholes call with the SVI volatility is convex in the strike (Durrleman's condition for ). With one more sign, , it holds exactly when that call is also nonincreasing, lies between and , and has the limits of a call price ( extendedCertificateFormula_iff_bsSmile_convex,butterflyFreeFormula_iff_isNormalizedCallPrice). -
Contracts, separate from models. Payoffs are terms of a contract language, priced by interchangeable models:
- the values of
europeanCall K Tin the-step CRR tree converge to its Black–Scholes value when ( tendsto_binomial_value_europeanCall); - in any model whose discounted price is a martingale from
, a call less a put is worth the forward, ( value_europeanCall_sub_put_of_martingale); - when the pricing measure makes the log-price Gaussian, the power call, the exchange option
(jointly Gaussian drivers) and the geometric Asian call (averaging over finitely many dates)
are worth their Black–Scholes closed forms, and the chooser's replicating portfolio is worth Rubinstein's
(
Contracts/Models/); - from the physical market, an asset
with a physical Brownian motion : under the Girsanov measure of the constant market price of risk at horizon , every fixed-dated contract observed in has the value it has on the risk-neutral asset at rate ( value_physical_eq_riskNeutral), so the call, the chooser and the geometric Asian call are worth the same Black–Scholes closed forms; the identification of the physical asset with the risk-neutral one is almost sure at each date; - the call's contract value is the initial capital of its delta hedge, as in the delta hedge
above
(
europeanCall_deltaHedge).
- the values of
-
Interest rates. In Vasicek and in Hull–White with continuous forcing, with the short rate and its time integral taken in their Wiener-integral representation and the Brownian measure read as the pricing measure, discounting by
: - the bond price at
is almost surely ( bondPrice_hullWhite); - the bond put is a Black put on the bond, which is lognormal under the forward measure
(Jamshidian), and a caplet is
such puts ( valueDisc_bondPut_hullWhite,valueDisc_caplet_eq_bondPut).
For any discount factor, a swap rate tied to the bonds by a model bundle gives:
- the payer swaption as
under the annuity measure; - the CMS swaplet as its forward value plus an exact covariance adjustment
(
valueDisc_payerSwaption,SwapModel.valueDisc_cmsSwaplet_eq).
In a Heath–Jarrow–Morton model bundle with short rate
, a schedule of fixed cash flows at is worth given a deterministic time- curve and the pricing hypothesis for the discount factor ( valueDisc_fixedFlows_hjm); that hypothesis is what the HJM drift condition delivers, and it is not proved. On a flat deterministic curve the value is unconditional (valueDisc_fixedFlows_hjm_flat). - the bond price at
Contents
| Area | Topics |
|---|---|
| Probability | conditional expectation, martingales and stopping times, Brownian motion, Poisson processes, Markov chains |
| Stochastic calculus | Itô integral and isometry, quadratic variation, Itô's formula, Girsanov's theorem, martingale representation, SDEs, Feynman–Kac, compensated Poisson integral |
| No-arbitrage | fundamental theorems, equivalent martingale measures, change of numéraire, market completeness, superreplication |
| Option pricing | Black–Scholes prices and Greeks, the Black–Scholes PDE, implied volatility, dividends, FX (Garman–Kohlhagen), Bachelier, Black-76, jump-diffusions (Merton's formula and Greeks, Esscher pricing, incompleteness at one date), Breeden–Litzenberger, a polynomial-sign certificate for strike-convexity of raw SVI |
| Exotic options | digital, exchange (Margrabe), chooser, barrier, lookback, geometric Asian, power and quanto options; spreads; variance swaps |
| Lattice models | binomial replication, American and Bermudan options via the Snell envelope, Cox–Ross–Rubinstein convergence, André's reflection principle |
| Fixed income and credit | bonds, duration and convexity, immunization, yield curves, forward rates, FRAs, swaps, caps and caplets, swaptions and CMS under the annuity measure, the forward measure, Vasicek, Hull–White and GSR, Jamshidian's bond options, hazard rates, CDS, CVA, first-to-default, KMV–Merton |
| Portfolio theory | Markowitz, CAPM, two-fund separation, the tangency portfolio, risk parity, Black–Litterman; Sharpe, Sortino, Treynor and information ratios; the Kelly criterion |
| Risk measures | the quantile function; value-at-risk and expected shortfall for every law: Rockafellar–Uryasev, coherence of ES, its dual representation, failure of VaR subadditivity (the exact range for independent defaults; infinite-mean Pareto), elicitability of VaR by the pinball loss and non-elicitability of ES, expectiles; coherent and spectral risk measures, expected utility, concentration indices |
| Dependence and extremes | copulas and Sklar's theorem (continuous margins), Fréchet–Hoeffding bounds, Hoeffding's covariance identity, Marshall–Olkin common shocks; GEV and GPD domains of attraction, maxima of Poisson-many losses |
| Credit portfolios | Bernoulli mixtures, the one-factor Gaussian threshold model, and the Basel IRB formula as the limit of portfolio VaR |
| Market microstructure | Avellaneda–Stoikov market making, the Glosten–Milgrom spread |
| Other | a contract language that separates payoffs from pricing models, with prices in Black–Scholes, the binomial tree and the Gaussian short-rate models; survival models, mortality and annuities; compound Poisson losses; constant-product AMMs |
Limitations
- Twenty of the 804 results are reduced cores. Eleven assume a structure whose fields include the textbook conclusion, so the conclusion is not derived: the reflection principle, nowhere differentiability and the law of the iterated logarithm for Brownian motion, Novikov's condition, the general form of Girsanov's theorem, the two-dimensional Itô formula, and five theorems on Markov chains. Two assume the conditional one-period fundamental theorem of asset pricing, the measurable-selection core of the Dalang–Morton–Willinger theorem: the theorem itself, and the put–call parity it gives in a discrete market. One assumes the bond-pricing identity of a Heath–Jarrow–Morton model, which the unproved drift condition would deliver: fixed cash flows in that model. The other six prove special cases: the first interarrival time of a Poisson process is exponential; Stulz's call on the maximum is checked only in its zero-strike limit, and the Heynen–Kat two-asset barrier only at zero correlation, neither formula being derived as an expected payoff; the Ornstein–Uhlenbeck Hermite modes decay at their eigenvalues only for degree at most 2; Haug's partial-time-start barrier and Rubinstein–Reiner's binary barrier are transcribed closed forms with proved identities between their terms, neither derived as an expected payoff (only the binary's vanilla leg is shown to be the digital call's price).
- Girsanov's theorem is proved only for bounded
(predictable, or adapted with continuous paths). Unbounded and Novikov's condition are among the reduced cores above. The measure is that of a fixed horizon and changes with : there is no single measure for all horizons, and past the new process is plus the frozen drift. - The second fundamental theorem is proved in both directions only for one risky asset on a finite
probability space of full support, with no arbitrage and full information at the horizon
(
): the market is complete if and only if its equivalent martingale measure is unique ( ftap_two); for the binomial tree this holds underBinomialNoArb(isCompleteMarket_horizonSpot_iff). In the Brownian market only the direction from completeness to uniqueness is proved: for a pricewith almost everywhere, a probability measure with square-integrable density with respect to , under which is a martingale, agrees with on . - Prices in the continuous-time models are discounted expectations under a pricing measure fixed by the model. Replication is proved in the binomial tree and, through martingale representation, for square-integrable claims on the Brownian filtration.
- Martingale representation proves that a hedge exists and is unique, but does not identify it; that needs the Clark–Ocone formula (#182, open).
- The SVI certificate's formula is defined structurally, not written out as a list of
inequalities. Butterfly-freeness is proved as a list of properties of the call price as a
function of the strike; the risk-neutral law is not constructed from them. At
convexity of the call is not tied to Durrleman's condition. - Itô's formula for an Itô process is proved on a finite horizon
, for a process built from a single Brownian motion with continuous adapted coefficients and a deterministic starting point. Itô's formula for a continuous semimartingale not built from is not proved, and neither is a quadratic-variation process for a general continuous local martingale, so Lévy's characterization asks that be a local martingale rather than that . - The jump-diffusion results on a process assume the properties listed above
(
JumpDiffusionProcess). A process with them is constructed only without jumps, as Brownian motion with drift. A change of measure on the process that alters the jump rate or the jump law is not covered. - The solution of an SDE with Lipschitz coefficients is a fixed point in the
space of predictable processes, not a process with continuous adapted paths, and pathwise uniqueness is not proved. That the Black–Scholes path solves its SDE is proved, but the path is not identified with the fixed point. - The binomial limit is proved for call prices and for the law of the terminal log-return. Convergence of the price process (Donsker's invariance principle) is not formalized.
- The multi-period fundamental theorem is proved without assumption on finite probability spaces
only. On a general space it rests on the unproved conditional one-period theorem (a measurable
selection of the one-period equivalent martingale measure over
), through the reduction and pasting above. The representation of coherent risk measures is proved on finite probability spaces only. - Bond options and caplets are priced in Vasicek and in Hull–White with continuous forcing, where the bond prices are derived from the Wiener-integral representation of the short rate. That this representation solves the short-rate SDE, and the swap of time integrals behind the integrated rate, are cited, not proved. Elsewhere the observed bond is a hypothesis of the model bundle, and so is the lognormality behind the Black-76 caplet and Black's swaption formula. The CMS adjustment is exact for payment at the fixing date. Its sign is proved only when every bond but the last is known at the fixing date. In the Heath–Jarrow–Morton bundle, the valuation of fixed cash flows is conditional on the bond-pricing hypothesis; the drift condition and the dynamics of the bonds are not proved.
Building
With elan installed:
git clone https://github.com/formal-applied-math/formal-mathfin.git
cd formal-mathfin
lake exe cache get # prebuilt Mathlib
lake build
To reproduce a release's claims in one command, run
scripts/reproduce.sh from a clone at its tag: it builds the library
(every proof, and the axiom pins below), then runs the repository's checks on the sources and the
corpus. scripts/reproduce.sh --corpus also re-checks every benchmark snippet against the library,
which takes hours on one machine.
lean-toolchain pins the Lean version and
lake-manifest.json pins Mathlib and BrownianMotion. BrownianMotion and the
library itself are compiled from source. CONTRIBUTING.md describes a prebuilt
Docker image and a faster edit-and-check loop for contributors.
Using the library in a project
Create a Lean project whose lean-toolchain matches the library's, and add the
dependency to its lakefile.toml:
[[require]]
name = "MathFin"
git = "https://github.com/formal-applied-math/formal-mathfin"
rev = "v1.10.0"
Then fetch it and the prebuilt Mathlib files:
lake update
lake exe cache get
lake build
and import it with import MathFin. Each release tag fixes the Lean toolchain, Mathlib and
BrownianMotion together; to follow main instead, use rev = "main" with the toolchain from that
revision. The first build compiles BrownianMotion and the library from source.
MathFinTest/Readme.lean is such a client: it imports only MathFin
and states the theorem quoted above, and a weekly workflow builds it in a fresh project that
requires this repository.
Verification
A successful lake build checks every proof in the library. The benchmark entries are not Lake
targets and are checked separately (see Benchmark below). In this repository, sorry appears only
in the two theorems of Challenge.lean, which are left unproved on purpose (see
Comparator below).
-
Axioms.
MathFin/AxiomAudit.leanand the generatedMathFin/AxiomAuditGen.leanrun#print axiomson a curated list of headline results and on every library constant that a benchmark entry's proof cites, and compare the output with#guard_msgs. Asorryor an extra axiom anywhere in the proof of one of them fails the build. Citations are found by where a name is declared, so a name cited underopen, by dot notation, or from a namespace other thanMathFinis covered. The Mathlib and BrownianMotion theorems thatlibrary_wrapperentries re-export are pinned too: BrownianMotion hassorrys of its own, and none of those theorems depends on one. -
Comparator.
Challenge.leanstates the coherent-risk representation theorem, with a witness that its hypothesis is satisfiable, using only Mathlib;Solution.leanproves both from the library, converting the Challenge's positions convention to the library's loss convention withisCoherentRiskMeasure_neg_iff. Lean's comparator (lake comparator), configured bycomparator.json, checks that the two files state the same theorems and that the proofs use only the three standard axioms. A workflow runs it with--paranoid, so the proofs must be accepted by every kernel bundled with Lean (Lean's default and paranoid kernels, lean4lean, nanoda, con-leche and con-ron), on changes to the pair and monthly; seedocs/palomar.md. -
Benchmark. Each entry in
benchmarks/records a result's Lean statement, its status and its scope. The ledger runner,tools/verify/ledger.py, checks each entry's snippet against the library, andverification_ledger.jsonstores a hash of the inputs it was checked under; CI fails if any entry's inputs have changed since. The entries are published as a Hugging Face dataset. -
Kernel replay. A monthly workflow replays every module's declarations through the Lean kernel with
leanchecker, below the elaborator. -
Provenance.
formalization.yamldescribes how the library was written, including AI assistance and the entries drafted by an automated pipeline. The American put port records its own provenance indocs/american-put-boundary.md.
Documentation
docs/beginners-manual.md: Lean and the library for mathematicians who have not used Lean, with exercises.docs/coverage.md: a dated log of status changes and corrections, with verification evidence.docs/blueprint.md: a dependency graph from Brownian motion to Black–Scholes, generated from the Lean source.docs/mathematical-architecture.md: the principles the library is organized around, and the theorems that connect them.MathFinExamples/Tour.lean: five representative proofs.MathFinExamples/Applications/: the library applied to concrete problems: a capped call, put–call parity on quotes, a binomial tree, a Gaussian risk report, a bootstrapped curve, default correlation in a credit pool and a minimum-variance portfolio. Each ends in one statement the build checks.docs/open-problems.md: a survey of open problems in mathematical finance.docs/status.md: where the program stands, and its backlog, the issue tracker.docs/roadmap.md: where it is going and why.docs/README.md: an index of the remaining documents.
Contributing
Contributions are welcome. CONTRIBUTING.md explains how to add a theorem, and
docs/onboarding.md walks through a first contribution. Issues labelled
good first issue
are the usual starting point.
Contributors
Raphael Coelho maintains the library, with contributions from:
- Godstime Aburu: the issue-label taxonomy.
- Alfredo Garcia: Glosten–Milgrom adverse selection, a drift term in the Itô-process price and the CIR bond loadings.
- Robert Martin: log-convexity of the American put exercise boundary.
- Aleksey Salkutsan: forward rate agreements and downside performance metrics.
- Mert Unsal: the Black–Scholes charm.
- Yang Ye: the integrated Itô–drift identity, Hull–White calibration, a Monte Carlo pricer, Cox credit, CMS rates and curve bootstrapping; the bivariate normal CDF, the Schwartz futures price, CVA, inflation, the LHP tranche loss, calendar arbitrage, joint elicitability, CreditMetrics, SA-CCR, two-asset options and DeFi lending and AMM mechanics.
Each module's header names its authors.
Citation
@article{coelho2026mathfin,
title = {A Formally Verified Library of Mathematical Finance in {Lean} 4},
author = {Coelho, Raphael},
journal = {arXiv preprint arXiv:2606.01356},
year = {2026},
doi = {10.48550/arXiv.2606.01356}
}
To cite the software itself, use the Zenodo DOI
10.5281/zenodo.20477781, which resolves to the latest
release. Both are in CITATION.cff.
Acknowledgements
The library depends on Mathlib and on BrownianMotion, the formalization of Brownian motion and
stochastic integration led by Rémy Degenne. The stochastic-processes part of the benchmark follows
Yuri F. Saporito's Stochastic Processes. The contract language takes its design ideas, but no
code, from Paul Bilokon's The Contract Is Not the Model (2026), and the survival models draw on
Yosuke Ito's Archive of Formal Proofs entry on actuarial mathematics
(docs/sources.md). The American put results are ported from Robert Martin's
AmericanPutConvexity, and the SVI
polynomial-sign certificate from his
ButterflyFreeSVI.
License
Apache 2.0. See LICENSE.