quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Analytic Black-Scholes-Merton European option pricing engine with exact AD Greeks.

use crate::instruments::option::{EuropeanOption, OptionType};
use crate::math::autodiff::{Dual64, HyperDual64};
use crate::math::distributions::normal_cdf;
use crate::termstructures::process::GeneralizedBlackScholesProcess;
use crate::time::day_counter::DayCounter;
use crate::time::day_counters::actual_365_fixed::Actual365Fixed;
use thiserror::Error;

/// Pricing errors for option valuation.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum PricingError {
    /// Calculation resulted in non-finite value (NaN or Inf).
    #[error("Non-finite pricing result")]
    NonFinite,
    /// Underlying spot or volatility was non-positive.
    #[error("Invalid parameter: spot={spot}, vol={vol}")]
    InvalidParameter {
        /// Spot price
        spot: f64,
        /// Volatility
        vol: f64,
    },
}

/// Greeks sensitivities for European options.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Greeks {
    /// Delta ($\Delta = \frac{\partial V}{\partial S}$): sensitivity to spot price
    pub delta: f64,
    /// Gamma ($\Gamma = \frac{\partial^2 V}{\partial S^2}$): second derivative with respect to spot
    pub gamma: f64,
    /// Vega ($\mathcal{V} = \frac{\partial V}{\partial \sigma}$): sensitivity to volatility
    pub vega: f64,
    /// Theta ($\Theta = -\frac{\partial V}{\partial T}$): sensitivity to time decay (per year)
    pub theta: f64,
    /// Rho ($\rho = \frac{\partial V}{\partial r}$): sensitivity to risk-free interest rate
    pub rho: f64,
    /// Dividend Rho ($\rho_q = \frac{\partial V}{\partial q}$): sensitivity to dividend yield
    pub dividend_rho: f64,
}

/// Analytic European option pricing engine using the Black-Scholes-Merton model.
///
/// # Examples
/// ```
/// use quantlib_rs::engines::analytic_european_engine::AnalyticEuropeanEngine;
/// use quantlib_rs::instruments::option::{EuropeanOption, OptionType};
/// use quantlib_rs::termstructures::process::GeneralizedBlackScholesProcess;
/// use quantlib_rs::time::date::{Date, Month};
///
/// let today = Date::from_ymd(2026, Month::September, 3).unwrap();
/// let maturity = Date::from_ymd(2027, Month::September, 3).unwrap();
///
/// let process = GeneralizedBlackScholesProcess::new(100.0, 0.05, 0.02, 0.20, today);
/// let engine = AnalyticEuropeanEngine::new(process);
///
/// let call = EuropeanOption::new(OptionType::Call, 100.0, maturity);
/// let npv = engine.calculate(&call).unwrap();
/// let greeks = engine.calculate_greeks(&call).unwrap();
///
/// assert!(npv > 0.0);
/// assert!(greeks.delta > 0.0 && greeks.delta < 1.0);
/// assert!(greeks.gamma > 0.0);
/// assert!(greeks.vega > 0.0);
/// ```
#[derive(Clone)]
pub struct AnalyticEuropeanEngine {
    process: GeneralizedBlackScholesProcess,
}

impl AnalyticEuropeanEngine {
    /// Create a new analytic European pricing engine for the given process.
    pub const fn new(process: GeneralizedBlackScholesProcess) -> Self {
        Self { process }
    }

    /// Return a reference to the underlying process.
    pub const fn process(&self) -> &GeneralizedBlackScholesProcess {
        &self.process
    }

    /// Calculate the Net Present Value (NPV) of a European option.
    pub fn calculate(&self, option: &EuropeanOption) -> Result<f64, PricingError> {
        let s = self.process.spot();
        let k = option.strike();
        let ref_date = self.process.reference_date();
        let mat_date = option.maturity_date();

        let dc = Actual365Fixed;
        let t = dc.year_fraction(ref_date, mat_date);

        if t <= 0.0 {
            return Ok(option.payoff(s));
        }

        let r = self.process.risk_free_rate().zero_rate(t);
        let q = self.process.dividend_yield().zero_rate(t);
        let vol = self.process.black_vol().black_vol(t, k);

        if s <= 0.0 || vol <= 0.0 {
            return Err(PricingError::InvalidParameter { spot: s, vol });
        }

        let price = black_scholes_price(option.option_type(), s, k, t, r, q, vol);
        if price.is_finite() {
            Ok(price)
        } else {
            Err(PricingError::NonFinite)
        }
    }

