16th November 2026Research

Verifying a codebase for the pricing of interest rate options

All posts

We fully verified the mathematical validity of a Python codebase that implements the pricing algorithms for seven interest rate models. This post explains our agentic workflows to extract the mathematical specification, check the code against it, and automatically detect a historical QuantLib bug that has resisted discovery for more than 19 years.

The codebase

A 2,800-line Python library of nine classical interest-rate models, with a textbook behind it.

  • An open-source Python library, interest-rate-models, by Marwin Steiner: about 2,800 lines in nine modules, from Vasicek to the LIBOR market model.
  • It prices in closed form where it can, simulates where it cannot, and calibrates Vasicek and CIR to a market curve.
  • Around 140 tests, and documentation that cites Brigo–Mercurio [2] and the original papers.

GitHub repository

The documentation

108 mathematical items covering seven interest-rate models and their pricing algorithms.

  • 31 definitions, 74 theorems and 3 lemmas covering Vasicek, CIR, Ho–Lee, Hull–White, G2++, HJM and the LIBOR market model.
  • The specification includes discount curves, model dynamics, bond and option pricing, simulation schemes and calibration, with explicit assumptions and boundary cases.
  • All 108 items are formalised in Lean, and all 77 theorems and lemmas have completed proofs.

The QuantLib CIR++ bug

A missing shift term in bond-option pricing, corrected in QuantLib 1.25 (January 2022).

  • The CIR++ model’s discountBondOption routine omitted the deterministic-shift adjustment from the exercise boundary. The fix subtracts log(discountShift) in the numerator of that boundary.
  • Magnus Mencke authored the fix commit on 28 July 2021. It was merged on 7 January 2022 in pull request #1286.
  • The correction is recorded in the QuantLib 1.25 release notes (January 2022).

The collapsible panels on the left hand side contain high-level information on the sample code base of interest rate models that this blog post focuses on, the documentation we extracted from it, as well as the formalisation we have produced. The workflow we have developed applies more generally and we will now describe it in detail. A second blog post about the migration workflow will follow.

Extracting the documentation

The first part concerns the extraction of the documentation, see Figure 1 below of an overview.

Real-world codebases are often poorly or incompletely documented. For our workflow to be general, it therefore had to take into account the codebase itself as a source for the documentation without replicating potentially faulty or overly specific details of the implementation. This is guaranteed by a two-step agentic procedure that runs concurrently per item.

An extractor agent reads and extracts the documentation in natural language and tags the evidence according to a system of four tiers: DOC for documentation (incl. doc strings, should either exist),  TEST for unit tests, LIT  for literature references, and CODE-ONLY for the code itself.

An adversarial reviewer has no access to the code and reads only the extractor's output, i.e. is agnostic towards any implementation details. It challenges every item: Is it true? Is its evidence tag honest? Does it pass the "textbook test", i.e. could it be part of a self-contained model specification?  It also checks that every unit test which states a mathematical claim maps to an actual theorem.

Every disagreement between the two agents is logged and, together with the agreed upon spec items, send to the user for final approval. CODE-ONLY items always go to the person, whether or not the agents disagree. 

After approval and further (potentially agent-supported) edits, the natural language documentation gets send to the Logos platform. Based on LogosLib, a library of previously certified items curated and maintained by Logos, it then gets formalised in Lean 4, the formal programming language of our choice. Besides, mathematical theorems within it get formally proved without any user intervention. 

The eventual outcome is a certified spec in Lean which, in the verification step described below, serves as a source of contracts that (the Lean representation of) the code needs to satisfy. 

Specification extraction and formalisation: parallel extractors and reviewers, without code access for the reviewers, produce spec items and disputes; the user approves the items and settles the disputes; formalisation agents, drawing on LogosLib, hand each formalised item to prover agents, producing a certified specification in Lean
Figure 1. Extracting the documentation. Click to play the animation.

Example: Cox-Ingersoll-Ross model

This paragraph contains a sample of the extracted documentation obtained in the previously described procedure. It has been edited for presentational clarity.

In the Cox–Ingersoll–Ross (CIR) model (see  [1] and [2], §3.2.3),  the short rate xt follows the stochastic differential equation

\[ dx_t = \kappa(\theta - x_t)\,dt + \sigma\sqrt{x_t}\,dW_t \]

