volsurf 1.0.0

Production-ready volatility surface library for derivatives pricing
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
//! Black (lognormal) implied volatility via Jäckel's "Let's Be Rational" algorithm.
//!
//! Wraps the [`implied_vol`] crate for near-machine-precision extraction.

use implied_vol::{DefaultSpecialFn, ImpliedBlackVolatility, PriceBlackScholes};

use crate::error::VolSurfError;
use crate::types::{OptionType, Vol};
use crate::validate::{validate_non_negative, validate_positive};

/// Black (lognormal) implied volatility calculator.
///
/// Uses Peter Jäckel's rational approximation algorithm (2013) for
/// near-machine-precision extraction of Black implied volatility.
///
/// # References
/// - Jäckel, P. "Let's Be Rational" (2013)
#[derive(Debug)]
pub struct BlackImpliedVol;

impl BlackImpliedVol {
    /// Compute Black implied volatility from an option price.
    ///
    /// # Arguments
    /// * `option_price` — Undiscounted option price (must be >= 0)
    /// * `forward` — Forward price at expiry (must be > 0 and finite)
    /// * `strike` — Strike price (must be > 0 and finite)
    /// * `expiry` — Time to expiry in years (must be > 0)
    /// * `option_type` — Call or Put
    ///
    /// # Errors
    /// Returns [`VolSurfError::InvalidInput`] for invalid inputs,
    /// [`VolSurfError::NumericalError`] if the price is outside the attainable range.
    pub fn compute(
        option_price: f64,
        forward: f64,
        strike: f64,
        expiry: f64,
        option_type: OptionType,
    ) -> crate::error::Result<Vol> {
        validate_non_negative(option_price, "option_price")?;
        validate_positive(forward, "forward")?;
        validate_positive(strike, "strike")?;
        validate_positive(expiry, "expiry")?;

        let is_call = matches!(option_type, OptionType::Call);

        let iv = ImpliedBlackVolatility::builder()
            .option_price(option_price)
            .forward(forward)
            .strike(strike)
            .expiry(expiry)
            .is_call(is_call)
            .build()
            .ok_or_else(|| VolSurfError::InvalidInput {
                message: "implied-vol rejected inputs as outside model domain".into(),
            })?;

        let sigma =
            iv.calculate::<DefaultSpecialFn>()
                .ok_or_else(|| VolSurfError::NumericalError {
                    message: "option price is outside the attainable range".into(),
                })?;

        Ok(Vol(sigma))
    }
}

