libitofin 0.8.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! Black 1976 formula family.
//!
//! Port of the value and undiscounted-form subset of
//! `ql/pricingengines/blackformula.{hpp,cpp}`: [`black_formula`], its forward
//! derivative, the cash/asset in-the-money probabilities and the standard
//! deviation first and second derivatives. Every function takes the *standard
//! deviation* over the option life, `volatility * sqrt(time_to_maturity)`,
//! not the volatility itself, and an optional lognormal `displacement`
//! shifting both forward and strike.
//!
//! The Bachelier (normal-model) pricing pair, [`bachelier_black_formula`] and
//! its forward derivative [`bachelier_black_formula_forward_derivative`], sit
//! beside the Black family; the optionlet volatility surface selects between
//! the two through its volatility type. Unlike the lognormal family the normal
//! model admits negative forwards and strikes and applies no displacement, so
//! these two functions deliberately skip [`check_parameters`]: they validate
//! only the standard deviation and discount, exactly as the C++ reference does.
//!
//! Out of scope, left as follow-ups with the quotes that need them: the
//! implied-standard-deviation family (approximations and solvers), including
//! its Bachelier variants.
//!
//! One deviation from the C++ reference: at `std_dev == 0` the reference's
//! `blackFormulaAssetItmProbability` tests `forward * sign < strike * sign`,
//! which inverts its own `std_dev -> 0` limit (`N(sign * d1) -> 1` exactly
//! when `sign * (forward - strike) > 0`) and the cash probability next to it.
//! The port uses the limit off the money; exactly at the money it returns
//! 0.0 like both C++ probability branches, where the limit would be 0.5.
//! Tests lock the off-the-money continuity and the at-the-money convention.

use crate::errors::QlResult;
use crate::fail;
use crate::math::distributions::normal::{CumulativeNormalDistribution, NormalDistribution};
use crate::math::solver1d::{DerivativeSolver, func1d};
use crate::math::solvers1d::newtonsafe::NewtonSafe;
use crate::option::OptionType;
use crate::types::{Natural, Real};

/// QuantLib's `checkParameters` (`blackformula.cpp:44,47,50`): the
/// `displacement >= 0`, `strike + displacement >= 0` and
/// `forward + displacement > 0` requirements, kept intact.
///
/// Divergence: the standalone finiteness checks on `strike` and `forward`, and
/// the `!is_finite()` clauses replacing C++'s implicit NaN handling. In C++ a
/// NaN argument fails every comparison, so `QL_REQUIRE(x >= 0.0)` already
/// throws; an infinite one does not, and `+inf - inf` in the shifted sums then
/// yields NaN downstream. Rejecting both here keeps the failure at the boundary.
fn check_parameters(strike: Real, forward: Real, displacement: Real) -> QlResult<()> {
    if !displacement.is_finite() || displacement < 0.0 {
        fail!("displacement ({displacement}) must be non-negative");
    }
    if !strike.is_finite() {
        fail!("strike ({strike}) must be finite");
    }
    if !forward.is_finite() {
        fail!("forward ({forward}) must be finite");
    }
    let shifted_strike = strike + displacement;
    if !shifted_strike.is_finite() || shifted_strike < 0.0 {
        fail!("strike + displacement ({strike} + {displacement}) must be non-negative");
    }
    let shifted_forward = forward + displacement;
    if !shifted_forward.is_finite() || shifted_forward <= 0.0 {
        fail!("forward + displacement ({forward} + {displacement}) must be positive");
    }
    Ok(())
}

fn check_std_dev_and_discount(std_dev: Real, discount: Real) -> QlResult<()> {
    check_std_dev(std_dev)?;
    if !discount.is_finite() || discount <= 0.0 {
        fail!("discount ({discount}) must be positive");
    }
    Ok(())
}

/// QuantLib's `QL_REQUIRE(stdDev >= 0.0)` (`blackformula.cpp:67`), extended to
/// reject `+inf`.
///
/// Divergence: `blackFormulaCashItmProbability` and
/// `blackFormulaAssetItmProbability` call only `checkParameters` and never
/// validate `stdDev`, so a negative one silently flips the sign of `d2`. This
/// port applies the same check there as in `black_formula`.
fn check_std_dev(std_dev: Real) -> QlResult<()> {
    if !std_dev.is_finite() || std_dev < 0.0 {
        fail!("stdDev ({std_dev}) must be non-negative");
    }
    Ok(())
}

fn sign_of(option_type: OptionType) -> Real {
    Real::from(option_type as i32)
}

