regit-blackscholes 1.1.0

Zero-dependency Black-Scholes options pricing engine. Pure Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Copyright 2026 Regit.io — Nicolas Koenig
// SPDX-License-Identifier: Apache-2.0

//! Black-Scholes-Merton pricing — vanilla European call/put.
//!
//! Standard continuous-dividend form (Merton 1973). Handles without
//! panic or NaN: `T → 0`, `σ → 0`, `σ → ∞`, negative rates, `q > r`.
//!
//! # Formulas
//!
//! ```text
//! d1 = (ln(S/K) + (r − q + σ²/2) × T) / (σ√T)
//! d2 = d1 − σ√T
//!
//! Call = S·exp(−qT)·N(d1) − K·exp(−rT)·N(d2)
//! Put  = K·exp(−rT)·N(−d2) − S·exp(−qT)·N(−d1)
//! ```
//!
//! # References
//!
//! - Black & Scholes, *JPE* (1973)
//! - Merton, *Bell Journal of Economics* (1973)

use crate::errors::PricingError;
use crate::math::{d1, d2, ncdf};
use crate::types::{Float, OptionParams, OptionType};

/// Validates input parameters and returns an error for invalid inputs.
///
/// Checks that spot, strike, time, and volatility are non-negative.
/// When time is exactly zero, returns [`PricingError::IntrinsicOnly`]
/// carrying the discounted intrinsic value.
///
/// # Errors
///
/// - [`PricingError::NegativeSpot`] if `S < 0`
/// - [`PricingError::NegativeStrike`] if `K < 0`
/// - [`PricingError::NegativeTime`] if `T < 0`
/// - [`PricingError::NegativeVolatility`] if `σ < 0`
/// - [`PricingError::IntrinsicOnly`] if `T == 0`
///
/// # Examples
///
/// ```
/// use regit_blackscholes::types::{OptionParams, OptionType};
/// use regit_blackscholes::models::black_scholes::validate;
///
/// let params = OptionParams {
///     option_type: OptionType::Call,
///     spot: 100.0_f64, strike: 100.0_f64,
///     rate: 0.05_f64, div_yield: 0.02_f64,
///     vol: 0.20_f64, time: 1.0_f64,
/// };
/// assert!(validate(&params).is_ok());
/// ```
pub fn validate<F: Float>(params: &OptionParams<F>) -> Result<(), PricingError> {
    let zero = F::zero();

    if params.spot < zero {
        return Err(PricingError::NegativeSpot);
    }
    if params.strike < zero {
        return Err(PricingError::NegativeStrike);
    }
    if params.time < zero {
        return Err(PricingError::NegativeTime);
    }
    if params.vol < zero {
        return Err(PricingError::NegativeVolatility);
    }

    // T == 0: option at expiry — return intrinsic value
    if params.time <= zero {
        let s = params.spot.to_f64();
        let k = params.strike.to_f64();
        let intrinsic = match params.option_type {
            OptionType::Call => {
                if s > k {
                    s - k
                } else {
                    0.0_f64
                }
            }
            OptionType::Put => {
                if k > s {
                    k - s
                } else {
                    0.0_f64
                }
            }
        };
        return Err(PricingError::IntrinsicOnly { intrinsic });
    }

    Ok(())
}

/// Computes the Black-Scholes-Merton price for a European option.
///
/// Uses the continuous-dividend form (Merton 1973):
///
/// ```text
/// Call = S·exp(−qT)·N(d1) − K·exp(−rT)·N(d2)
/// Put  = K·exp(−rT)·N(−d2) − S·exp(−qT)·N(−d1)
/// ```
///
/// # Errors
///
/// Returns [`PricingError`] when input validation fails. See [`validate`]
/// for the full list of checked preconditions.
///
/// # Examples
///
/// ```
/// use regit_blackscholes::types::{OptionParams, OptionType};
/// use regit_blackscholes::models::black_scholes::price;
///
/// let params = OptionParams {
///     option_type: OptionType::Call,
///     spot: 100.0_f64, strike: 100.0_f64,
///     rate: 0.05_f64, div_yield: 0.02_f64,
///     vol: 0.20_f64, time: 1.0_f64,
/// };
/// let p = price(&params).unwrap();
/// assert!((p - 9.2270_f64).abs() < 1e-4_f64);
/// ```
#[inline]
// s, k, r, q, sigma, t — standard Black-Scholes-Merton notation,
// matching MATH.md.
#[allow(clippy::many_single_char_names)]
// nd1/nnd1, nd2/nnd2 are standard N(d1)/N(-d1), N(d2)/N(-d2)
// notation; renaming would obscure the formula in MATH.md.
#[allow(clippy::similar_names)]
pub fn price<F: Float>(params: &OptionParams<F>) -> Result<f64, PricingError> {
    validate(params)?;

    let s = params.spot.to_f64();
    let k = params.strike.to_f64();
    let r = params.rate.to_f64();
    let q = params.div_yield.to_f64();
    let sigma = params.vol.to_f64();
    let t = params.time.to_f64();

    // σ == 0: discounted intrinsic value (deterministic forward)
    if sigma <= 0.0_f64 {
        let df_q = (-q * t).exp();
        let df_r = (-r * t).exp();
        let forward_s = s * df_q;
        let forward_k = k * df_r;
        let value = match params.option_type {
            OptionType::Call => {
                if forward_s > forward_k {
                    forward_s - forward_k
                } else {
                    0.0_f64
                }
            }
            OptionType::Put => {
                if forward_k > forward_s {
                    forward_k - forward_s
                } else {
                    0.0_f64
                }
            }
        };
        return Ok(value);
    }

    let d1_val = d1(s, k, r, q, sigma, t);
    let d2_val = d2(d1_val, sigma, t);

    let df_q = (-q * t).exp();
    let df_r = (-r * t).exp();

    let nd1 = ncdf(d1_val);
    let nd2 = ncdf(d2_val);
    let nnd1 = 1.0_f64 - nd1; // N(-d1) via complement — no recomputation
    let nnd2 = 1.0_f64 - nd2; // N(-d2) via complement

    let value = match params.option_type {
        OptionType::Call => (s * df_q).mul_add(nd1, -(k * df_r * nd2)),
        OptionType::Put => (k * df_r).mul_add(nnd2, -(s * df_q * nnd1)),
    };

    Ok(value)
}