/// Compute undiscounted Black-Scholes option price.
///
/// # Arguments
/// * `forward` — Forward price at expiry (must be > 0 and finite)
/// * `strike` — Strike price (must be > 0 and finite)
/// * `vol` — Black implied volatility σ (must be >= 0)
/// * `expiry` — Time to expiry in years (must be >= 0)
/// * `option_type` — Call or Put
///
/// # Errors
/// Returns [`VolSurfError::InvalidInput`] for invalid inputs.
pub fn black_price(
    forward: f64,
    strike: f64,
    vol: f64,
    expiry: f64,
    option_type: OptionType,
) -> crate::error::Result<f64> {
    validate_positive(forward, "forward")?;
    validate_positive(strike, "strike")?;
    validate_non_negative(vol, "volatility")?;
    validate_non_negative(expiry, "expiry")?;

    let is_call = matches!(option_type, OptionType::Call);

    let price = PriceBlackScholes::builder()
        .forward(forward)
        .strike(strike)
        .volatility(vol)
        .expiry(expiry)
        .is_call(is_call)
        .build()
        .ok_or_else(|| VolSurfError::InvalidInput {
            message: "implied-vol rejected pricing inputs as outside model domain".into(),
        })?
        .calculate::<DefaultSpecialFn>();

    Ok(price)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;

    #[test]
    fn round_trip_atm_call() {
        let (f, k, t, sigma) = (100.0, 100.0, 1.0, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_atm_put() {
        let (f, k, t, sigma) = (100.0, 100.0, 1.0, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Put).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Put).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_itm_call() {
        let (f, k, t, sigma) = (100.0, 80.0, 1.0, 0.25);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_otm_call() {
        let (f, k, t, sigma) = (100.0, 120.0, 1.0, 0.30);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_deep_otm_call() {
        let (f, k, t, sigma) = (100.0, 200.0, 1.0, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        assert!(price > 0.0, "deep OTM price should be positive");
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_high_vol() {
        let (f, k, t, sigma) = (100.0, 100.0, 1.0, 1.0);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_short_expiry() {
        let (f, k, t, sigma) = (100.0, 100.0, 0.01, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_long_expiry() {
        let (f, k, t, sigma) = (100.0, 100.0, 10.0, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_otm_put() {
        let (f, k, t, sigma) = (100.0, 80.0, 1.0, 0.25);
        let price = black_price(f, k, sigma, t, OptionType::Put).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Put).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_itm_put() {
        let (f, k, t, sigma) = (100.0, 120.0, 1.0, 0.30);
        let price = black_price(f, k, sigma, t, OptionType::Put).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Put).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn black_price_call_put_parity() {
        let (f, k, t, sigma) = (100.0, 110.0, 1.0, 0.25);
        let call = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let put = black_price(f, k, sigma, t, OptionType::Put).unwrap();
        // Call - Put = Forward - Strike (undiscounted put-call parity)
        assert_abs_diff_eq!(call - put, f - k, epsilon = 1e-10);
    }

    #[test]
    fn black_price_zero_vol_call() {
        // Zero vol: call = max(F - K, 0)
        let price = black_price(100.0, 80.0, 0.0, 1.0, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, 20.0, epsilon = 1e-12);
    }

    #[test]
    fn black_price_zero_vol_otm_call() {
        // Zero vol, OTM call: max(F - K, 0) = 0
        let price = black_price(100.0, 120.0, 0.0, 1.0, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, 0.0, epsilon = 1e-12);
    }

    #[test]
    fn black_price_zero_expiry() {
        // Zero expiry: intrinsic value
        let price = black_price(100.0, 80.0, 0.20, 0.0, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, 20.0, epsilon = 1e-12);
    }

    #[test]
    fn compute_rejects_negative_price() {
        let result = BlackImpliedVol::compute(-1.0, 100.0, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_nan_price() {
        let result = BlackImpliedVol::compute(f64::NAN, 100.0, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_zero_forward() {
        let result = BlackImpliedVol::compute(5.0, 0.0, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_negative_forward() {
        let result = BlackImpliedVol::compute(5.0, -1.0, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_infinite_forward() {
        let result = BlackImpliedVol::compute(5.0, f64::INFINITY, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_zero_strike() {
        let result = BlackImpliedVol::compute(5.0, 100.0, 0.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_zero_expiry() {
        let result = BlackImpliedVol::compute(5.0, 100.0, 100.0, 0.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_negative_expiry() {
        let result = BlackImpliedVol::compute(5.0, 100.0, 100.0, -1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_price_above_forward() {
        // Call price cannot exceed forward price
        let result = BlackImpliedVol::compute(150.0, 100.0, 100.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::NumericalError { .. })));
    }

    #[test]
    fn black_price_rejects_negative_vol() {
        let result = black_price(100.0, 100.0, -0.1, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_rejects_negative_expiry() {
        let result = black_price(100.0, 100.0, 0.2, -1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_rejects_zero_forward() {
        let result = black_price(0.0, 100.0, 0.2, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    // Gap #13: Zero strike + zero vol combined edge case

    #[test]
    fn black_price_rejects_zero_strike() {
        // Zero strike is rejected by validate_positive, regardless of vol
        let result = black_price(100.0, 0.0, 0.0, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_rejects_zero_strike_with_zero_vol() {
        let result = black_price(100.0, 0.0, 0.0, 1.0, OptionType::Put);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    // Gap #14: Infinite strike

    #[test]
    fn compute_rejects_infinite_strike() {
        let result = BlackImpliedVol::compute(5.0, 100.0, f64::INFINITY, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn compute_rejects_nan_strike() {
        let result = BlackImpliedVol::compute(5.0, 100.0, f64::NAN, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_rejects_infinite_strike() {
        let result = black_price(100.0, f64::INFINITY, 0.2, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_rejects_nan_strike() {
        let result = black_price(100.0, f64::NAN, 0.2, 1.0, OptionType::Call);
        assert!(matches!(result, Err(VolSurfError::InvalidInput { .. })));
    }

    #[test]
    fn black_price_zero_vol_itm_put() {
        // ITM put: K > F, intrinsic = max(K-F, 0) = 20.0
        let price = black_price(100.0, 120.0, 0.0, 1.0, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, 20.0, epsilon = 1e-12);
    }

    #[test]
    fn black_price_zero_vol_otm_put() {
        // OTM put: K < F, intrinsic = max(K-F, 0) = 0.0
        let price = black_price(100.0, 80.0, 0.0, 1.0, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, 0.0, epsilon = 1e-12);
    }

    #[test]
    fn black_price_zero_vol_atm_put() {
        // ATM put: K = F, intrinsic = 0
        let price = black_price(100.0, 100.0, 0.0, 1.0, OptionType::Put).unwrap();
        assert_abs_diff_eq!(price, 0.0, epsilon = 1e-12);
    }

    #[test]
    fn near_intrinsic_iv_stability() {
        // Deep ITM call: F=100, K=80, intrinsic=20.0
        // Price just above intrinsic
        let forward = 100.0;
        let strike = 80.0;
        let expiry = 1.0;
        let price = 20.01; // just above intrinsic of 20.0

        let iv =
            BlackImpliedVol::compute(price, forward, strike, expiry, OptionType::Call).unwrap();
        assert!(
            iv.0 > 0.0,
            "IV should be positive for price above intrinsic"
        );
        assert!(iv.0.is_finite(), "IV should be finite");

        // Round-trip: reprice with extracted IV should match original price
        let reprice = black_price(forward, strike, iv.0, expiry, OptionType::Call).unwrap();
        assert_abs_diff_eq!(reprice, price, epsilon = 1e-8);
    }

    #[test]
    fn round_trip_extreme_otm_call() {
        // |x| = ln(10) ≈ 2.3 with high vol to keep price above zero
        let (f, k, t, sigma) = (100.0, 1000.0, 1.0, 0.80);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        assert!(price > 0.0);
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn round_trip_extreme_itm_call() {
        // |x| = ln(1000) ≈ 6.9
        let (f, k, t, sigma) = (100.0, 0.1, 1.0, 0.20);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-12);
    }

    #[test]
    fn compute_near_maximum_price() {
        // Price close to forward (b_max), paper eq 6.18 warns accuracy degrades
        let iv = BlackImpliedVol::compute(99.99, 100.0, 100.0, 1.0, OptionType::Call).unwrap();
        assert!(iv.0 > 5.0, "near-max price should yield very high vol");
        assert!(iv.0.is_finite());
    }

    #[test]
    fn compute_rejects_put_price_above_strike() {
        let result = BlackImpliedVol::compute(150.0, 100.0, 100.0, 1.0, OptionType::Put);
        assert!(matches!(result, Err(VolSurfError::NumericalError { .. })));
    }

    #[test]
    fn round_trip_very_high_vol() {
        let (f, k, t, sigma) = (100.0, 100.0, 1.0, 5.0);
        let price = black_price(f, k, sigma, t, OptionType::Call).unwrap();
        let iv = BlackImpliedVol::compute(price, f, k, t, OptionType::Call).unwrap();
        let reprice = black_price(f, k, iv.0, t, OptionType::Call).unwrap();
        assert_abs_diff_eq!(price, reprice, epsilon = 1e-10);
    }
}