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
//! `analytic::bsm` against published examples, limits and put–call parity.

use std::error::Error as StdError;

use moru_quant::analytic::OptionType;
use moru_quant::analytic::bsm::{self, Inputs};
use moru_quant::{Error, Input};

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

/// Relative tolerance of put–call parity, as a fraction of
/// `max(S·e^((b−r)T), K·e^(−rT))`.
const PARITY_TOLERANCE: f64 = 1e-12;

/// Absolute tolerance of the zero-volatility and zero-time limits.
const LIMIT_TOLERANCE: f64 = 1e-12;

/// A published example: inputs, option type, printed price and the
/// half-unit of its last printed digit.
struct Published {
    source: &'static str,
    inputs: (f64, f64, f64, f64, f64, f64),
    option_type: OptionType,
    price: f64,
    half_unit: f64,
}

/// Inputs are `(S, K, r, b, σ, T)`.
const PUBLISHED: [Published; 6] = [
    Published {
        // Haug (2007), §1.1.1 Black–Scholes: b = r.
        source: "Haug §1.1.1",
        inputs: (60.0, 65.0, 0.08, 0.08, 0.30, 0.25),
        option_type: OptionType::Call,
        price: 2.1334,
        half_unit: 5e-5,
    },
    Published {
        // Haug (2007), §1.1.2 Merton, dividend yield q = 0.05: b = r − q.
        source: "Haug §1.1.2",
        inputs: (100.0, 95.0, 0.10, 0.05, 0.20, 0.5),
        option_type: OptionType::Put,
        price: 2.4648,
        half_unit: 5e-5,
    },
    Published {
        // Haug (2007), §1.1.3 Black-76 on a futures price: b = 0.
        source: "Haug §1.1.3",
        inputs: (19.0, 19.0, 0.10, 0.0, 0.28, 0.75),
        option_type: OptionType::Call,
        price: 1.7011,
        half_unit: 5e-5,
    },
    Published {
        // Haug (2007), §1.1.5 Garman–Kohlhagen, r_f = 0.08: b = r − r_f.
        source: "Haug §1.1.5",
        inputs: (1.56, 1.60, 0.06, -0.02, 0.12, 0.5),
        option_type: OptionType::Call,
        price: 0.0291,
        half_unit: 5e-5,
    },
    Published {
        // Hull, Options, Futures, and Other Derivatives, 9th ed., Example 15.6.
        source: "Hull Example 15.6 (call)",
        inputs: (42.0, 40.0, 0.10, 0.10, 0.20, 0.5),
        option_type: OptionType::Call,
        price: 4.76,
        half_unit: 5e-3,
    },
    Published {
        source: "Hull Example 15.6 (put)",
        inputs: (42.0, 40.0, 0.10, 0.10, 0.20, 0.5),
        option_type: OptionType::Put,
        price: 0.81,
        half_unit: 5e-3,
    },
];

fn inputs(values: (f64, f64, f64, f64, f64, f64)) -> Result<Inputs, Error> {
    let (spot, strike, rate, carry, volatility, time) = values;
    Inputs::new(spot, strike, rate, carry, volatility, time)
}

#[test]
fn test_price_matches_published_examples() -> TestResult {
    for example in &PUBLISHED {
        let price = bsm::price(example.option_type, &inputs(example.inputs)?);
        assert!(
            (price - example.price).abs() <= example.half_unit,
            "{}: got {price}, published {}",
            example.source,
            example.price
        );
    }
    Ok(())
}

/// Made-up inputs covering in / at / out of the money, negative rates,
/// negative carry and long expiries.
const GRID_SPOTS: [f64; 5] = [50.0, 90.0, 100.0, 110.0, 200.0];
const GRID_RATES: [f64; 3] = [-0.01, 0.0, 0.07];
const GRID_CARRIES: [f64; 3] = [-0.03, 0.0, 0.05];
const GRID_VOLATILITIES: [f64; 3] = [0.01, 0.25, 1.5];
const GRID_TIMES: [f64; 3] = [1.0 / 365.0, 1.0, 30.0];
const GRID_STRIKE: f64 = 100.0;

#[test]
fn test_put_call_parity() -> TestResult {
    for spot in GRID_SPOTS {
        for rate in GRID_RATES {
            for carry in GRID_CARRIES {
                for volatility in GRID_VOLATILITIES {
                    for time in GRID_TIMES {
                        let inputs = Inputs::new(spot, GRID_STRIKE, rate, carry, volatility, time)?;
                        let call = bsm::price(OptionType::Call, &inputs);
                        let put = bsm::price(OptionType::Put, &inputs);
                        let forward_value = spot * ((carry - rate) * time).exp();
                        let strike_value = GRID_STRIKE * (-rate * time).exp();
                        let scale = forward_value.max(strike_value);
                        let gap = (call - put) - (forward_value - strike_value);
                        assert!(
                            gap.abs() <= PARITY_TOLERANCE * scale,
                            "S={spot} r={rate} b={carry} σ={volatility} T={time}: gap {gap:e}"
                        );
                        assert!(call >= 0.0 && put >= 0.0, "negative price at S={spot}");
                    }
                }
            }
        }
    }
    Ok(())
}

