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
//! `math::normal` against the 25-digit reference vectors in `tests/vectors/`
//! (generated by `tests/vectors/normal.py`; method and sources in its
//! docstring) and against the distribution's invariants.

use std::error::Error as StdError;

use moru_quant::Error;
use moru_quant::math::normal;

/// Relative tolerance of the reference comparisons (`math::normal` docs).
const RELATIVE_TOLERANCE: f64 = 1e-14;

const CDF_VECTORS: &str = include_str!("vectors/normal_cdf.txt");
const INVERSE_CDF_VECTORS: &str = include_str!("vectors/normal_inverse_cdf.txt");

type TestResult = Result<(), Box<dyn StdError>>;

/// Rows of a vector file: whitespace-separated numbers, `#` comment lines.
fn rows(text: &str) -> Result<Vec<Vec<f64>>, Box<dyn StdError>> {
    let mut out = Vec::new();
    for line in text
        .lines()
        .filter(|l| !l.starts_with('#') && !l.trim().is_empty())
    {
        let row = line
            .split_whitespace()
            .map(str::parse::<f64>)
            .collect::<Result<Vec<_>, _>>()?;
        out.push(row);
    }
    Ok(out)
}

fn relative_error(actual: f64, expected: f64) -> f64 {
    ((actual - expected) / expected).abs()
}

#[test]
fn test_pdf_and_cdf_match_reference_vectors() -> TestResult {
    let rows = rows(CDF_VECTORS)?;
    assert!(rows.len() > 20, "vector file truncated");
    for row in rows {
        let [x, pdf, cdf] = row[..] else {
            return Err(format!("malformed row {row:?}").into());
        };
        let pdf_error = relative_error(normal::pdf(x), pdf);
        let cdf_error = relative_error(normal::cdf(x), cdf);
        assert!(
            pdf_error <= RELATIVE_TOLERANCE,
            "pdf({x}): relative error {pdf_error:e}"
        );
        assert!(
            cdf_error <= RELATIVE_TOLERANCE,
            "cdf({x}): relative error {cdf_error:e}"
        );
    }
    Ok(())
}

#[test]
fn test_inverse_cdf_matches_reference_vectors() -> TestResult {
    let rows = rows(INVERSE_CDF_VECTORS)?;
    assert!(rows.len() > 15, "vector file truncated");
    for row in rows {
        let [p, x] = row[..] else {
            return Err(format!("malformed row {row:?}").into());
        };
        let error = relative_error(normal::inverse_cdf(p)?, x);
        assert!(
            error <= RELATIVE_TOLERANCE,
            "inverse_cdf({p}): relative error {error:e}"
        );
    }
    Ok(())
}

#[test]
fn test_cdf_symmetry() {
    // Φ(x) + Φ(−x) = 1, with both halves from different code paths for x ≠ 0.
    for i in 0..=1000 {
        let x = f64::from(i) * 0.01;
        let sum = normal::cdf(x) + normal::cdf(-x);
        assert!(
            (sum - 1.0).abs() <= 2.0 * f64::EPSILON,
            "x = {x}: sum {sum}"
        );
    }
}

#[test]
fn test_cdf_monotone_across_region_boundaries() {
    // A fine grid over every approximation region, including the switches
    // at |x| = 0.66291 and |x| = sqrt(32), and the underflow cut-off.
    let mut previous = 0.0;
    for i in 0..=50_000 {
        let x = -40.5 + f64::from(i) * 0.001;
        let value = normal::cdf(x);
        assert!(
            value >= previous,
            "cdf decreases at x = {x}: {previous} -> {value}"
        );
        previous = value;
    }
}

#[test]
fn test_cdf_and_pdf_special_values() {
    assert!(normal::cdf(f64::NAN).is_nan());
    assert!(normal::pdf(f64::NAN).is_nan());
    assert!(normal::cdf(f64::NEG_INFINITY) <= 0.0);
    assert!(normal::cdf(-f64::MAX) <= 0.0);
    assert!(normal::cdf(f64::INFINITY) >= 1.0);
    assert!(normal::cdf(f64::MAX) >= 1.0);
    assert!(normal::pdf(f64::INFINITY) <= 0.0);
    assert!(normal::pdf(-f64::MAX) <= 0.0);
    assert!((normal::cdf(0.0) - 0.5).abs() <= f64::EPSILON);
    // Φ(−38) ≈ 2.9e-316: subnormal, so it must underflow gradually, not to 0.
    let deep = normal::cdf(-38.0);
    assert!(
        deep > 0.0 && deep < f64::MIN_POSITIVE,
        "cdf(-38) = {deep:e}"
    );
}

#[test]
fn test_inverse_cdf_round_trip_through_cdf() -> TestResult {
    // Two independent algorithms (Cody, Wichura) agree. The lower half only:
    // above 1/2, Φ(x) rounds to a coarse grid near 1 and loses x.
    for i in 1..=740 {
        let x = -f64::from(i) * 0.05;
        let back = normal::inverse_cdf(normal::cdf(x))?;
        assert!(
            (back - x).abs() <= 1e-13 * x.abs(),
            "x = {x}: round trip {back}"
        );
    }
    Ok(())
}

#[test]
fn test_inverse_cdf_rejects_probabilities_outside_open_unit_interval() {
    for p in [
        0.0,
        -0.0,
        1.0,
        -0.5,
        1.5,
        f64::NAN,
        f64::INFINITY,
        f64::NEG_INFINITY,
    ] {
        let result = normal::inverse_cdf(p);
        assert!(
            matches!(result, Err(Error::ProbabilityOutOfRange { value }) if value.to_bits() == p.to_bits()),
            "inverse_cdf({p}) returned {result:?}"
        );
    }
}

#[test]
fn test_inverse_cdf_central_point() -> TestResult {
    assert!(normal::inverse_cdf(0.5)?.abs() <= f64::EPSILON);
    Ok(())
}