/// Black 1976 value of a European option on the given forward.
pub fn black_formula(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev_and_discount(std_dev, discount)?;

    let sign = sign_of(option_type);

    if std_dev == 0.0 {
        let intrinsic = (forward - strike) * sign;
        let intrinsic = if intrinsic < 0.0 { 0.0 } else { intrinsic };
        return Ok(intrinsic * discount);
    }

    let forward = forward + displacement;
    let strike = strike + displacement;

    if strike == 0.0 {
        return Ok(match option_type {
            OptionType::Call => forward * discount,
            OptionType::Put => 0.0,
        });
    }

    let d1 = (forward / strike).ln() / std_dev + 0.5 * std_dev;
    let d2 = d1 - std_dev;
    let phi = CumulativeNormalDistribution::standard();
    let nd1 = phi.value(sign * d1);
    let nd2 = phi.value(sign * d2);
    let result = discount * sign * (forward * nd1 - strike * nd2);
    if result.is_nan() || result < 0.0 {
        fail!(
            "negative value ({result}) for {std_dev} stdDev, {option_type} option, \
             {strike} strike, {forward} forward"
        );
    }
    Ok(result)
}

/// Derivative of [`black_formula`] with respect to the forward.
pub fn black_formula_forward_derivative(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev_and_discount(std_dev, discount)?;

    let sign = sign_of(option_type);

    if std_dev == 0.0 {
        let moneyness = (forward - strike) * sign;
        return Ok(if moneyness > 0.0 {
            sign * discount
        } else {
            0.0
        });
    }

    let forward = forward + displacement;
    let strike = strike + displacement;

    if strike == 0.0 {
        return Ok(match option_type {
            OptionType::Call => discount,
            OptionType::Put => 0.0,
        });
    }

    let d1 = (forward / strike).ln() / std_dev + 0.5 * std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(sign * phi.value(sign * d1) * discount)
}

/// Risk-neutral probability of exercise in the bond martingale measure, `N(d2)`.
pub fn black_formula_cash_itm_probability(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev(std_dev)?;

    let sign = sign_of(option_type);

    if std_dev == 0.0 {
        return Ok(if forward * sign > strike * sign {
            1.0
        } else {
            0.0
        });
    }

    let forward = forward + displacement;
    let strike = strike + displacement;
    if strike == 0.0 {
        return Ok(match option_type {
            OptionType::Call => 1.0,
            OptionType::Put => 0.0,
        });
    }
    let d2 = (forward / strike).ln() / std_dev - 0.5 * std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(phi.value(sign * d2))
}

/// Risk-neutral probability of exercise in the asset martingale measure, `N(d1)`.
pub fn black_formula_asset_itm_probability(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev(std_dev)?;

    let sign = sign_of(option_type);

    if std_dev == 0.0 {
        return Ok(if forward * sign > strike * sign {
            1.0
        } else {
            0.0
        });
    }

    let forward = forward + displacement;
    let strike = strike + displacement;
    if strike == 0.0 {
        return Ok(match option_type {
            OptionType::Call => 1.0,
            OptionType::Put => 0.0,
        });
    }
    let d1 = (forward / strike).ln() / std_dev + 0.5 * std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(phi.value(sign * d1))
}

/// Derivative of [`black_formula`] with respect to the standard deviation.
///
/// Multiplying by `sqrt(time_to_maturity)` turns this into the Black vega.
pub fn black_formula_std_dev_derivative(
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev_and_discount(std_dev, discount)?;

    let forward = forward + displacement;
    let strike = strike + displacement;

    if std_dev == 0.0 || strike == 0.0 {
        return Ok(0.0);
    }

    let d1 = (forward / strike).ln() / std_dev + 0.5 * std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(discount * forward * phi.derivative(d1))
}

/// Derivative of [`black_formula`] with respect to the implied volatility.
///
/// This is the Black vega: [`black_formula_std_dev_derivative`] times
/// `sqrt(expiry)`.
pub fn black_formula_vol_derivative(
    strike: Real,
    forward: Real,
    std_dev: Real,
    expiry: Real,
    discount: Real,
    displacement: Real,
) -> QlResult<Real> {
    let derivative =
        black_formula_std_dev_derivative(strike, forward, std_dev, discount, displacement)?;
    Ok(derivative * expiry.sqrt())
}

