moru-quant 0.1.0

Rust library for quantitative finance and derivatives valuation: option pricing, implied volatility, Greeks, yield curves, and finite-difference / Monte Carlo engines.
Documentation
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Generate the standard normal reference vectors in this directory.

Reference values are computed in arbitrary-precision decimal arithmetic
(Python standard library only), independently of the Rust implementation:

- Phi(x) = 1/2 + phi(x) * sum_{n>=0} x^(2n+1) / (1*3*5*...*(2n+1)),
  the Taylor series of the normal CDF (Abramowitz & Stegun 26.2.11), with a
  working precision large enough to absorb its cancellation for x < 0.
- Cross-check: for |x| >= 3 the lower tail is recomputed with the Laplace
  continued fraction Q(x) = phi(x) / (x + 1/(x + 2/(x + 3/(x + ...))))
  (Abramowitz & Stegun 26.2.14); the script aborts if the two methods differ
  in the first OUTPUT_DIGITS significant digits.
- Inverse CDF: Newton iteration on the series above until the step is below
  10^-(OUTPUT_DIGITS + 10) relative to max(|x|, 1); for |x| >= 3 the result is cross-checked
  by evaluating the tail at x with the continued fraction, which must match
  the input tail probability to 10^-OUTPUT_DIGITS relative.
- PDF: the closed form exp(-x^2/2) / sqrt(2 pi), with no second method.

Every input is an exact binary64 value, so each reference is the correctly
rounded result for exactly that input. Run from the repository root with
`just vectors`, or directly:

    uv run crates/moru-quant/tests/vectors/normal.py
"""

import decimal
import math
import os
from decimal import Decimal as D

WORKING_DIGITS = 1000
OUTPUT_DIGITS = 25
CF_TERMS = 4000

decimal.getcontext().prec = WORKING_DIGITS

CDF_INPUTS = [
    -37.5, -37.0, -30.0, -25.5, -20.0, -12.75, -8.0, -5.7, -5.65, -4.0,
    -2.5, -1.0, -0.7, -0.66, -0.25, -1e-10,
    1e-10, 0.25, 0.66, 0.7, 1.0, 1.96, 2.5, 4.0, 5.65, 5.7, 8.0, 8.5, 10.0,
    # Inputs whose square is not a binary64 number: they expose the rounding
    # error of a naive exp(-x*x/2) in both approximation regions.
    -37.3, -33.33, -26.1, -19.7, -13.7, -6.3, -5.3, -4.9, -3.7,
]

INVERSE_INPUTS = [
    5e-324, 1e-310, 2.2250738585072014e-308, 1e-300, 1e-100, 1e-20, 1e-12,
    1e-10, 1e-3, 0.07, 0.075, 0.08, 0.25, 0.4999999999, 0.6, 0.9, 0.925,
    0.93, 0.999, 1.0 - 1e-10, 0.9999999999999999,
]


def pi():
    # Machin: pi = 16 atan(1/5) - 4 atan(1/239).
    def atan_inv(n):
        total, term, k, n2 = D(0), D(1) / n, 0, n * n
        while term != 0:
            total += term / (2 * k + 1) if k % 2 == 0 else -term / (2 * k + 1)
            term /= n2
            k += 1
        return total

    return 16 * atan_inv(5) - 4 * atan_inv(239)


INV_SQRT_2PI = 1 / (2 * pi()).sqrt()


def pdf(x):
    return INV_SQRT_2PI * (-(x * x) / 2).exp()


def cdf_series(x):
    total, term, n = D(0), x, 0
    x2 = x * x
    while abs(term) > D(10) ** (-WORKING_DIGITS + 10) * abs(total + term):
        total += term
        n += 1
        term = term * x2 / (2 * n + 1)
    return D(1) / 2 + pdf(x) * total


def lower_tail_cf(y):
    """Q(y) for y > 0 by the Laplace continued fraction."""
    acc = y
    for k in range(CF_TERMS, 0, -1):
        acc = y + k / acc
    return pdf(y) / acc


def significant(v):
    return format(v, f".{OUTPUT_DIGITS - 1}e")


def check_cdf(x, value):
    if abs(x) < 3:
        return
    tail = lower_tail_cf(abs(x))
    other = tail if x < 0 else 1 - tail
    if significant(+other) != significant(+value):
        raise SystemExit(f"methods disagree at x={x!r}: {value} vs {other}")


def inverse(p):
    target = D(p)
    x = D(start_guess(p))
    while True:
        step = (cdf_series(x) - target) / pdf(x)
        x -= step
        if abs(step) <= D(10) ** -(OUTPUT_DIGITS + 10) * max(abs(x), D(1)):
            check_inverse(p, x)
            return x


def check_inverse(p, x):
    if abs(x) < 3:
        return
    expected_tail = D(p) if x < 0 else 1 - D(p)
    tail = lower_tail_cf(abs(x))
    if abs(tail - expected_tail) > D(10) ** -OUTPUT_DIGITS * expected_tail:
        raise SystemExit(f"methods disagree at p={p!r}: tail {tail} vs {expected_tail}")


def start_guess(p):
    # Rational approximation A&S 26.2.23 (|error| < 4.5e-4); any start in the
    # basin of attraction will do, Newton refines it.
    tail = min(p, 1.0 - p)
    t = math.sqrt(-2.0 * math.log(tail))
    guess = t - (2.515517 + 0.802853 * t + 0.010328 * t * t) / (
        1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t ** 3
    )
    return -guess if p < 0.5 else guess


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(here, "normal_cdf.txt"), "w") as out:
        out.write(
            "# Standard normal PDF and CDF at exact binary64 inputs.\n"
            f"# {OUTPUT_DIGITS} significant digits; generated by normal.py in"
            " this directory\n"
            "# (Taylor series A&S 26.2.11, cross-checked against the"
            " continued fraction A&S 26.2.14 for |x| >= 3).\n"
            "# x  pdf(x)  cdf(x)\n"
        )
        for xf in CDF_INPUTS:
            x = D(xf)
            value = cdf_series(x)
            check_cdf(x, value)
            out.write(f"{xf!r} {significant(+pdf(x))} {significant(+value)}\n")
    with open(os.path.join(here, "normal_inverse_cdf.txt"), "w") as out:
        out.write(
            "# Standard normal inverse CDF at exact binary64 probabilities.\n"
            f"# {OUTPUT_DIGITS} significant digits; generated by normal.py in"
            " this directory\n"
            "# (Newton iteration on the Taylor series A&S 26.2.11, cross-checked against\n"
            "# the continued fraction A&S 26.2.14 for |x| >= 3).\n"
            "# p  inverse_cdf(p)\n"
        )
        for p in INVERSE_INPUTS:
            out.write(f"{p!r} {significant(+inverse(p))}\n")


if __name__ == "__main__":
    main()