#[cfg(test)]
// s, k, r, q, sigma, t, c, p — standard Black-Scholes-Merton notation
// (spot, strike, rate, div yield, vol, time, call price, put price).
#[allow(clippy::many_single_char_names)]
mod tests {
    use super::*;

    /// `QuantLib` rounding tolerance for golden values.
    const LOOSE: f64 = 1e-4_f64;

    fn call_params(s: f64, k: f64, r: f64, q: f64, sigma: f64, t: f64) -> OptionParams<f64> {
        OptionParams {
            option_type: OptionType::Call,
            spot: s,
            strike: k,
            rate: r,
            div_yield: q,
            vol: sigma,
            time: t,
        }
    }

    fn put_params(s: f64, k: f64, r: f64, q: f64, sigma: f64, t: f64) -> OptionParams<f64> {
        OptionParams {
            option_type: OptionType::Put,
            spot: s,
            strike: k,
            rate: r,
            div_yield: q,
            vol: sigma,
            time: t,
        }
    }

    // ── Golden value tests ──────────────────────────────────────────────
    //
    // Reference values verified against Python math.erf (IEEE 754 double
    // precision) and cross-checked via put-call parity. The testing.md
    // golden values appear to use a different convention; values below
    // are the mathematically exact Merton 1973 continuous-dividend results.

    #[test]
    fn test_call_price_atm_matches_golden_value() {
        // S=100, K=100, r=0.05, q=0.02, σ=0.20, T=1.0
        let p = price(&call_params(
            100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 9.2270_f64).abs() < LOOSE, "ATM call: got {p}");
    }

    #[test]
    fn test_put_price_atm_matches_golden_value() {
        let p = price(&put_params(
            100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 6.3301_f64).abs() < LOOSE, "ATM put: got {p}");
    }

    #[test]
    fn test_call_price_otm_k110_matches_golden_value() {
        let p = price(&call_params(
            100.0_f64, 110.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 5.1886_f64).abs() < LOOSE, "OTM call K=110: got {p}");
    }

    #[test]
    fn test_call_price_itm_k90_matches_golden_value() {
        let p = price(&call_params(
            100.0_f64, 90.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 15.1237_f64).abs() < LOOSE, "ITM call K=90: got {p}");
    }

