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
//! The crate's error type, returned when an input fails validation at the
//! API boundary.

use std::fmt;

/// An input rejected at the API boundary.
///
/// Every variant names the offending input and its value, or the derived
/// quantity that is not representable, so the caller can report it.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// The input is `NaN` or infinite.
    NotFinite {
        /// Which input.
        input: Input,
        /// The value passed.
        value: f64,
    },
    /// The input must be greater than zero.
    NotPositive {
        /// Which input.
        input: Input,
        /// The value passed.
        value: f64,
    },
    /// The input must be zero or greater.
    Negative {
        /// Which input.
        input: Input,
        /// The value passed.
        value: f64,
    },
    /// A probability is not strictly between `0` and `1`.
    ProbabilityOutOfRange {
        /// The value passed.
        value: f64,
    },
    /// The inputs are individually valid but a quantity derived from them
    /// is not a finite `f64` (for example `exp(−r·T)` for a large negative
    /// `r·T`).
    Overflow {
        /// The derived quantity, as a formula.
        quantity: &'static str,
    },
}

/// A named input of a pricing function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Input {
    /// Price of the underlying.
    Spot,
    /// Strike price.
    Strike,
    /// Continuously compounded risk-free rate.
    Rate,
    /// Continuously compounded cost of carry.
    CostOfCarry,
    /// Volatility of the underlying.
    Volatility,
    /// Time to expiry.
    Time,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFinite { input, value } => {
                write!(f, "{input} must be a finite number, got {value}")
            }
            Self::NotPositive { input, value } => {
                write!(f, "{input} must be greater than zero, got {value}")
            }
            Self::Negative { input, value } => {
                write!(f, "{input} must be zero or greater, got {value}")
            }
            Self::ProbabilityOutOfRange { value } => {
                write!(
                    f,
                    "probability must be strictly between 0 and 1, got {value}"
                )
            }
            Self::Overflow { quantity } => write!(
                f,
                "{quantity} is not a finite f64; check the input magnitudes and units \
                 (prices in one currency, rates as annual decimals such as 0.05, \
                 time in years)"
            ),
        }
    }
}

impl std::error::Error for Error {}

impl fmt::Display for Input {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Spot => "spot",
            Self::Strike => "strike",
            Self::Rate => "rate",
            Self::CostOfCarry => "cost of carry",
            Self::Volatility => "volatility",
            Self::Time => "time",
        })
    }
}

/// `value` if it is finite.
pub(crate) fn finite(input: Input, value: f64) -> Result<f64, Error> {
    if value.is_finite() {
        Ok(value)
    } else {
        Err(Error::NotFinite { input, value })
    }
}

/// `value` if it is finite and greater than zero.
pub(crate) fn positive(input: Input, value: f64) -> Result<f64, Error> {
    if finite(input, value)? > 0.0 {
        Ok(value)
    } else {
        Err(Error::NotPositive { input, value })
    }
}

/// `value` if it is finite and zero or greater.
pub(crate) fn non_negative(input: Input, value: f64) -> Result<f64, Error> {
    if finite(input, value)? >= 0.0 {
        Ok(value)
    } else {
        Err(Error::Negative { input, value })
    }
}