Skip to main content

moru_quant/analytic/
bsm.rs

1//! Generalized Black–Scholes–Merton price of European options, with a
2//! continuously compounded cost of carry `b` (E. G. Haug, *The Complete
3//! Guide to Option Pricing Formulas*, 2nd ed., McGraw-Hill, 2007, §1.1.6).
4//!
5//! ```text
6//! call = S·e^((b−r)T)·N(d1) − K·e^(−rT)·N(d2)
7//! put  = K·e^(−rT)·N(−d2) − S·e^((b−r)T)·N(−d1)
8//! d1   = (ln(S/K) + (b + σ²/2)·T) / (σ·√T),   d2 = d1 − σ·√T
9//! ```
10//!
11//! The choice of `b` selects the model:
12//!
13//! | Underlying | Cost of carry `b` |
14//! |---|---|
15//! | Non-dividend stock (Black–Scholes 1973) | `r` |
16//! | Stock or index with dividend yield `q` (Merton 1973) | `r − q` |
17//! | Futures (Black 1976) | `0` |
18//! | Currency with foreign rate `r_f` (Garman–Kohlhagen 1983) | `r − r_f` |
19
20use crate::analytic::OptionType;
21use crate::error::{self, Error, Input};
22use crate::math::normal;
23
24/// Validated inputs of the generalized Black–Scholes–Merton formula.
25///
26/// Construction checks every input once; [`price`] then trusts them.
27///
28/// # Invariants
29///
30/// Spot and strike are finite and positive; rate and cost of carry are
31/// finite; volatility and time are finite and non-negative; the discounted
32/// spot `S·e^((b−r)T)`, the discounted strike `K·e^(−rT)`, the total
33/// standard deviation `σ·√T` and `ln(S/K) + b·T` are finite.
34///
35/// # Units
36///
37/// Spot and strike in the same currency units; rate, cost of carry and
38/// volatility annualized, as decimals (`0.05` for 5 %); time in years.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct Inputs {
41    discounted_spot: f64,
42    discounted_strike: f64,
43    log_moneyness: f64,
44    std_dev: f64,
45}
46
47impl Inputs {
48    /// Validates the inputs of the generalized Black–Scholes–Merton formula.
49    ///
50    /// # Errors
51    ///
52    /// - [`Error::NotFinite`] if any input is `NaN` or infinite;
53    /// - [`Error::NotPositive`] if `spot` or `strike` is zero or negative;
54    /// - [`Error::Negative`] if `volatility` or `time` is negative;
55    /// - [`Error::Overflow`] if `S·e^((b−r)T)`, `K·e^(−rT)`, `σ·√T` or
56    ///   `ln(S/K) + b·T` is not a finite `f64`.
57    ///
58    /// Inputs are checked in parameter order; the first failure is returned.
59    ///
60    /// # Units
61    ///
62    /// See [`Inputs`].
63    ///
64    /// # Examples
65    ///
66    /// ```
67    /// use moru_quant::analytic::bsm::{self, Inputs};
68    /// use moru_quant::analytic::OptionType;
69    ///
70    /// // Stock with a 5 % dividend yield: b = r − q.
71    /// let (rate, dividend_yield) = (0.10, 0.05);
72    /// let inputs = Inputs::new(100.0, 95.0, rate, rate - dividend_yield, 0.20, 0.5)?;
73    /// let put = bsm::price(OptionType::Put, &inputs);
74    /// assert!((put - 2.4648).abs() < 5e-5);
75    /// # Ok::<(), moru_quant::Error>(())
76    /// ```
77    pub fn new(
78        spot: f64,
79        strike: f64,
80        rate: f64,
81        cost_of_carry: f64,
82        volatility: f64,
83        time: f64,
84    ) -> Result<Self, Error> {
85        let spot = error::positive(Input::Spot, spot)?;
86        let strike = error::positive(Input::Strike, strike)?;
87        let rate = error::finite(Input::Rate, rate)?;
88        let cost_of_carry = error::finite(Input::CostOfCarry, cost_of_carry)?;
89        let volatility = error::non_negative(Input::Volatility, volatility)?;
90        let time = error::non_negative(Input::Time, time)?;
91
92        let discounted_spot = derived(
93            "spot·exp((b − r)·T)",
94            spot * ((cost_of_carry - rate) * time).exp(),
95        )?;
96        let discounted_strike = derived("strike·exp(−r·T)", strike * (-rate * time).exp())?;
97        let std_dev = derived("volatility·√T", volatility * time.sqrt())?;
98        // ln(S/K) rather than ln S − ln K: no cancellation near the money.
99        let log_moneyness = derived(
100            "ln(spot/strike) + b·T",
101            (spot / strike).ln() + cost_of_carry * time,
102        )?;
103        Ok(Self {
104            discounted_spot,
105            discounted_strike,
106            log_moneyness,
107            std_dev,
108        })
109    }
110}
111
112/// Generalized Black–Scholes–Merton price of a European option.
113///
114/// With zero volatility or zero time the price is the discounted intrinsic
115/// value of the forward: `max(S·e^((b−r)T) − K·e^(−rT), 0)` for a call,
116/// `max(K·e^(−rT) − S·e^((b−r)T), 0)` for a put.
117///
118/// The absolute error is within a few `f64::EPSILON · max(S·e^((b−r)T),
119/// K·e^(−rT))`, inherited from [`normal::cdf`]; tests check published
120/// values to their printed precision and put–call parity to `1e-12` of that
121/// scale.
122///
123/// # Units
124///
125/// Currency units of [`Inputs`]' spot and strike.
126///
127/// # Examples
128///
129/// ```
130/// use moru_quant::analytic::bsm::{self, Inputs};
131/// use moru_quant::analytic::OptionType;
132///
133/// // Non-dividend stock: b = r.
134/// let inputs = Inputs::new(60.0, 65.0, 0.08, 0.08, 0.30, 0.25)?;
135/// let call = bsm::price(OptionType::Call, &inputs);
136/// assert!((call - 2.1334).abs() < 5e-5);
137/// # Ok::<(), moru_quant::Error>(())
138/// ```
139pub fn price(option_type: OptionType, inputs: &Inputs) -> f64 {
140    let Inputs {
141        discounted_spot,
142        discounted_strike,
143        log_moneyness,
144        std_dev,
145    } = *inputs;
146    // σ·√T = 0 makes d1 = ±∞, or 0/0 at the forward; the limit is the
147    // discounted intrinsic value.
148    if std_dev <= 0.0 {
149        return match option_type {
150            OptionType::Call => (discounted_spot - discounted_strike).max(0.0),
151            OptionType::Put => (discounted_strike - discounted_spot).max(0.0),
152        };
153    }
154    let d1 = log_moneyness / std_dev + 0.5 * std_dev;
155    let d2 = d1 - std_dev;
156    // Each side uses N of its own d (not put–call parity) so that a small
157    // price is not the difference of two large ones.
158    match option_type {
159        OptionType::Call => discounted_spot * normal::cdf(d1) - discounted_strike * normal::cdf(d2),
160        OptionType::Put => {
161            discounted_strike * normal::cdf(-d2) - discounted_spot * normal::cdf(-d1)
162        }
163    }
164}
165
166/// `value` if it is finite.
167fn derived(quantity: &'static str, value: f64) -> Result<f64, Error> {
168    if value.is_finite() {
169        Ok(value)
170    } else {
171        Err(Error::Overflow { quantity })
172    }
173}