/// Second derivative of [`black_formula`] with respect to the standard deviation.
pub fn black_formula_std_dev_second_derivative(
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
    displacement: Real,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    check_std_dev_and_discount(std_dev, discount)?;

    let forward = forward + displacement;
    let strike = strike + displacement;

    if std_dev == 0.0 || strike == 0.0 {
        return Ok(0.0);
    }

    let d1 = (forward / strike).ln() / std_dev + 0.5 * std_dev;
    let d1_prime = -(forward / strike).ln() / (std_dev * std_dev) + 0.5;
    let density = NormalDistribution::standard();
    Ok(discount * forward * density.derivative(d1) * d1_prime)
}

/// Implied Black standard deviation that reprices `black_price` under
/// [`black_formula`].
///
/// Port of `blackFormulaImpliedStdDev` (`blackformula.cpp:382-440`): checks the
/// price against put-call parity, converts an in-the-money option to its
/// out-of-the-money complement (greater vega/price ratio, hence numerically more
/// robust), then inverts [`black_formula`] for the standard deviation with a
/// [`NewtonSafe`] solve bracketed on `[0, 24]` (`24 = 300% * sqrt(60)`).
///
/// The undiscounted objective and its derivative mirror C++'s
/// `BlackImpliedStdDevHelper` (`blackformula.cpp:330-379`): the value is
/// `black_formula(type, strike, forward, std_dev, 1, 0) - black_price/discount`
/// on the displacement-shifted strike and forward, and the derivative is the
/// helper's signed `signedForward * phi(signed d1)`, reproduced here as
/// `sign * black_formula_std_dev_derivative(...)`. The sign is negative for the
/// out-of-the-money put branch, exactly as the helper computes it; the solve
/// still converges because [`NewtonSafe`] bisects whenever a Newton step leaves
/// the bracket.
///
/// # Divergence
///
/// C++ seeds the solve with `blackFormulaImpliedStdDevApproximation` when `guess`
/// is `Null<Real>`; the Rust API instead requires a finite non-negative `guess`
/// (the optionlet stripper always supplies one). The approximation-seeded
/// overload is deferred to #577.
///
/// # Errors
///
/// Rejects a non-positive `discount`, a negative `black_price`, a price implying
/// a negative complementary option under put-call parity, and a negative or
/// non-finite `guess`; propagates a solver that fails to converge.
#[allow(clippy::too_many_arguments)]
pub fn black_formula_implied_std_dev(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    black_price: Real,
    discount: Real,
    displacement: Real,
    guess: Real,
    accuracy: Real,
    max_iterations: Natural,
) -> QlResult<Real> {
    check_parameters(strike, forward, displacement)?;
    if !discount.is_finite() || discount <= 0.0 {
        fail!("discount ({discount}) must be positive");
    }
    if !black_price.is_finite() || black_price < 0.0 {
        fail!("option price ({black_price}) must be non-negative");
    }

    let mut option_type = option_type;
    let mut black_price = black_price;
    let other_option_price = black_price - sign_of(option_type) * (forward - strike) * discount;
    if other_option_price < 0.0 {
        fail!(
            "negative complementary-option price ({other_option_price}) implied by put-call \
             parity: no solution exists for {option_type} strike {strike}, forward {forward}, \
             price {black_price}, deflator {discount}"
        );
    }

    if matches!(option_type, OptionType::Put) && strike > forward {
        option_type = OptionType::Call;
        black_price = other_option_price;
    }
    if matches!(option_type, OptionType::Call) && strike < forward {
        option_type = OptionType::Put;
        black_price = other_option_price;
    }

    if !guess.is_finite() || guess < 0.0 {
        fail!("stdDev guess ({guess}) must be non-negative");
    }

    let shifted_strike = strike + displacement;
    let shifted_forward = forward + displacement;
    let target = black_price / discount;
    let otm_sign = sign_of(option_type);

    let value = |std_dev: Real| {
        black_formula(
            option_type,
            shifted_strike,
            shifted_forward,
            std_dev,
            1.0,
            0.0,
        )
        .map(|price| price - target)
        .unwrap_or(Real::NAN)
    };
    let derivative = |std_dev: Real| {
        black_formula_std_dev_derivative(shifted_strike, shifted_forward, std_dev, 1.0, 0.0)
            .map(|d| otm_sign * d)
            .unwrap_or(Real::NAN)
    };

    let std_dev = NewtonSafe::new()
        .with_max_evaluations(max_iterations as usize)
        .solve_bracketed(func1d(value, derivative), accuracy, guess, 0.0, 24.0)?;
    if std_dev < 0.0 {
        fail!("stdDev ({std_dev}) must be non-negative");
    }
    Ok(std_dev)
}