for suitable parameters \( \kappa, \theta, \sigma > 0 \), an initial value \( x_0 \ge 0 \), and a standard Brownian motion \( W \).

It is standard to overlay the model with a piecewise constant shift to match market prices. For simplicity, we will assume a constant shift s∈R and reproduce a historical QuantLib bug in the shifted model rt=xt+s which the Logos system detects.  

Zero-coupon bonds

A zero-coupon bond paying \( 1 \) at time \( T \) is worth, at time \( t \) 

\[ P_0(t,T) = A(\tau)\,e^{-B(\tau)\,x_t}, \quad \tau = T - t, \]

in the unshifted model (\( s = 0 \)), where the coefficients \( A \) and \( B \) depend only on \( \kappa, \theta, \sigma \) (see [2], §3.2.3). The shift only discounts by an extra e−sτ:

\[ P_s(t,T) = e^{-s\tau} A(\tau)\,e^{-B(\tau)\,x_t}, \qquad x_t = r_t - s . \]

The change is reflected in the following piece of code.

Code: the shifted bond pricecir.py:134–157
python
def bond_price(self, t: float, T: float, r: float | None = None) -> float:
    """Zero-coupon bond price P(t, T).

    Parameters
    ----------
    t : float
      Valuation time in years.
    T : float
      Bond maturity in years, T >= t.
    r : float, optional
      Short rate at t; defaults to the configured ``r0``.

    Returns
    -------
    float
      The bond price.
    """
    t, T = float(t), float(T)
    if T < t:
      raise ValueError("need T >= t")
    tau = T - t
    r = self._resolve_rate(r)
    # Introduced: the constant-shift model r(t) = x(t) + self.shift.
    x = r - self.shift
    # Updated: use x and discount by the extra factor exp(-self.shift * tau).
    return float(self._A(tau) * np.exp(-self._B(tau) * x - self.shift * tau))

Bond options and the exercise boundary

A European call with expiry \( T \) and strike \( K \) on the bond maturing at \( S > T \) pays \( \bigl(P(T,S) - K\bigr)^+ \).  Its price has a closed form (see [2], §3.2.3):

\[ \begin{aligned} \mathrm{ZBC}_0(t,T,S,K) = {}& P_0(t,S)\,\chi^2\bigl(2x^*\,[\rho+\psi+B(\tau_s)];\, d,\, \lambda_1\bigr) \\ &- K\,P_0(t,T)\,\chi^2\bigl(2x^*\,[\rho+\psi];\, d,\, \lambda_2\bigr), \end{aligned} \]

with τs=S−T, the notation χ2(⋅;d,λ) describes the noncentral chi-square distribution function, and ρ,ψ,d,λ1,λ2 are parameters as defined in Brigo–Mercurio [2]. The important quantity here is the exercise boundary x∗: the factor value at time T at which the bond is worth exactly the strike. Solving P0(T,S)=K gives 

\[ x^* = \frac{\ln\bigl(A(\tau_s)/K\bigr)}{B(\tau_s)} . \]

With a shift, the bond is worth the strike when \( e^{-s\tau_s} A(\tau_s)\,e^{-B(\tau_s)\,x} = K \), so the boundary moves:

\[ r^* = \frac{\ln\bigl(A(\tau_s)/K\bigr)\;\textcolor{#b42318}{\boldsymbol{-\;s\,\tau_s}}}{B(\tau_s)} . \tag{1} \]

The bond prices in the formula must be the shifted ones, and the boundary must be \( r^* \). 

The following piece of code highlights the missing shift term from equation (1) in red.

Code: the shifted bond option, ZBC and ZBPcir.py:159–222
python
def bond_option(
    self,
    T: float,
    S: float,
    strike: float,
    kind: str = "call",
    r: float | None = None,
) -> float:
    """European option, expiring at T, on a zero-coupon bond maturing at S.

    Priced at time 0 with the closed-form formula in terms of the
    noncentral chi-square distribution; see the model documentation
    page for the expression.

    Parameters
    ----------
    T : float
      Option expiry in years, positive.
    S : float
      Bond maturity in years, S > T.
    strike : float
      Strike price of the bond, positive.
    kind : {'call', 'put'}
      Option type.
    r : float, optional
      Short rate at time 0; defaults to the configured ``r0``.

    Returns
    -------
    float
      The option price.
    """
    T, S, strike = float(T), float(S), float(strike)
    if not 0.0 < T < S:
      raise ValueError("need 0 < T < S")
    if strike <= 0:
      raise ValueError("strike must be positive")
    if kind not in ("call", "put"):
      raise ValueError(f"kind must be 'call' or 'put', got {kind!r}")
    r = self._resolve_rate(r)
    x = r - self.shift

    h, k, s2 = self._h, self.kappa, self.sigma**2
    tau_s = S - T
    rho = 2.0 * h / (s2 * (np.exp(h * T) - 1.0))
    psi = (k + h) / s2
    B_ts = float(self._B(tau_s))
    A_ts = float(self._A(tau_s))
    r_star = (np.log(A_ts / strike) - self.shift * tau_s) / B_ts
    # ↑ missing: the shift term −s·τ_s of the boundary r*

    df = 4.0 * k * self.theta / s2
    nc_common = 2.0 * rho**2 * x * np.exp(h * T)

    p_T = self.bond_price(0.0, T, r)
    p_S = self.bond_price(0.0, S, r)
    call = p_S * ncx2_cdf(
      2.0 * r_star * (rho + psi + B_ts), df, nc_common / (rho + psi + B_ts)
    ) - strike * p_T * ncx2_cdf(
      2.0 * r_star * (rho + psi), df, nc_common / (rho + psi)
    )
    if kind == "call":
      return float(call)
    # put-call parity: ZBP = ZBC - P(0,S) + K P(0,T)
    return float(call - p_S + strike * p_T)

Codebase verification

Once a documentation for the codebase exists – either provided by the user a priori, or generated by Logos in the first step described above – the verification can begin.

At first, the codebase gets extracted into a blueprint which contains the internal Lean representation of the codebase at hand. It is then automatically enriched by verification contracts that its methods have to satisfy. Sources for such contracts can vary and comprise, for example, LogosLib, the (previously extracted) documentation, or further user input. Parallel verifier agents then prove those contracts autonomously or provide a counterexample in case they are not true. 

All of the previously described steps are handled by the Logos backend. The user only ever sees the result of those actions as reflected in their codebase, fully documented. 

the codebase is extracted automatically into a blueprint; contracts drawn from LogosLib, the certified specification and the user are attached, giving an enhanced blueprint; verification agents work on it in parallel and produce certificates and errors, which are linked back to a copy of the codebase with the lines concerned marked green or red
Figure 2. Verifying the code. Click to play the animation

A counterexample for shifted CIR

In the shifted CIR model with parameter \( s \) (see section above), for \( \tau_s = S-T \)the call-price is given by the following formula

\[ \begin{aligned} &\mathrm{Call}_s(T,S,K;\, r_0) = e^{-sS}\,\mathrm{ZBC}_0\bigl(T,S,K e^{s\tau_s};\, r_0 - s\bigr) . \end{aligned} \]

Take the following inputs, with shift \( s=1 \) and initial rate \( r_0=2 \), so that the unshifted factor starts at \( x_0=r_0-s=1 \):

\[ \begin{gathered} \kappa=\theta=\sigma=1,\quad T=1,\quad S=2,\\ K=A(1)/e\approx0.2593,\\ s=1,\quad r_0=2. \end{gathered} \]

For this shift, the bond price at expiry cannot exceed the strike, because \( x_1\ge0 \):

\[ \begin{aligned} P_1(1,2)&=e^{-1}A(1)e^{-B(1)x_1} \le e^{-1}A(1)=K. \end{aligned} \]

The call never pays out, so the contract requires a price of exactly \( 0 \). Evaluating the now faulty code instead gives:

\[ \mathrm{Call}_1(1,2,K;\,2)\approx-0.0114<0. \]

This negative price contradicts the required value of zero and therefore violates the contract that \( \mathrm{Call}_s(T,S,K;\, r_0) \ge 0 \). 

The Logos system also detects the reason for the violated contract and flags it in the codebase .

Literature

  1. J. C. Cox, J. E. Ingersoll, Jr., and S. A. Ross. A Theory of the Term Structure of Interest Rates. Econometrica, 53(2), 385–407, 1985. doi:10.2307/1911242
  2. D. Brigo and F. Mercurio. Interest Rate Models — Theory and Practice: With Smile, Inflation and Credit. Second edition. Springer, 2006. doi:10.1007/978-3-540-34604-3

Get in touch

Tell us about the system you want to migrate, verify or accelerate.