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
//! Generalized Black–Scholes–Merton price of European options, with a
//! continuously compounded cost of carry `b` (E. G. Haug, *The Complete
//! Guide to Option Pricing Formulas*, 2nd ed., McGraw-Hill, 2007, §1.1.6).
//!
//! ```text
//! call = S·e^((b−r)T)·N(d1) − K·e^(−rT)·N(d2)
//! put  = K·e^(−rT)·N(−d2) − S·e^((b−r)T)·N(−d1)
//! d1   = (ln(S/K) + (b + σ²/2)·T) / (σ·√T),   d2 = d1 − σ·√T
//! ```
//!
//! The choice of `b` selects the model:
//!
//! | Underlying | Cost of carry `b` |
//! |---|---|
//! | Non-dividend stock (Black–Scholes 1973) | `r` |
//! | Stock or index with dividend yield `q` (Merton 1973) | `r − q` |
//! | Futures (Black 1976) | `0` |
//! | Currency with foreign rate `r_f` (Garman–Kohlhagen 1983) | `r − r_f` |

use crate::analytic::OptionType;
use crate::error::{self, Error, Input};
use crate::math::normal;

/// Validated inputs of the generalized Black–Scholes–Merton formula.
///
/// Construction checks every input once; [`price`] then trusts them.
///
/// # Invariants
///
/// Spot and strike are finite and positive; rate and cost of carry are
/// finite; volatility and time are finite and non-negative; the discounted
/// spot `S·e^((b−r)T)`, the discounted strike `K·e^(−rT)`, the total
/// standard deviation `σ·√T` and `ln(S/K) + b·T` are finite.
///
/// # Units
///
/// Spot and strike in the same currency units; rate, cost of carry and
/// volatility annualized, as decimals (`0.05` for 5 %); time in years.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Inputs {
    discounted_spot: f64,
    discounted_strike: f64,
    log_moneyness: f64,
    std_dev: f64,
}

impl Inputs {
    /// Validates the inputs of the generalized Black–Scholes–Merton formula.
    ///
    /// # Errors
    ///
    /// - [`Error::NotFinite`] if any input is `NaN` or infinite;
    /// - [`Error::NotPositive`] if `spot` or `strike` is zero or negative;
    /// - [`Error::Negative`] if `volatility` or `time` is negative;
    /// - [`Error::Overflow`] if `S·e^((b−r)T)`, `K·e^(−rT)`, `σ·√T` or
    ///   `ln(S/K) + b·T` is not a finite `f64`.
    ///
    /// Inputs are checked in parameter order; the first failure is returned.
    ///
    /// # Units
    ///
    /// See [`Inputs`].
    ///
    /// # Examples
    ///
    /// ```
    /// use moru_quant::analytic::bsm::{self, Inputs};
    /// use moru_quant::analytic::OptionType;
    ///
    /// // Stock with a 5 % dividend yield: b = r − q.
    /// let (rate, dividend_yield) = (0.10, 0.05);
    /// let inputs = Inputs::new(100.0, 95.0, rate, rate - dividend_yield, 0.20, 0.5)?;
    /// let put = bsm::price(OptionType::Put, &inputs);
    /// assert!((put - 2.4648).abs() < 5e-5);
    /// # Ok::<(), moru_quant::Error>(())
    /// ```
    pub fn new(
        spot: f64,
        strike: f64,
        rate: f64,
        cost_of_carry: f64,
        volatility: f64,
        time: f64,
    ) -> Result<Self, Error> {
        let spot = error::positive(Input::Spot, spot)?;
        let strike = error::positive(Input::Strike, strike)?;
        let rate = error::finite(Input::Rate, rate)?;
        let cost_of_carry = error::finite(Input::CostOfCarry, cost_of_carry)?;
        let volatility = error::non_negative(Input::Volatility, volatility)?;
        let time = error::non_negative(Input::Time, time)?;

        let discounted_spot = derived(
            "spot·exp((b − r)·T)",
            spot * ((cost_of_carry - rate) * time).exp(),
        )?;
        let discounted_strike = derived("strike·exp(−r·T)", strike * (-rate * time).exp())?;
        let std_dev = derived("volatility·√T", volatility * time.sqrt())?;
        // ln(S/K) rather than ln S − ln K: no cancellation near the money.
        let log_moneyness = derived(
            "ln(spot/strike) + b·T",
            (spot / strike).ln() + cost_of_carry * time,
        )?;
        Ok(Self {
            discounted_spot,
            discounted_strike,
            log_moneyness,
            std_dev,
        })
    }
}

/// Generalized Black–Scholes–Merton price of a European option.
///
/// With zero volatility or zero time the price is the discounted intrinsic
/// value of the forward: `max(S·e^((b−r)T) − K·e^(−rT), 0)` for a call,
/// `max(K·e^(−rT) − S·e^((b−r)T), 0)` for a put.
///
/// The absolute error is within a few `f64::EPSILON · max(S·e^((b−r)T),
/// K·e^(−rT))`, inherited from [`normal::cdf`]; tests check published
/// values to their printed precision and put–call parity to `1e-12` of that
/// scale.
///
/// # Units
///
/// Currency units of [`Inputs`]' spot and strike.
///
/// # Examples
///
/// ```
/// use moru_quant::analytic::bsm::{self, Inputs};
/// use moru_quant::analytic::OptionType;
///
/// // Non-dividend stock: b = r.
/// let inputs = Inputs::new(60.0, 65.0, 0.08, 0.08, 0.30, 0.25)?;
/// let call = bsm::price(OptionType::Call, &inputs);
/// assert!((call - 2.1334).abs() < 5e-5);
/// # Ok::<(), moru_quant::Error>(())
/// ```
pub fn price(option_type: OptionType, inputs: &Inputs) -> f64 {
    let Inputs {
        discounted_spot,
        discounted_strike,
        log_moneyness,
        std_dev,
    } = *inputs;
    // σ·√T = 0 makes d1 = ±∞, or 0/0 at the forward; the limit is the
    // discounted intrinsic value.
    if std_dev <= 0.0 {
        return match option_type {
            OptionType::Call => (discounted_spot - discounted_strike).max(0.0),
            OptionType::Put => (discounted_strike - discounted_spot).max(0.0),
        };
    }
    let d1 = log_moneyness / std_dev + 0.5 * std_dev;
    let d2 = d1 - std_dev;
    // Each side uses N of its own d (not put–call parity) so that a small
    // price is not the difference of two large ones.
    match option_type {
        OptionType::Call => discounted_spot * normal::cdf(d1) - discounted_strike * normal::cdf(d2),
        OptionType::Put => {
            discounted_strike * normal::cdf(-d2) - discounted_spot * normal::cdf(-d1)
        }
    }
}

/// `value` if it is finite.
fn derived(quantity: &'static str, value: f64) -> Result<f64, Error> {
    if value.is_finite() {
        Ok(value)
    } else {
        Err(Error::Overflow { quantity })
    }
}