/// Bachelier (normal-model) value of a European option on the given forward.
///
/// Port of `bachelierBlackFormula` (`blackformula.cpp:705`). With
/// `d = (forward - strike) * sign` and `h = d / std_dev`, the premium is
/// `discount * (std_dev * phi(h) + d * Phi(h))`, where `phi`/`Phi` are the
/// standard normal density and cumulative distribution. The normal model
/// prices negative forwards and strikes, so only `std_dev` and `discount` are
/// validated; the terminal non-negativity check mirrors C++'s `QL_ENSURE`.
pub fn bachelier_black_formula(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
) -> QlResult<Real> {
    check_std_dev_and_discount(std_dev, discount)?;

    let sign = sign_of(option_type);
    let d = (forward - strike) * sign;

    if std_dev == 0.0 {
        return Ok(discount * d.max(0.0));
    }

    let h = d / std_dev;
    let phi = CumulativeNormalDistribution::standard();
    let result = discount * (std_dev * phi.derivative(h) + d * phi.value(h));
    if result.is_nan() || result < 0.0 {
        fail!(
            "negative value ({result}) for {std_dev} stdDev, {option_type} option, \
             {strike} strike, {forward} forward"
        );
    }
    Ok(result)
}

/// Derivative of [`bachelier_black_formula`] with respect to the forward.
///
/// Port of `bachelierBlackFormulaForwardDerivative` (`blackformula.cpp:738`),
/// which equals `sign * Phi(h) * discount`. At `std_dev == 0` the reference
/// collapses this to `sign * max(boost_sign((forward - strike) * sign), 0) *
/// discount`; `boost::math::sign` yields `0` at the money, so the derivative
/// is `0` exactly when `forward == strike` (distinct from `f64::signum`, which
/// never returns zero).
pub fn bachelier_black_formula_forward_derivative(
    option_type: OptionType,
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
) -> QlResult<Real> {
    check_std_dev_and_discount(std_dev, discount)?;

    let sign = sign_of(option_type);
    let moneyness = (forward - strike) * sign;

    if std_dev == 0.0 {
        let boost_sign: Real = if moneyness > 0.0 {
            1.0
        } else if moneyness < 0.0 {
            -1.0
        } else {
            0.0
        };
        return Ok(sign * boost_sign.max(0.0) * discount);
    }

    let h = moneyness / std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(sign * phi.value(h) * discount)
}