    /// Calculate exact Greeks using forward-mode automatic differentiation.
    pub fn calculate_greeks(&self, option: &EuropeanOption) -> Result<Greeks, PricingError> {
        let s = self.process.spot();
        let k = option.strike();
        let ref_date = self.process.reference_date();
        let mat_date = option.maturity_date();

        let dc = Actual365Fixed;
        let t = dc.year_fraction(ref_date, mat_date);

        if t <= 0.0 {
            return Ok(Greeks::default());
        }

        let r = self.process.risk_free_rate().zero_rate(t);
        let q = self.process.dividend_yield().zero_rate(t);
        let vol = self.process.black_vol().black_vol(t, k);

        if s <= 0.0 || vol <= 0.0 {
            return Err(PricingError::InvalidParameter { spot: s, vol });
        }

        // 1. Exact Delta and Gamma via HyperDual64 on Spot
        let s_hd = HyperDual64::variable(s);
        let price_hd = black_scholes_hyperdual(option.option_type(), s_hd, k, t, r, q, vol);
        let delta = price_hd.der1;
        let gamma = price_hd.der12;

        // 2. Exact Vega via Dual64 on Volatility
        let vol_dual = Dual64::variable(vol);
        let vega = black_scholes_dual_vol(option.option_type(), s, k, t, r, q, vol_dual).der;

        // 3. Exact Rho via Dual64 on Rate
        let r_dual = Dual64::variable(r);
        let rho = black_scholes_dual_rate(option.option_type(), s, k, t, r_dual, q, vol).der;

        // 4. Exact Dividend Rho via Dual64 on Dividend
        let q_dual = Dual64::variable(q);
        let dividend_rho =
            black_scholes_dual_div(option.option_type(), s, k, t, r, q_dual, vol).der;

        // 5. Exact Theta via Dual64 on Time to maturity (Theta = -dV/dT)
        let t_dual = Dual64::variable(t);
        let theta = -black_scholes_dual_time(option.option_type(), s, k, t_dual, r, q, vol).der;

        Ok(Greeks {
            delta,
            gamma,
            vega,
            theta,
            rho,
            dividend_rho,
        })
    }

    /// Calculate Greeks using central finite-difference bumps (for independent validation).
    pub fn calculate_greeks_bumped(
        &self,
        option: &EuropeanOption,
        bump_s: f64,
        bump_vol: f64,
        bump_r: f64,
        bump_t: f64,
    ) -> Result<Greeks, PricingError> {
        let s = self.process.spot();
        let k = option.strike();
        let ref_date = self.process.reference_date();
        let mat_date = option.maturity_date();

        let dc = Actual365Fixed;
        let t = dc.year_fraction(ref_date, mat_date);

        let r = self.process.risk_free_rate().zero_rate(t);
        let q = self.process.dividend_yield().zero_rate(t);
        let vol = self.process.black_vol().black_vol(t, k);

        let opt_type = option.option_type();

        // Spot bump: Delta & Gamma
        let p_up = black_scholes_price(opt_type, s + bump_s, k, t, r, q, vol);
        let p_down = black_scholes_price(opt_type, s - bump_s, k, t, r, q, vol);
        let p_mid = black_scholes_price(opt_type, s, k, t, r, q, vol);

        let delta = (p_up - p_down) / (2.0 * bump_s);
        let gamma = (p_up - 2.0 * p_mid + p_down) / (bump_s * bump_s);

        // Volatility bump: Vega
        let p_vol_up = black_scholes_price(opt_type, s, k, t, r, q, vol + bump_vol);
        let p_vol_down = black_scholes_price(opt_type, s, k, t, r, q, vol - bump_vol);
        let vega = (p_vol_up - p_vol_down) / (2.0 * bump_vol);

        // Rate bump: Rho
        let p_r_up = black_scholes_price(opt_type, s, k, t, r + bump_r, q, vol);
        let p_r_down = black_scholes_price(opt_type, s, k, t, r - bump_r, q, vol);
        let rho = (p_r_up - p_r_down) / (2.0 * bump_r);

        // Dividend bump: Dividend Rho
        let p_q_up = black_scholes_price(opt_type, s, k, t, r, q + bump_r, vol);
        let p_q_down = black_scholes_price(opt_type, s, k, t, r, q - bump_r, vol);
        let dividend_rho = (p_q_up - p_q_down) / (2.0 * bump_r);

        // Time bump: Theta = -dV/dT
        let p_t_up = black_scholes_price(opt_type, s, k, t + bump_t, r, q, vol);
        let p_t_down = black_scholes_price(opt_type, s, k, (t - bump_t).max(1e-6), r, q, vol);
        let theta = -(p_t_up - p_t_down) / (2.0 * bump_t);

        Ok(Greeks {
            delta,
            gamma,
            vega,
            theta,
            rho,
            dividend_rho,
        })
    }
}