#[test]
fn test_zero_volatility_gives_discounted_intrinsic_value() -> TestResult {
    let (strike, time) = (100.0, 2.0);
    // The last case is S = K with b = 0, so ln(S/K) + b·T is exactly 0 and,
    // without the σ·√T = 0 branch, d1 would be 0/0.
    for (spot, rate, carry) in [(120.0, 0.05, 0.02), (80.0, 0.05, 0.02), (100.0, 0.03, 0.0)] {
        let inputs = Inputs::new(spot, strike, rate, carry, 0.0, time)?;
        let forward_value = spot * ((carry - rate) * time).exp();
        let strike_value = strike * (-rate * time).exp();
        let call = bsm::price(OptionType::Call, &inputs);
        let put = bsm::price(OptionType::Put, &inputs);
        let expected_call = (forward_value - strike_value).max(0.0);
        let expected_put = (strike_value - forward_value).max(0.0);
        assert!(
            (call - expected_call).abs() <= LIMIT_TOLERANCE,
            "call at S={spot}: {call}"
        );
        assert!(
            (put - expected_put).abs() <= LIMIT_TOLERANCE,
            "put at S={spot}: {put}"
        );
    }
    Ok(())
}

#[test]
fn test_zero_time_gives_intrinsic_value() -> TestResult {
    let strike = 100.0;
    for spot in [80.0, 100.0, 120.0] {
        let inputs = Inputs::new(spot, strike, 0.05, 0.02, 0.3, 0.0)?;
        let call = bsm::price(OptionType::Call, &inputs);
        let put = bsm::price(OptionType::Put, &inputs);
        let expected_call = f64::max(spot - strike, 0.0);
        let expected_put = f64::max(strike - spot, 0.0);
        assert!(
            (call - expected_call).abs() <= LIMIT_TOLERANCE,
            "call at S={spot}: {call}"
        );
        assert!(
            (put - expected_put).abs() <= LIMIT_TOLERANCE,
            "put at S={spot}: {put}"
        );
    }
    Ok(())
}

#[test]
fn test_new_rejects_invalid_inputs() {
    let valid = [100.0, 100.0, 0.05, 0.05, 0.2, 1.0];
    let cases = [
        (0, f64::NAN, Input::Spot, "not finite"),
        (0, f64::INFINITY, Input::Spot, "not finite"),
        (0, 0.0, Input::Spot, "not positive"),
        (0, -1.0, Input::Spot, "not positive"),
        (1, f64::NEG_INFINITY, Input::Strike, "not finite"),
        (1, 0.0, Input::Strike, "not positive"),
        (2, f64::NAN, Input::Rate, "not finite"),
        (3, f64::INFINITY, Input::CostOfCarry, "not finite"),
        (4, f64::NAN, Input::Volatility, "not finite"),
        (4, -0.2, Input::Volatility, "negative"),
        (5, f64::INFINITY, Input::Time, "not finite"),
        (5, -1.0, Input::Time, "negative"),
    ];
    for (index, bad, input, kind) in cases {
        let mut v = valid;
        v[index] = bad;
        let result = Inputs::new(v[0], v[1], v[2], v[3], v[4], v[5]);
        let matched = match (kind, result) {
            ("not finite", Err(Error::NotFinite { input: i, value })) => {
                i == input && value.to_bits() == bad.to_bits()
            }
            ("not positive", Err(Error::NotPositive { input: i, value })) => {
                i == input && value.to_bits() == bad.to_bits()
            }
            ("negative", Err(Error::Negative { input: i, value })) => {
                i == input && value.to_bits() == bad.to_bits()
            }
            _ => false,
        };
        assert!(matched, "{input} = {bad}: expected {kind}, got {result:?}");
    }
}

#[test]
fn test_new_rejects_overflowing_derived_quantities() {
    let cases = [
        // exp((b − r)·T) overflows.
        (100.0, 100.0, 0.0, 1000.0, 0.2, 1.0, "spot·exp((b − r)·T)"),
        // exp(−r·T) overflows.
        (100.0, 100.0, -1000.0, -1000.0, 0.2, 1.0, "strike·exp(−r·T)"),
        // σ·√T overflows.
        (100.0, 100.0, 0.0, 0.0, 1e300, 1e30, "volatility·√T"),
        // ln(S/K) + b·T overflows while b − r and r stay harmless.
        (
            100.0,
            100.0,
            1e300,
            1e300,
            0.2,
            1e10,
            "ln(spot/strike) + b·T",
        ),
    ];
    for (spot, strike, rate, carry, volatility, time, expected) in cases {
        let result = Inputs::new(spot, strike, rate, carry, volatility, time);
        assert!(
            matches!(result, Err(Error::Overflow { quantity }) if quantity == expected),
            "expected overflow of {expected}, got {result:?}"
        );
    }
}

#[test]
fn test_error_display_names_input_and_value() {
    let message = Error::Negative {
        input: Input::Volatility,
        value: -0.2,
    }
    .to_string();
    assert!(
        message.contains("volatility") && message.contains("-0.2"),
        "{message}"
    );
    let message = Error::NotFinite {
        input: Input::CostOfCarry,
        value: f64::NAN,
    }
    .to_string();
    assert!(
        message.contains("cost of carry") && message.contains("NaN"),
        "{message}"
    );
}