Skip to main content

moru_quant/
error.rs

1//! The crate's error type, returned when an input fails validation at the
2//! API boundary.
3
4use std::fmt;
5
6/// An input rejected at the API boundary.
7///
8/// Every variant names the offending input and its value, or the derived
9/// quantity that is not representable, so the caller can report it.
10#[derive(Debug, Clone, Copy, PartialEq)]
11#[non_exhaustive]
12pub enum Error {
13    /// The input is `NaN` or infinite.
14    NotFinite {
15        /// Which input.
16        input: Input,
17        /// The value passed.
18        value: f64,
19    },
20    /// The input must be greater than zero.
21    NotPositive {
22        /// Which input.
23        input: Input,
24        /// The value passed.
25        value: f64,
26    },
27    /// The input must be zero or greater.
28    Negative {
29        /// Which input.
30        input: Input,
31        /// The value passed.
32        value: f64,
33    },
34    /// A probability is not strictly between `0` and `1`.
35    ProbabilityOutOfRange {
36        /// The value passed.
37        value: f64,
38    },
39    /// The inputs are individually valid but a quantity derived from them
40    /// is not a finite `f64` (for example `exp(−r·T)` for a large negative
41    /// `r·T`).
42    Overflow {
43        /// The derived quantity, as a formula.
44        quantity: &'static str,
45    },
46}
47
48/// A named input of a pricing function.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub enum Input {
52    /// Price of the underlying.
53    Spot,
54    /// Strike price.
55    Strike,
56    /// Continuously compounded risk-free rate.
57    Rate,
58    /// Continuously compounded cost of carry.
59    CostOfCarry,
60    /// Volatility of the underlying.
61    Volatility,
62    /// Time to expiry.
63    Time,
64}
65
66impl fmt::Display for Error {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::NotFinite { input, value } => {
70                write!(f, "{input} must be a finite number, got {value}")
71            }
72            Self::NotPositive { input, value } => {
73                write!(f, "{input} must be greater than zero, got {value}")
74            }
75            Self::Negative { input, value } => {
76                write!(f, "{input} must be zero or greater, got {value}")
77            }
78            Self::ProbabilityOutOfRange { value } => {
79                write!(
80                    f,
81                    "probability must be strictly between 0 and 1, got {value}"
82                )
83            }
84            Self::Overflow { quantity } => write!(
85                f,
86                "{quantity} is not a finite f64; check the input magnitudes and units \
87                 (prices in one currency, rates as annual decimals such as 0.05, \
88                 time in years)"
89            ),
90        }
91    }
92}
93
94impl std::error::Error for Error {}
95
96impl fmt::Display for Input {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(match self {
99            Self::Spot => "spot",
100            Self::Strike => "strike",
101            Self::Rate => "rate",
102            Self::CostOfCarry => "cost of carry",
103            Self::Volatility => "volatility",
104            Self::Time => "time",
105        })
106    }
107}
108
109/// `value` if it is finite.
110pub(crate) fn finite(input: Input, value: f64) -> Result<f64, Error> {
111    if value.is_finite() {
112        Ok(value)
113    } else {
114        Err(Error::NotFinite { input, value })
115    }
116}
117
118/// `value` if it is finite and greater than zero.
119pub(crate) fn positive(input: Input, value: f64) -> Result<f64, Error> {
120    if finite(input, value)? > 0.0 {
121        Ok(value)
122    } else {
123        Err(Error::NotPositive { input, value })
124    }
125}
126
127/// `value` if it is finite and zero or greater.
128pub(crate) fn non_negative(input: Input, value: f64) -> Result<f64, Error> {
129    if finite(input, value)? >= 0.0 {
130        Ok(value)
131    } else {
132        Err(Error::Negative { input, value })
133    }
134}