/// Closed-form Black-Scholes-Merton option pricing formula.
pub fn black_scholes_price(
    option_type: OptionType,
    spot: f64,
    strike: f64,
    t: f64,
    rate: f64,
    dividend: f64,
    vol: f64,
) -> f64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = vol * sqrt_t;

    let d1 = ((spot / strike).ln() + (rate - dividend + 0.5 * vol * vol) * t) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (-rate * t).exp();
    let df_q = (-dividend * t).exp();

    match option_type {
        OptionType::Call => spot * df_q * normal_cdf(d1) - strike * df_r * normal_cdf(d2),
        OptionType::Put => strike * df_r * normal_cdf(-d2) - spot * df_q * normal_cdf(-d1),
    }
}

fn black_scholes_hyperdual(
    option_type: OptionType,
    spot: HyperDual64,
    strike: f64,
    t: f64,
    rate: f64,
    dividend: f64,
    vol: f64,
) -> HyperDual64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = vol * sqrt_t;

    let log_ratio = (spot / strike).ln();
    let drift = (rate - dividend + 0.5 * vol * vol) * t;
    let d1 = (log_ratio + drift) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (-rate * t).exp();
    let df_q = (-dividend * t).exp();

    match option_type {
        OptionType::Call => spot * df_q * d1.normal_cdf() - d2.normal_cdf() * (strike * df_r),
        OptionType::Put => {
            HyperDual64::from(strike * df_r) * (-d2).normal_cdf() - spot * df_q * (-d1).normal_cdf()
        }
    }
}

fn black_scholes_dual_vol(
    option_type: OptionType,
    spot: f64,
    strike: f64,
    t: f64,
    rate: f64,
    dividend: f64,
    vol: Dual64,
) -> Dual64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = vol * sqrt_t;

    let log_term = (spot / strike).ln();
    let drift = (rate - dividend) * t;
    let half_vol2_t = vol * vol * (0.5 * t);
    let d1 = (half_vol2_t + (log_term + drift)) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (-rate * t).exp();
    let df_q = (-dividend * t).exp();

    match option_type {
        OptionType::Call => d1.normal_cdf() * (spot * df_q) - d2.normal_cdf() * (strike * df_r),
        OptionType::Put => {
            (-d2).normal_cdf() * (strike * df_r) - (-d1).normal_cdf() * (spot * df_q)
        }
    }
}

fn black_scholes_dual_rate(
    option_type: OptionType,
    spot: f64,
    strike: f64,
    t: f64,
    rate: Dual64,
    dividend: f64,
    vol: f64,
) -> Dual64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = vol * sqrt_t;

    let log_term = (spot / strike).ln();
    let drift = (rate - dividend) * t;
    let half_vol2_t = 0.5 * vol * vol * t;
    let d1 = (drift + (log_term + half_vol2_t)) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (rate * (-t)).exp();
    let df_q = (-dividend * t).exp();

    match option_type {
        OptionType::Call => d1.normal_cdf() * (spot * df_q) - d2.normal_cdf() * (df_r * strike),
        OptionType::Put => {
            (-d2).normal_cdf() * (df_r * strike) - (-d1).normal_cdf() * (spot * df_q)
        }
    }
}

fn black_scholes_dual_div(
    option_type: OptionType,
    spot: f64,
    strike: f64,
    t: f64,
    rate: f64,
    dividend: Dual64,
    vol: f64,
) -> Dual64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = vol * sqrt_t;

    let log_term = (spot / strike).ln();
    let drift = (Dual64::constant(rate) - dividend) * t;
    let half_vol2_t = 0.5 * vol * vol * t;
    let d1 = (drift + (log_term + half_vol2_t)) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (-rate * t).exp();
    let df_q = (dividend * (-t)).exp();

    match option_type {
        OptionType::Call => d1.normal_cdf() * (df_q * spot) - d2.normal_cdf() * (strike * df_r),
        OptionType::Put => {
            (-d2).normal_cdf() * (strike * df_r) - (-d1).normal_cdf() * (df_q * spot)
        }
    }
}

fn black_scholes_dual_time(
    option_type: OptionType,
    spot: f64,
    strike: f64,
    t: Dual64,
    rate: f64,
    dividend: f64,
    vol: f64,
) -> Dual64 {
    let sqrt_t = t.sqrt();
    let vol_sqrt_t = sqrt_t * vol;

    let log_term = (spot / strike).ln();
    let drift = t * (rate - dividend + 0.5 * vol * vol);
    let d1 = (drift + log_term) / vol_sqrt_t;
    let d2 = d1 - vol_sqrt_t;

    let df_r = (t * (-rate)).exp();
    let df_q = (t * (-dividend)).exp();

    match option_type {
        OptionType::Call => d1.normal_cdf() * (df_q * spot) - d2.normal_cdf() * (df_r * strike),
        OptionType::Put => {
            (-d2).normal_cdf() * (df_r * strike) - (-d1).normal_cdf() * (df_q * spot)
        }
    }
}