/// Derivative of [`bachelier_black_formula`] with respect to the standard
/// deviation.
///
/// Port of `bachelierBlackFormulaStdDevDerivative` (`blackformula.cpp:923`),
/// which equals `discount * phi((forward - strike) / std_dev)` where `phi` is
/// the standard normal density. The normal model prices negative forwards and
/// strikes, so only `std_dev` and `discount` are validated. Multiplying by
/// `sqrt(exercise_time)` turns this into the Bachelier vega.
pub fn bachelier_black_formula_std_dev_derivative(
    strike: Real,
    forward: Real,
    std_dev: Real,
    discount: Real,
) -> QlResult<Real> {
    check_std_dev_and_discount(std_dev, discount)?;

    if std_dev == 0.0 {
        return Ok(0.0);
    }

    let d1 = (forward - strike) / std_dev;
    let phi = CumulativeNormalDistribution::standard();
    Ok(discount * phi.derivative(d1))
}

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

    use crate::pricingengines::hull_fixture::{
        DISCOUNT as HULL_DISCOUNT, FORWARD as HULL_FORWARD, STD_DEV as HULL_STD_DEV,
    };

    fn assert_close(actual: Real, expected: Real, tolerance: Real) {
        assert!(
            (actual - expected).abs() <= tolerance,
            "actual {actual} vs expected {expected} (tolerance {tolerance})"
        );
    }

    #[test]
    fn known_values_match_black_scholes() {
        let call = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let put = black_formula(
            OptionType::Put,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        assert_close(call, 4.759422392871536, 1e-10);
        assert_close(put, 0.8085993729000926, 1e-10);
    }

    #[test]
    fn put_call_parity_holds() {
        for strike in [20.0, 40.0, 44.15338604779301, 60.0] {
            let call = black_formula(
                OptionType::Call,
                strike,
                HULL_FORWARD,
                HULL_STD_DEV,
                HULL_DISCOUNT,
                0.0,
            )
            .expect("valid inputs");
            let put = black_formula(
                OptionType::Put,
                strike,
                HULL_FORWARD,
                HULL_STD_DEV,
                HULL_DISCOUNT,
                0.0,
            )
            .expect("valid inputs");
            assert_close(call - put, HULL_DISCOUNT * (HULL_FORWARD - strike), 1e-12);
        }
    }

    #[test]
    fn zero_std_dev_returns_discounted_intrinsic() {
        let call = black_formula(OptionType::Call, 40.0, 44.0, 0.0, 0.95, 0.0).expect("valid");
        assert_close(call, 0.95 * 4.0, 1e-15);
        let put = black_formula(OptionType::Put, 40.0, 44.0, 0.0, 0.95, 0.0).expect("valid");
        assert_close(put, 0.0, 0.0);
    }

    #[test]
    fn zero_strike_prices_the_forward() {
        let call = black_formula(OptionType::Call, 0.0, 44.0, 0.2, 0.95, 0.0).expect("valid");
        assert_close(call, 44.0 * 0.95, 1e-15);
        let put = black_formula(OptionType::Put, 0.0, 44.0, 0.2, 0.95, 0.0).expect("valid");
        assert_close(put, 0.0, 0.0);
    }

    #[test]
    fn invalid_inputs_are_rejected() {
        assert!(black_formula(OptionType::Call, 40.0, 44.0, -0.1, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, 44.0, 0.1, 0.0, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, 44.0, Real::NAN, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, Real::NAN, 0.1, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, -1.0, 44.0, 0.1, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, -44.0, 0.1, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, 44.0, 0.1, 0.95, -0.01).is_err());
    }

    fn assert_forward_derivative_consistency(option_type: OptionType, strikes: &[Real], vol: Real) {
        let forward = 1.0;
        let tte: Real = 10.0;
        let std_dev = vol * tte.sqrt();
        let discount = 0.95;
        let displacement = 0.01;
        let bump = 0.0001;
        let epsilon = 1.0e-10;

        for &strike in strikes {
            let delta = black_formula_forward_derivative(
                option_type,
                strike,
                forward,
                std_dev,
                discount,
                displacement,
            )
            .expect("valid inputs");
            let bumped_delta = black_formula_forward_derivative(
                option_type,
                strike,
                forward + bump,
                std_dev,
                discount,
                displacement,
            )
            .expect("valid inputs");

            let base_premium = black_formula(
                option_type,
                strike,
                forward,
                std_dev,
                discount,
                displacement,
            )
            .expect("valid inputs");
            let bumped_premium = black_formula(
                option_type,
                strike,
                forward + bump,
                std_dev,
                discount,
                displacement,
            )
            .expect("valid inputs");
            let delta_approx = (bumped_premium - base_premium) / bump;

            assert!(
                delta.max(bumped_delta) + epsilon > delta_approx
                    && delta_approx > delta.min(bumped_delta) - epsilon,
                "forward derivative inconsistent with bump for {option_type} at strike {strike}: \
                 analytical {delta}, approximated {delta_approx}"
            );
        }
    }

    #[test]
    fn forward_derivative_is_consistent_with_bumping() {
        let strikes = [0.1, 0.5, 1.0, 2.0, 3.0];
        assert_forward_derivative_consistency(OptionType::Call, &strikes, 0.1);
        assert_forward_derivative_consistency(OptionType::Put, &strikes, 0.1);
    }

    #[test]
    fn forward_derivative_is_consistent_with_bumping_at_zero_strike() {
        assert_forward_derivative_consistency(OptionType::Call, &[0.0], 0.1);
        assert_forward_derivative_consistency(OptionType::Put, &[0.0], 0.1);
    }

    #[test]
    fn forward_derivative_is_consistent_with_bumping_at_zero_volatility() {
        let strikes = [0.1, 0.5, 1.0, 2.0, 3.0];
        assert_forward_derivative_consistency(OptionType::Call, &strikes, 0.0);
        assert_forward_derivative_consistency(OptionType::Put, &strikes, 0.0);
    }

    #[test]
    fn std_dev_derivative_matches_bumped_value() {
        let bump = 1.0e-6;
        let up = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV + bump,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let down = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV - bump,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let analytical =
            black_formula_std_dev_derivative(40.0, HULL_FORWARD, HULL_STD_DEV, HULL_DISCOUNT, 0.0)
                .expect("valid inputs");
        assert_close((up - down) / (2.0 * bump), analytical, 1e-6);

        let wide = 1.0e-4;
        let up_wide = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV + wide,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let down_wide = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV - wide,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let second = black_formula_std_dev_second_derivative(
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        let base = black_formula(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV,
            HULL_DISCOUNT,
            0.0,
        )
        .expect("valid inputs");
        assert_close(
            (up_wide - 2.0 * base + down_wide) / (wide * wide),
            second,
            1e-4,
        );
    }

    #[test]
    fn vol_derivative_scales_by_sqrt_expiry() {
        let std_dev_derivative =
            black_formula_std_dev_derivative(40.0, HULL_FORWARD, HULL_STD_DEV, HULL_DISCOUNT, 0.0)
                .expect("valid inputs");
        let vol_derivative =
            black_formula_vol_derivative(40.0, HULL_FORWARD, HULL_STD_DEV, 0.5, HULL_DISCOUNT, 0.0)
                .expect("valid inputs");
        assert_close(vol_derivative, std_dev_derivative * 0.5_f64.sqrt(), 1e-12);
        assert_close(vol_derivative, 8.813415059602862, 1e-10);
    }

    #[test]
    fn itm_probabilities_match_normal_quantiles() {
        let cash = black_formula_cash_itm_probability(
            OptionType::Call,
            40.0,
            HULL_FORWARD,
            HULL_STD_DEV,
            0.0,
        )
        .expect("valid inputs");
        assert_close(cash, 0.7349460368459086, 1e-10);
    }

    #[test]
    fn asset_itm_probability_is_continuous_at_zero_std_dev() {
        for (option_type, forward) in [
            (OptionType::Call, 44.0),
            (OptionType::Call, 36.0),
            (OptionType::Put, 44.0),
            (OptionType::Put, 36.0),
        ] {
            let limit = black_formula_asset_itm_probability(option_type, 40.0, forward, 1e-12, 0.0)
                .expect("valid inputs");
            let at_zero = black_formula_asset_itm_probability(option_type, 40.0, forward, 0.0, 0.0)
                .expect("valid inputs");
            assert_close(at_zero, limit, 1e-9);
        }
    }

    #[test]
    fn itm_probabilities_at_the_money_keep_the_zero_convention() {
        for option_type in [OptionType::Call, OptionType::Put] {
            let asset = black_formula_asset_itm_probability(option_type, 40.0, 40.0, 0.0, 0.0)
                .expect("valid inputs");
            assert_close(asset, 0.0, 0.0);
            let cash = black_formula_cash_itm_probability(option_type, 40.0, 40.0, 0.0, 0.0)
                .expect("valid inputs");
            assert_close(cash, 0.0, 0.0);
        }
    }

    #[test]
    fn itm_probabilities_reject_invalid_standard_deviation() {
        assert!(
            black_formula_cash_itm_probability(OptionType::Call, 40.0, 44.0, -0.1, 0.0).is_err()
        );
        assert!(
            black_formula_asset_itm_probability(OptionType::Call, 40.0, 44.0, -0.1, 0.0).is_err()
        );
        assert!(
            black_formula_cash_itm_probability(OptionType::Call, 40.0, 44.0, Real::NAN, 0.0)
                .is_err()
        );
        assert!(
            black_formula_asset_itm_probability(OptionType::Call, 40.0, 44.0, Real::NAN, 0.0)
                .is_err()
        );
        assert!(
            black_formula_cash_itm_probability(OptionType::Call, 40.0, 44.0, Real::INFINITY, 0.0)
                .is_err()
        );
    }

    #[test]
    fn black_formula_rejects_non_finite_inputs() {
        assert!(black_formula(OptionType::Call, Real::INFINITY, 44.0, 0.2, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, Real::INFINITY, 0.2, 0.95, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, 44.0, 0.2, Real::INFINITY, 0.0).is_err());
        assert!(black_formula(OptionType::Call, 40.0, 44.0, 0.2, 0.95, Real::INFINITY).is_err());
    }

    #[test]
    fn bachelier_put_call_parity_is_exact() {
        // C - P == discount * (forward - strike) for the normal model, derived from
        // C - P = discount * [d*Phi(h) + d*(1 - Phi(h))] with d = forward - strike.
        for (forward, strike) in [(0.03, 0.02), (0.02, 0.02), (-0.01, 0.01), (0.05, -0.02)] {
            for std_dev in [0.001, 0.02, 0.1] {
                let call =
                    bachelier_black_formula(OptionType::Call, strike, forward, std_dev, 0.95)
                        .expect("valid inputs");
                let put = bachelier_black_formula(OptionType::Put, strike, forward, std_dev, 0.95)
                    .expect("valid inputs");
                assert_close(call - put, 0.95 * (forward - strike), 1e-15);
            }
        }
    }

    #[test]
    fn bachelier_zero_volatility_is_discounted_intrinsic() {
        for (forward, strike) in [(0.03, 0.02), (0.01, 0.02), (-0.02, -0.01)] {
            let call = bachelier_black_formula(OptionType::Call, strike, forward, 0.0, 0.95)
                .expect("valid inputs");
            let put = bachelier_black_formula(OptionType::Put, strike, forward, 0.0, 0.95)
                .expect("valid inputs");
            assert_close(call, 0.95 * (forward - strike).max(0.0), 0.0);
            assert_close(put, 0.95 * (strike - forward).max(0.0), 0.0);
        }
    }

    #[test]
    fn bachelier_at_the_money_matches_the_closed_form() {
        // At forward == strike, d = 0 and h = 0, so the premium collapses to
        // discount * std_dev * phi(0) = discount * std_dev / sqrt(2*pi).
        for std_dev in [0.001, 0.05, 0.2] {
            let expected = 0.95 * std_dev / (2.0 * std::f64::consts::PI).sqrt();
            for option_type in [OptionType::Call, OptionType::Put] {
                let premium = bachelier_black_formula(option_type, 1.0, 1.0, std_dev, 0.95)
                    .expect("valid inputs");
                assert_close(premium, expected, 1e-16);
            }
        }
    }

    #[test]
    fn bachelier_matches_the_normal_pricing_definition() {
        // premium = discount * (std_dev * phi(h) + d * Phi(h)), d = (forward-strike)*sign,
        // h = d / std_dev, reconstructed from the normal primitives directly.
        let phi = CumulativeNormalDistribution::standard();
        for (forward, strike) in [(0.03, 0.025), (-0.01, 0.005), (0.02, 0.02)] {
            for std_dev in [0.001, 0.01, 0.05] {
                for option_type in [OptionType::Call, OptionType::Put] {
                    let sign = Real::from(option_type as i32);
                    let d = (forward - strike) * sign;
                    let h = d / std_dev;
                    let expected = 0.95 * (std_dev * phi.derivative(h) + d * phi.value(h));
                    let actual =
                        bachelier_black_formula(option_type, strike, forward, std_dev, 0.95)
                            .expect("valid inputs");
                    assert_close(actual, expected, 1e-16);
                }
            }
        }
    }

    #[test]
    fn bachelier_prices_negative_forward_and_strike() {
        let premium = bachelier_black_formula(OptionType::Call, -0.005, -0.01, 0.01, 1.0)
            .expect("normal model admits negative rates");
        assert!(premium > 0.0);
    }

    #[test]
    fn bachelier_rejects_invalid_std_dev_and_discount() {
        assert!(bachelier_black_formula(OptionType::Call, 1.0, 1.0, -0.1, 0.95).is_err());
        assert!(bachelier_black_formula(OptionType::Call, 1.0, 1.0, Real::INFINITY, 0.95).is_err());
        assert!(bachelier_black_formula(OptionType::Call, 1.0, 1.0, 0.1, 0.0).is_err());
        assert!(bachelier_black_formula(OptionType::Call, 1.0, 1.0, 0.1, -1.0).is_err());
        assert!(
            bachelier_black_formula_forward_derivative(OptionType::Call, 1.0, 1.0, -0.1, 0.95)
                .is_err()
        );
        assert!(
            bachelier_black_formula_forward_derivative(OptionType::Call, 1.0, 1.0, 0.1, 0.0)
                .is_err()
        );
    }

    fn assert_bachelier_forward_derivative(option_type: OptionType, strikes: &[Real], bpvol: Real) {
        // Mean-value-theorem check ported from blackformula.cpp:357: the analytical
        // forward derivative must bracket the bumped finite difference of the premium.
        let forward = 1.0;
        let tte: Real = 10.0;
        let std_dev = bpvol * tte.sqrt();
        let discount = 0.95;
        let bump = 0.0001;
        let epsilon = 1.0e-10;
        for &strike in strikes {
            let delta = bachelier_black_formula_forward_derivative(
                option_type,
                strike,
                forward,
                std_dev,
                discount,
            )
            .expect("valid inputs");
            let bumped_delta = bachelier_black_formula_forward_derivative(
                option_type,
                strike,
                forward + bump,
                std_dev,
                discount,
            )
            .expect("valid inputs");
            let base = bachelier_black_formula(option_type, strike, forward, std_dev, discount)
                .expect("valid inputs");
            let bumped =
                bachelier_black_formula(option_type, strike, forward + bump, std_dev, discount)
                    .expect("valid inputs");
            let delta_approx = (bumped - base) / bump;
            assert!(delta.max(bumped_delta) + epsilon > delta_approx);
            assert!(delta_approx > delta.min(bumped_delta) - epsilon);
        }
    }

    #[test]
    fn bachelier_forward_derivative_brackets_the_bumped_premium() {
        let strikes = [-3.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0];
        assert_bachelier_forward_derivative(OptionType::Call, &strikes, 0.001);
        assert_bachelier_forward_derivative(OptionType::Put, &strikes, 0.001);
    }

    #[test]
    fn bachelier_forward_derivative_brackets_the_bumped_premium_zero_vol() {
        let strikes = [-3.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0];
        assert_bachelier_forward_derivative(OptionType::Call, &strikes, 0.0);
        assert_bachelier_forward_derivative(OptionType::Put, &strikes, 0.0);
    }

    #[test]
    fn bachelier_std_dev_derivative_matches_bumped_value() {
        let forward = 1.0;
        let std_dev = 0.001 * 10.0_f64.sqrt();
        let discount = 0.95;
        let bump = 1.0e-6;
        for strike in [-1.0, 0.0, 0.9, 1.0, 1.1, 2.0] {
            let up = bachelier_black_formula(
                OptionType::Call,
                strike,
                forward,
                std_dev + bump,
                discount,
            )
            .expect("valid inputs");
            let down = bachelier_black_formula(
                OptionType::Call,
                strike,
                forward,
                std_dev - bump,
                discount,
            )
            .expect("valid inputs");
            let analytical =
                bachelier_black_formula_std_dev_derivative(strike, forward, std_dev, discount)
                    .expect("valid inputs");
            assert_close((up - down) / (2.0 * bump), analytical, 1e-6);
        }
    }

    #[test]
    fn bachelier_std_dev_derivative_edge_cases() {
        assert_eq!(
            bachelier_black_formula_std_dev_derivative(1.0, 1.0, 0.0, 0.95).expect("zero std dev"),
            0.0
        );
        assert!(bachelier_black_formula_std_dev_derivative(1.0, 1.0, -0.1, 0.95).is_err());
        assert!(bachelier_black_formula_std_dev_derivative(1.0, 1.0, 0.1, 0.0).is_err());
    }

    /// Round-trips vol -> price -> implied stddev across Call/Put and ITM/OTM,
    /// with and without a displacement, so both the put-call-parity conversion
    /// (the ITM cases flip to the OTM complement) and the shifted-lognormal
    /// branch are exercised. This is the supporting oracle for the enabler; the
    /// discriminating stripper round-trip is #576.
    #[test]
    fn implied_std_dev_round_trips_black_formula() {
        let discount = 0.95;
        let true_std_dev = 0.15;
        let accuracy = 1e-10;
        for displacement in [0.0, 0.01] {
            for (option_type, strike, forward) in [
                (OptionType::Call, 0.03, 0.025),
                (OptionType::Call, 0.02, 0.025),
                (OptionType::Put, 0.02, 0.025),
                (OptionType::Put, 0.03, 0.025),
            ] {
                let price = black_formula(
                    option_type,
                    strike,
                    forward,
                    true_std_dev,
                    discount,
                    displacement,
                )
                .expect("valid inputs");
                let recovered = black_formula_implied_std_dev(
                    option_type,
                    strike,
                    forward,
                    price,
                    discount,
                    displacement,
                    0.14,
                    accuracy,
                    100,
                )
                .expect("inverts black_formula");
                assert_close(recovered, true_std_dev, 1e-6);
            }
        }
    }

    #[test]
    fn implied_std_dev_rejects_a_negative_guess() {
        let price = black_formula(OptionType::Call, 0.03, 0.025, 0.15, 0.95, 0.0).expect("valid");
        assert!(
            black_formula_implied_std_dev(
                OptionType::Call,
                0.03,
                0.025,
                price,
                0.95,
                0.0,
                -1.0,
                1e-10,
                100
            )
            .is_err()
        );
    }

    #[test]
    fn implied_std_dev_rejects_invalid_price_and_discount() {
        assert!(
            black_formula_implied_std_dev(
                OptionType::Call,
                0.03,
                0.025,
                -0.1,
                0.95,
                0.0,
                0.14,
                1e-10,
                100
            )
            .is_err()
        );
        assert!(
            black_formula_implied_std_dev(
                OptionType::Call,
                0.03,
                0.025,
                0.01,
                0.0,
                0.0,
                0.14,
                1e-10,
                100
            )
            .is_err()
        );
    }
}