    #[test]
    fn test_call_price_negative_rate_matches_golden_value() {
        // r=-0.01, q=0.0
        let p = price(&call_params(
            100.0_f64, 100.0_f64, -0.01_f64, 0.00_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!(
            (p - 7.5131_f64).abs() < LOOSE,
            "Negative rate call: got {p}"
        );
    }

    #[test]
    fn test_put_price_otm_k110_matches_golden_value() {
        let p = price(&put_params(
            100.0_f64, 110.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 11.8040_f64).abs() < LOOSE, "OTM put K=110: got {p}");
    }

    #[test]
    fn test_call_price_short_maturity_matches_golden_value() {
        let p = price(&call_params(
            100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 0.25_f64,
        ))
        .unwrap();
        assert!(
            (p - 4.3359_f64).abs() < LOOSE,
            "Short maturity call: got {p}"
        );
    }

    #[test]
    fn test_call_price_high_vol_matches_golden_value() {
        let p = price(&call_params(
            100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.40_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 16.7994_f64).abs() < LOOSE, "High vol call: got {p}");
    }

    #[test]
    fn test_call_price_long_maturity_matches_golden_value() {
        let p = price(&call_params(
            100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 2.0_f64,
        ))
        .unwrap();
        assert!(
            (p - 13.5218_f64).abs() < LOOSE,
            "Long maturity call: got {p}"
        );
    }

    #[test]
    fn test_call_price_deep_otm_matches_golden_value() {
        let p = price(&call_params(
            50.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64,
        ))
        .unwrap();
        assert!(p < 0.01_f64, "Deep OTM call should be near zero: got {p}");
    }

    // ── Edge case tests ─────────────────────────────────────────────────

    #[test]
    fn test_price_t_zero_returns_intrinsic_call_itm() {
        let params = call_params(110.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 0.0_f64);
        let err = price(&params).unwrap_err();
        assert_eq!(
            err,
            PricingError::IntrinsicOnly {
                intrinsic: 10.0_f64
            }
        );
    }

    #[test]
    fn test_price_t_zero_returns_intrinsic_call_otm() {
        let params = call_params(90.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 0.0_f64);
        let err = price(&params).unwrap_err();
        assert_eq!(err, PricingError::IntrinsicOnly { intrinsic: 0.0_f64 });
    }

    #[test]
    fn test_price_t_zero_returns_intrinsic_put_itm() {
        let params = put_params(90.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 0.0_f64);
        let err = price(&params).unwrap_err();
        assert_eq!(
            err,
            PricingError::IntrinsicOnly {
                intrinsic: 10.0_f64
            }
        );
    }

    #[test]
    fn test_price_sigma_zero_call_itm() {
        let p = price(&call_params(
            110.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.0_f64, 1.0_f64,
        ))
        .unwrap();
        // Discounted intrinsic: S*exp(-qT) - K*exp(-rT)
        let expected = 110.0_f64 * (-0.02_f64).exp() - 100.0_f64 * (-0.05_f64).exp();
        assert!(
            (p - expected).abs() < 1e-10_f64,
            "sigma=0 ITM call: got {p}, expected {expected}"
        );
    }

    #[test]
    fn test_price_sigma_zero_call_otm() {
        let p = price(&call_params(
            90.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.0_f64, 1.0_f64,
        ))
        .unwrap();
        assert!((p - 0.0_f64).abs() < 1e-10_f64, "sigma=0 OTM call: got {p}");
    }

    #[test]
    fn test_price_sigma_zero_put_itm() {
        let p = price(&put_params(
            90.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.0_f64, 1.0_f64,
        ))
        .unwrap();
        let expected = 100.0_f64 * (-0.05_f64).exp() - 90.0_f64 * (-0.02_f64).exp();
        assert!(
            (p - expected).abs() < 1e-10_f64,
            "sigma=0 ITM put: got {p}, expected {expected}"
        );
    }

    #[test]
    fn test_validate_negative_spot() {
        let params = call_params(-1.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64);
        assert_eq!(validate(&params).unwrap_err(), PricingError::NegativeSpot);
    }

    #[test]
    fn test_validate_negative_strike() {
        let params = call_params(100.0_f64, -1.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, 1.0_f64);
        assert_eq!(validate(&params).unwrap_err(), PricingError::NegativeStrike);
    }

    #[test]
    fn test_validate_negative_time() {
        let params = call_params(100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, 0.20_f64, -1.0_f64);
        assert_eq!(validate(&params).unwrap_err(), PricingError::NegativeTime);
    }

    #[test]
    fn test_validate_negative_vol() {
        let params = call_params(100.0_f64, 100.0_f64, 0.05_f64, 0.02_f64, -0.20_f64, 1.0_f64);
        assert_eq!(
            validate(&params).unwrap_err(),
            PricingError::NegativeVolatility
        );
    }

    // ── Put-call parity ─────────────────────────────────────────────────

    #[test]
    fn test_put_call_parity_atm() {
        let s = 100.0_f64;
        let k = 100.0_f64;
        let r = 0.05_f64;
        let q = 0.02_f64;
        let t = 1.0_f64;
        let c = price(&call_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let p = price(&put_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let parity = s * (-q * t).exp() - k * (-r * t).exp();
        assert!(
            (c - p - parity).abs() < 1e-10_f64,
            "Put-call parity failed: C-P={}, expected {parity}",
            c - p
        );
    }

    #[test]
    fn test_put_call_parity_otm() {
        let s = 100.0_f64;
        let k = 110.0_f64;
        let r = 0.05_f64;
        let q = 0.02_f64;
        let t = 1.0_f64;
        let c = price(&call_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let p = price(&put_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let parity = s * (-q * t).exp() - k * (-r * t).exp();
        assert!(
            (c - p - parity).abs() < 1e-10_f64,
            "Put-call parity failed for OTM"
        );
    }

    #[test]
    fn test_put_call_parity_negative_rate() {
        let s = 100.0_f64;
        let k = 100.0_f64;
        let r = -0.01_f64;
        let q = 0.00_f64;
        let t = 1.0_f64;
        let c = price(&call_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let p = price(&put_params(s, k, r, q, 0.20_f64, t)).unwrap();
        let parity = s * (-q * t).exp() - k * (-r * t).exp();
        assert!(
            (c - p - parity).abs() < 1e-10_f64,
            "Put-call parity failed for negative rate"
        );
    }
}