libitofin 0.6.1

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
//! Heston-model calibration helper.
//!
//! Port of `ql/models/equity/hestonmodelhelper.{hpp,cpp}`.
//! [`HestonModelHelper`] is a
//! [`BlackCalibrationHelper`](crate::models::calibrationhelper::BlackCalibrationHelper):
//! it prices a European vanilla option's market value from a quoted Black
//! volatility over a flat-vol surface, and its model value through the model
//! pricing engine a calibration installs (an
//! [`AnalyticHestonEngine`](crate::pricingengines::AnalyticHestonEngine)).
//!
//! ## Ported surface
//!
//! Both constructors (`hestonmodelhelper.cpp:33-62`): [`new`](HestonModelHelper::new)
//! takes the spot as a bare [`Real`] and wraps it in a constant
//! [`SimpleQuote`] (`cpp:42`); [`with_spot_handle`](HestonModelHelper::with_spot_handle)
//! takes a [`Handle<Quote>`](Handle) spot directly (`cpp:48-62`).
//!
//! ## `addTimesTo`
//!
//! `addTimesTo` (`hestonmodelhelper.hpp:56`) is literally empty `{}` in C++ - the
//! helper has no tree/lattice pricing path. It is already omitted from the
//! [`BlackCalibrationHelper`](crate::models::calibrationhelper::BlackCalibrationHelper)
//! trait surface (`calibrationhelper.rs` deferral of `addTimesTo`), so there is
//! nothing to implement: the empty C++ body maps to no Rust method at all.
//!
//! ## Divergences from QuantLib
//!
//! - **`Settings` is an explicit constructor argument.** C++ reads the global
//!   `Settings::instance()` when the built [`VanillaOption`] checks expiry; per
//!   D5 the core has no global, so the settings are passed in and reused for the
//!   option. The Heston engine takes its maturity time from the process curves
//!   (not the settings), so the settings only gate the option's expiry check;
//!   pass the same [`Settings`] the curves and engine are anchored to.
//! - **`model_value` / `black_price` are `&self` and recompute their derived
//!   state.** C++'s are const and lean on a `LazyObject::calculate()` that caches
//!   `mutable exerciseDate_ / tau_ / type_ / option_`. This port's
//!   [`BlackCalibrationHelper`](crate::models::calibrationhelper::BlackCalibrationHelper)
//!   fixes both as `&self`, so [`derive`](HestonModelHelper::derive) recomputes
//!   the exercise date, `tau`, the discounted strike/spot and the option type on
//!   each call (a few flat-curve discount lookups) and
//!   [`model_value`](HestonModelHelper::model_value) builds a fresh
//!   [`VanillaOption`]. `derive` is pure in the helper's inputs, so this is
//!   observationally identical to the C++ cache; observers are held weakly, so a
//!   fresh option per call does not leak.
//! - **A missing model engine is an explicit `Err`.** C++ `modelValue`
//!   dereferences a null `engine_`; the port returns an error (D4).
//! - **`black_price` uses the 6-arg [`black_formula`].** C++'s 4-arg overload
//!   (`cpp:89-91`) has discount `1.0` and displacement `0.0`; the strike and
//!   forward passed are already discounted, so this port passes `discount = 1.0`
//!   and `displacement = 0.0` (passing a curve discount here would double-count).

use crate::errors::QlResult;
use crate::exercise::{EuropeanExercise, Exercise};
use crate::fail;
use crate::handle::Handle;
use crate::instrument::Instrument;
use crate::instruments::{PlainVanillaPayoff, StrikedTypePayoff, VanillaOption};
use crate::models::calibrationhelper::{
    BlackCalibrationHelper, BlackCalibrationHelperBase, CalibrationErrorType,
};
use crate::option::OptionType;
use crate::pricingengines::blackformula::black_formula;
use crate::quotes::{Quote, SimpleQuote};
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut, shared, shared_mut};
use crate::termstructures::volatility::VolatilityType;
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::date::Date;
use crate::time::period::Period;
use crate::types::{Real, Time};

/// The state derived from the term structures on each valuation
/// (`performCalculations`, `hestonmodelhelper.cpp:64-78`).
struct Derived {
    exercise_date: Date,
    tau: Time,
    option_type: OptionType,
    discounted_strike: Real,
    discounted_spot: Real,
}

/// Calibration helper for the Heston model (`hestonmodelhelper.hpp:32`).
pub struct HestonModelHelper {
    base: BlackCalibrationHelperBase,
    maturity: Period,
    calendar: Calendar,
    s0: Handle<dyn Quote>,
    strike_price: Real,
    risk_free_rate: Handle<dyn YieldTermStructure>,
    dividend_yield: Handle<dyn YieldTermStructure>,
    settings: Shared<Settings<Date>>,
}

impl HestonModelHelper {
    /// Builds a helper from a bare spot (`hestonmodelhelper.cpp:33-45`): the spot
    /// is wrapped in a constant [`SimpleQuote`] and the helper delegates to
    /// [`with_spot_handle`](Self::with_spot_handle). C++ does not register with
    /// the constant spot; this port does (`with_spot_handle` registers all three
    /// handles), a no-op since a [`SimpleQuote`] built here never changes.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        maturity: Period,
        calendar: Calendar,
        s0: Real,
        strike_price: Real,
        volatility: Handle<dyn Quote>,
        risk_free_rate: Handle<dyn YieldTermStructure>,
        dividend_yield: Handle<dyn YieldTermStructure>,
        error_type: CalibrationErrorType,
        settings: Shared<Settings<Date>>,
    ) -> HestonModelHelper {
        let s0: Handle<dyn Quote> = Handle::new(shared(SimpleQuote::new(s0)) as Shared<dyn Quote>);
        HestonModelHelper::with_spot_handle(
            maturity,
            calendar,
            s0,
            strike_price,
            volatility,
            risk_free_rate,
            dividend_yield,
            error_type,
            settings,
        )
    }

    /// Builds a helper from a quoted spot (`hestonmodelhelper.cpp:47-62`).
    ///
    /// Registers the base's observer with the spot, risk-free and dividend
    /// handles (C++ `registerWith(s0)`/`registerWith(riskFreeRate)`/
    /// `registerWith(dividendYield)`, `:58-60`), so a change to any invalidates
    /// the cached market value alongside the volatility handle the base
    /// registers. The base uses the default `ShiftedLognormal` volatility type
    /// and zero shift of the C++ 2-arg base constructor.
    #[allow(clippy::too_many_arguments)]
    pub fn with_spot_handle(
        maturity: Period,
        calendar: Calendar,
        s0: Handle<dyn Quote>,
        strike_price: Real,
        volatility: Handle<dyn Quote>,
        risk_free_rate: Handle<dyn YieldTermStructure>,
        dividend_yield: Handle<dyn YieldTermStructure>,
        error_type: CalibrationErrorType,
        settings: Shared<Settings<Date>>,
    ) -> HestonModelHelper {
        let base = BlackCalibrationHelperBase::new(
            volatility,
            error_type,
            VolatilityType::ShiftedLognormal,
            0.0,
        );

        let observer = base.observer();
        s0.register_observer(&observer);
        risk_free_rate.register_observer(&observer);
        dividend_yield.register_observer(&observer);

        HestonModelHelper {
            base,
            maturity,
            calendar,
            s0,
            strike_price,
            risk_free_rate,
            dividend_yield,
            settings,
        }
    }

    /// The year fraction to the exercise date (`maturity()`,
    /// `hestonmodelhelper.hpp:60`): the `tau` of the current derived state.
    ///
    /// # Errors
    ///
    /// Propagates a failure of [`derive`](Self::derive) (an empty curve handle).
    pub fn maturity(&self) -> QlResult<Time> {
        Ok(self.derive()?.tau)
    }

    /// `performCalculations`'s derived state (`hestonmodelhelper.cpp:64-72`):
    /// advances the risk-free reference date by the maturity, times it, and
    /// selects the option type from forward moneyness. The type is
    /// [`Call`](OptionType::Call) when the discounted strike is at least the
    /// discounted spot, else [`Put`](OptionType::Put) (`cpp:68-71`).
    fn derive(&self) -> QlResult<Derived> {
        let risk_free = self.risk_free_rate.current_link()?;
        let reference_date = risk_free.reference_date()?;
        let exercise_date = self.calendar.advance_by_period(
            reference_date,
            self.maturity,
            BusinessDayConvention::Following,
            false,
        );
        let tau = risk_free.time_from_reference(exercise_date)?;

        let discounted_strike = self.strike_price * risk_free.discount(tau, false)?;
        let dividend = self.dividend_yield.current_link()?;
        let spot = self.s0.current_link()?.value()?;
        let discounted_spot = spot * dividend.discount(tau, false)?;

        let option_type = if discounted_strike >= discounted_spot {
            OptionType::Call
        } else {
            OptionType::Put
        };

        Ok(Derived {
            exercise_date,
            tau,
            option_type,
            discounted_strike,
            discounted_spot,
        })
    }

    /// Builds the vanilla option `performCalculations` assembles
    /// (`hestonmodelhelper.cpp:73-77`): a [`PlainVanillaPayoff`] of the derived
    /// type struck at `strikePrice_` over a [`EuropeanExercise`] on the exercise
    /// date.
    fn build_option(&self, derived: &Derived) -> SharedMut<VanillaOption> {
        let payoff = shared(PlainVanillaPayoff::new(
            derived.option_type,
            self.strike_price,
        )) as Shared<dyn StrikedTypePayoff>;
        let exercise = shared(EuropeanExercise::new(derived.exercise_date)) as Shared<dyn Exercise>;
        shared_mut(VanillaOption::new(
            payoff,
            exercise,
            Shared::clone(&self.settings),
        ))
    }
}

impl BlackCalibrationHelper for HestonModelHelper {
    fn base(&self) -> &BlackCalibrationHelperBase {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BlackCalibrationHelperBase {
        &mut self.base
    }

    /// `modelValue` (`hestonmodelhelper.cpp:80-84`): installs the model engine on
    /// the option and returns its NPV.
    fn model_value(&self) -> QlResult<Real> {
        let derived = self.derive()?;
        let option = self.build_option(&derived);
        let Some(engine) = self.base.pricing_engine() else {
            fail!("no model pricing engine set on the heston model helper");
        };
        option
            .borrow_mut()
            .base_mut()
            .set_pricing_engine(SharedMut::clone(engine));
        let value = option.borrow_mut().npv()?;
        Ok(value)
    }

    /// `blackPrice` (`hestonmodelhelper.cpp:86-92`): the Black 1976 value at the
    /// given volatility, with the strike and forward already discounted, so the
    /// discount and displacement of the 6-arg formula are `1.0` and `0.0`.
    fn black_price(&self, volatility: Real) -> QlResult<Real> {
        let derived = self.derive()?;
        let std_dev = volatility * derived.tau.sqrt();
        black_formula(
            derived.option_type,
            derived.discounted_strike,
            derived.discounted_spot,
            std_dev,
            1.0,
            0.0,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interestrate::Compounding;
    use crate::math::interpolations::linear::Linear;
    use crate::math::optimization::endcriteria::EndCriteria;
    use crate::math::optimization::levenbergmarquardt::LevenbergMarquardt;
    use crate::models::calibrationhelper::CalibrationHelper;
    use crate::models::{HestonModel, calibrate};
    use crate::pricingengine::PricingEngine;
    use crate::pricingengines::vanilla::analytichestonengine::AnalyticHestonEngine;
    use crate::processes::HestonProcess;
    use crate::termstructures::yields::{FlatForward, ZeroCurve};
    use crate::time::calendars::nullcalendar::NullCalendar;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::daycounters::actual365fixed::Actual365Fixed;
    use crate::time::frequency::Frequency;
    use crate::time::timeunit::TimeUnit;
    use crate::types::Integer;

    const VOL: Real = 0.1;

    fn today() -> Date {
        Date::new(15, Month::January, 2026)
    }

    /// The `testBlackCalibration` market data (`hestonmodel.cpp:239-251`):
    /// Actual360 flat curves at 4% risk-free / 50% dividend referenced at the
    /// evaluation date, unit spot and a flat 10% volatility, on a
    /// [`NullCalendar`]. The 50% dividend yield drives forwards well below spot,
    /// so the out-of-the-money (positive-moneyness) helpers become puts.
    struct Fixture {
        settings: Shared<Settings<Date>>,
        risk_free: Handle<dyn YieldTermStructure>,
        dividend: Handle<dyn YieldTermStructure>,
        s0: Handle<dyn Quote>,
        vol: Handle<dyn Quote>,
        calendar: Calendar,
    }

    impl Fixture {
        fn new() -> Fixture {
            let settings = shared(Settings::new());
            settings.set_evaluation_date(today());
            let flat = |rate: Real| -> Handle<dyn YieldTermStructure> {
                Handle::new(shared(FlatForward::with_rate(
                    today(),
                    rate,
                    Actual360::new(),
                    Compounding::Continuous,
                    Frequency::Annual,
                )) as Shared<dyn YieldTermStructure>)
            };
            Fixture {
                settings,
                risk_free: flat(0.04),
                dividend: flat(0.50),
                s0: Handle::new(shared(SimpleQuote::new(1.0)) as Shared<dyn Quote>),
                vol: Handle::new(shared(SimpleQuote::new(VOL)) as Shared<dyn Quote>),
                calendar: NullCalendar::new(),
            }
        }

        /// `tau` exactly as the helper derives it (`hestonmodelhelper.cpp:65-66`):
        /// the risk-free curve's time to the maturity-advanced reference date.
        fn tau(&self, maturity: Period) -> Time {
            let risk_free = self.risk_free.current_link().unwrap();
            let reference = risk_free.reference_date().unwrap();
            let exercise = self.calendar.advance_by_period(
                reference,
                maturity,
                BusinessDayConvention::Following,
                false,
            );
            risk_free.time_from_reference(exercise).unwrap()
        }

        /// The forward `s0 * dividendDiscount / riskFreeDiscount`
        /// (`hestonmodel.cpp:257-258`).
        fn forward(&self, tau: Time) -> Real {
            let risk_free = self.risk_free.current_link().unwrap();
            let dividend = self.dividend.current_link().unwrap();
            let s0 = self.s0.current_link().unwrap().value().unwrap();
            s0 * dividend.discount(tau, false).unwrap() / risk_free.discount(tau, false).unwrap()
        }

        fn helper(&self, maturity: Period, strike: Real) -> HestonModelHelper {
            HestonModelHelper::with_spot_handle(
                maturity,
                self.calendar.clone(),
                self.s0.clone(),
                strike,
                self.vol.clone(),
                self.risk_free.clone(),
                self.dividend.clone(),
                CalibrationErrorType::RelativePriceError,
                Shared::clone(&self.settings),
            )
        }

        /// A Black price computed independently of the helper, with the strike
        /// and forward discounted and a forced option type - the reference the
        /// standalone pins compare against (`hestonmodelhelper.cpp:89-91`).
        fn direct_black(
            &self,
            maturity: Period,
            strike: Real,
            option_type: OptionType,
            vol: Real,
        ) -> Real {
            let tau = self.tau(maturity);
            let risk_free = self.risk_free.current_link().unwrap();
            let dividend = self.dividend.current_link().unwrap();
            let s0 = self.s0.current_link().unwrap().value().unwrap();
            black_formula(
                option_type,
                strike * risk_free.discount(tau, false).unwrap(),
                s0 * dividend.discount(tau, false).unwrap(),
                vol * tau.sqrt(),
                1.0,
                0.0,
            )
            .unwrap()
        }
    }

    /// STANDALONE PIN: `black_price` equals a directly computed
    /// [`black_formula`] with the discounted strike/forward, and `market_value`
    /// equals `black_price` at the quoted volatility (the base-class contract).
    /// A 6-arg wiring, discounting or `tau` bug diverges this off the optimizer.
    /// The 6M at-the-forward helper (moneyness 0) has strike equal to the
    /// forward, so its `strike * rf_discount == s0 * div_discount` and the type
    /// is a call.
    #[test]
    fn black_price_matches_a_direct_black_formula_and_market_value() {
        let fixture = Fixture::new();
        let maturity = Period::new(6, TimeUnit::Months);
        let strike = fixture.forward(fixture.tau(maturity));
        let mut helper = fixture.helper(maturity, strike);

        let expected = fixture.direct_black(maturity, strike, OptionType::Call, VOL);
        let black = helper.black_price(VOL).unwrap();
        assert!(
            (black - expected).abs() <= 1.0e-12,
            "black_price {black} vs direct black_formula {expected} (error {})",
            (black - expected).abs()
        );

        let market = helper.market_value().unwrap();
        assert!(
            (market - black).abs() <= 1.0e-12,
            "market_value {market} vs black_price {black} (error {})",
            (market - black).abs()
        );
    }

    /// CONFIRM-BY-STUBBING: the `type_` decision (`hestonmodelhelper.cpp:68-71`)
    /// is live inside `black_price`. A strike far below the forward prices as a
    /// put (matches a forced-put `black_formula`, differs from a forced call);
    /// a strike far above prices as a call. Removing the moneyness branch would
    /// break one side of each pair.
    #[test]
    fn black_price_tracks_the_option_type_decision() {
        let fixture = Fixture::new();
        let maturity = Period::new(1, TimeUnit::Years);
        let forward = fixture.forward(fixture.tau(maturity));

        let put_strike = forward * 0.5;
        let put_black = fixture
            .helper(maturity, put_strike)
            .black_price(VOL)
            .unwrap();
        let forced_put = fixture.direct_black(maturity, put_strike, OptionType::Put, VOL);
        let forced_call = fixture.direct_black(maturity, put_strike, OptionType::Call, VOL);
        assert!(
            (put_black - forced_put).abs() <= 1.0e-12,
            "a strike below the forward must price as a put: {put_black} vs {forced_put}"
        );
        assert!(
            (put_black - forced_call).abs() > 1.0e-8,
            "the type decision is dead: the put priced as a forced call ({put_black})"
        );

        let call_strike = forward * 2.0;
        let call_black = fixture
            .helper(maturity, call_strike)
            .black_price(VOL)
            .unwrap();
        let forced_call = fixture.direct_black(maturity, call_strike, OptionType::Call, VOL);
        let forced_put = fixture.direct_black(maturity, call_strike, OptionType::Put, VOL);
        assert!(
            (call_black - forced_call).abs() <= 1.0e-12,
            "a strike above the forward must price as a call: {call_black} vs {forced_call}"
        );
        assert!(
            (call_black - forced_put).abs() > 1.0e-8,
            "the type decision is dead: the call priced as a forced put ({call_black})"
        );
    }

    /// ORACLE `testBlackCalibration` (`hestonmodel.cpp:232-311`): calibrate the
    /// Heston model to a flat 10% vol surface (21 helpers over 7 maturities x 3
    /// moneyness) for three starting vol-of-vols. A flat surface has no smile, so
    /// the fit drives sigma to zero and theta/v0 to the constant variance. The
    /// theta pin is C++'s deliberately weak `|kappa * (theta - vol^2)|` (a small
    /// kappa lets theta drift), ported faithfully. The distribution check
    /// confirms the put branch is genuinely exercised (7 puts at moneyness +1,
    /// 14 calls at moneyness <= 0).
    ///
    /// #425 ported the small-`sigma` chF series expansion
    /// (`analytichestonengine.cpp:584-617`), which unblocks the sigma=0.1 start
    /// (sigma -> ~1e-7 through the series, no panic). This oracle also drives the
    /// sigma=0.3 and sigma=0.5 starts, and at their INITIAL cost - params
    /// `(kappa=0.2, theta=0.02, sigma>=0.3, rho=-0.75, v0=0.01)` -
    /// `optimalControlVariate` (`analytichestonengine.cpp:707-719`) selects
    /// `AsymptoticChF` for every maturity >= 2 months (the 1-month helper stays
    /// `AngledContour` as `tau ~ 0.086 < 0.15` fails condition 1). Issue #426
    /// ported the `AsymptoticChF` control variate (`phi`/`psi` + `Ci`/`Si`), so
    /// all three starts now converge. C++ `testBlackCalibration`
    /// (`hestonmodel.cpp:280-283`) builds `AnalyticHestonEngine(model, 96)`,
    /// whose `cpxLog_` is `OptimalCV` (`analytichestonengine.cpp:666`).
    #[test]
    fn heston_calibrates_to_a_flat_vol_surface() {
        let fixture = Fixture::new();
        let maturities = [
            Period::new(1, TimeUnit::Months),
            Period::new(2, TimeUnit::Months),
            Period::new(3, TimeUnit::Months),
            Period::new(6, TimeUnit::Months),
            Period::new(9, TimeUnit::Months),
            Period::new(1, TimeUnit::Years),
            Period::new(2, TimeUnit::Years),
        ];
        let moneynesses = [-1.0, 0.0, 1.0];

        let mut helpers: Vec<SharedMut<HestonModelHelper>> = Vec::new();
        let mut puts = 0usize;
        let mut calls = 0usize;
        for &maturity in &maturities {
            for &moneyness in &moneynesses {
                let tau = fixture.tau(maturity);
                let strike = fixture.forward(tau) * (-moneyness * VOL * tau.sqrt()).exp();
                let helper = fixture.helper(maturity, strike);

                let black = helper.black_price(VOL).unwrap();
                let call = fixture.direct_black(maturity, strike, OptionType::Call, VOL);
                let put = fixture.direct_black(maturity, strike, OptionType::Put, VOL);
                if (black - put).abs() < (black - call).abs() {
                    puts += 1;
                } else {
                    calls += 1;
                }
                helpers.push(shared_mut(helper));
            }
        }
        assert_eq!(helpers.len(), 21);
        assert_eq!(
            puts, 7,
            "the 50% dividend fixture must exercise the put branch (moneyness +1)"
        );
        assert_eq!(calls, 14);

        let tolerance = 3.0e-3;
        let expected_variance = VOL * VOL;
        for &sigma in &[0.1, 0.3, 0.5] {
            let process = shared(HestonProcess::new(
                fixture.risk_free.clone(),
                fixture.dividend.clone(),
                fixture.s0.clone(),
                0.01,
                0.2,
                0.02,
                sigma,
                -0.75,
            ));
            let model = HestonModel::new(process).unwrap();
            let engine =
                shared_mut(AnalyticHestonEngine::new(SharedMut::clone(&model), 96).unwrap())
                    as SharedMut<dyn PricingEngine>;
            for helper in &helpers {
                helper
                    .borrow_mut()
                    .base_mut()
                    .set_pricing_engine(SharedMut::clone(&engine));
            }
            let dyn_helpers: Vec<SharedMut<dyn CalibrationHelper>> = helpers
                .iter()
                .map(|helper| SharedMut::clone(helper) as SharedMut<dyn CalibrationHelper>)
                .collect();

            let mut method = LevenbergMarquardt::new(1e-8, 1e-8, 1e-8, false);
            let end_criteria = EndCriteria::new(400, Some(40), 1e-8, 1e-8, Some(1e-8)).unwrap();
            calibrate(
                &model,
                &dyn_helpers,
                &mut method,
                &end_criteria,
                None,
                Vec::new(),
                Vec::new(),
            )
            .unwrap();

            let model = model.borrow();
            assert!(
                model.sigma() < tolerance,
                "sigma {} exceeds {tolerance} (start {sigma})",
                model.sigma()
            );
            let theta_residual = model.kappa() * (model.theta() - expected_variance);
            assert!(
                theta_residual.abs() < tolerance,
                "kappa*(theta - vol^2) = {theta_residual} exceeds {tolerance} (start {sigma})"
            );
            assert!(
                (model.v0() - expected_variance).abs() < tolerance,
                "v0 {} vs vol^2 {expected_variance} exceeds {tolerance} (start {sigma})",
                model.v0()
            );
        }
    }

    /// The DAX calibration market data (`hestonmodel.cpp:76-146`,
    /// `getDAXCalibrationMarketData`): the A. Sepp DAX implied-vol example -
    /// settlement 5 July 2002, [`Actual365Fixed`] over the [`Target`] calendar. The
    /// risk-free curve is a 9-point [`ZeroCurve`] (settlement anchor 0.0357 then
    /// the eight `r[]` points at `settlement + t[i]`, cpp:88-100) interpolated
    /// linearly; the dividend is a flat-zero [`FlatForward`] (`flatRate(..., 0.0)`,
    /// cpp:103); spot is 4468.17 (cpp:120). The 13-strike x 8-expiry implied-vol
    /// matrix `v[]` (104 values, laid out row-per-strike as in C++) builds 104
    /// [`HestonModelHelper`]s indexed `vol = v[s*8+m]` with maturity
    /// `(t[m]+3)/7` weeks (cpp:126-137), each using
    /// [`CalibrationErrorType::ImpliedVolError`] (cpp:137) - the implied-vol
    /// residual is the quantity A. Sepp's sse = 177.2 measures.
    struct DaxMarketData {
        risk_free: Handle<dyn YieldTermStructure>,
        dividend: Handle<dyn YieldTermStructure>,
        s0: Handle<dyn Quote>,
        options: Vec<SharedMut<HestonModelHelper>>,
    }

    fn dax_market_data() -> DaxMarketData {
        let settlement = Date::new(5, Month::July, 2002);
        let settings = shared(Settings::new());
        settings.set_evaluation_date(settlement);

        let day_counter = Actual365Fixed::new();
        let calendar = Target::new();

        let t: [Integer; 8] = [13, 41, 75, 165, 256, 345, 524, 703];
        let r: [Real; 8] = [
            0.0357, 0.0349, 0.0341, 0.0355, 0.0359, 0.0368, 0.0386, 0.0401,
        ];

        let mut dates = vec![settlement];
        let mut rates = vec![0.0357];
        for i in 0..8 {
            dates.push(settlement + t[i]);
            rates.push(r[i]);
        }
        let risk_free: Handle<dyn YieldTermStructure> = Handle::new(shared(
            ZeroCurve::new(dates, rates, day_counter.clone(), Linear).unwrap(),
        )
            as Shared<dyn YieldTermStructure>);

        let dividend: Handle<dyn YieldTermStructure> = Handle::new(shared(FlatForward::with_rate(
            settlement,
            0.0,
            day_counter.clone(),
            Compounding::Continuous,
            Frequency::Annual,
        ))
            as Shared<dyn YieldTermStructure>);

        let s0: Handle<dyn Quote> =
            Handle::new(shared(SimpleQuote::new(4468.17)) as Shared<dyn Quote>);

        let v: [[Real; 8]; 13] = [
            [
                0.6625, 0.4875, 0.4204, 0.3667, 0.3431, 0.3267, 0.3121, 0.3121,
            ],
            [
                0.6007, 0.4543, 0.3967, 0.3511, 0.3279, 0.3154, 0.2984, 0.2921,
            ],
            [
                0.5084, 0.4221, 0.3718, 0.3327, 0.3155, 0.3027, 0.2919, 0.2889,
            ],
            [
                0.4541, 0.3869, 0.3492, 0.3149, 0.2963, 0.2926, 0.2819, 0.2800,
            ],
            [
                0.4060, 0.3607, 0.3330, 0.2999, 0.2887, 0.2811, 0.2751, 0.2775,
            ],
            [
                0.3726, 0.3396, 0.3108, 0.2781, 0.2788, 0.2722, 0.2661, 0.2686,
            ],
            [
                0.3550, 0.3277, 0.3012, 0.2781, 0.2781, 0.2661, 0.2661, 0.2681,
            ],
            [
                0.3428, 0.3209, 0.2958, 0.2740, 0.2688, 0.2627, 0.2580, 0.2620,
            ],
            [
                0.3302, 0.3062, 0.2799, 0.2631, 0.2573, 0.2533, 0.2504, 0.2544,
            ],
            [
                0.3343, 0.2959, 0.2705, 0.2540, 0.2504, 0.2464, 0.2448, 0.2462,
            ],
            [
                0.3460, 0.2845, 0.2624, 0.2463, 0.2425, 0.2385, 0.2373, 0.2422,
            ],
            [
                0.3857, 0.2860, 0.2578, 0.2399, 0.2357, 0.2327, 0.2312, 0.2351,
            ],
            [
                0.3976, 0.2860, 0.2607, 0.2356, 0.2297, 0.2268, 0.2241, 0.2320,
            ],
        ];
        let strike: [Real; 13] = [
            3400.0, 3600.0, 3800.0, 4000.0, 4200.0, 4400.0, 4500.0, 4600.0, 4800.0, 5000.0, 5200.0,
            5400.0, 5600.0,
        ];

        let mut options = Vec::with_capacity(13 * 8);
        for s in 0..13 {
            for m in 0..8 {
                let vol: Handle<dyn Quote> =
                    Handle::new(shared(SimpleQuote::new(v[s][m])) as Shared<dyn Quote>);
                let maturity = Period::new((t[m] + 3) / 7, TimeUnit::Weeks);
                options.push(shared_mut(HestonModelHelper::with_spot_handle(
                    maturity,
                    calendar.clone(),
                    s0.clone(),
                    strike[s],
                    vol,
                    risk_free.clone(),
                    dividend.clone(),
                    CalibrationErrorType::ImpliedVolError,
                    Shared::clone(&settings),
                )));
            }
        }

        DaxMarketData {
            risk_free,
            dividend,
            s0,
            options,
        }
    }

    /// ORACLE `testDAXCalibration` (`hestonmodel.cpp:313-370`), the
    /// [`AnalyticHestonEngine`] arm only. Calibrate the Heston model to the A. Sepp
    /// DAX implied-vol matrix (104 helpers) from the seed (v0=0.1, kappa=1.0,
    /// theta=0.1, sigma=0.5, rho=-0.5, cpp:329-333) with `AnalyticHestonEngine(model, 64)`
    /// and a [`LevenbergMarquardt`] fit, then reproduce the sum of squared
    /// calibration errors sse ~= 177.2 (`|sse - 177.2| < 1.0`, cpp:358-364).
    ///
    /// DEFERRAL (#262-class, visible): C++ loops THREE engines (cpp:342-346) -
    /// `AnalyticHestonEngine(model, 64)`, `COSHestonEngine(model, 12, 75)` and
    /// `ExponentialFittingHestonEngine(model)` - asserting sse ~= 177.2 for each.
    /// The latter two are separate, unported Heston engines (tracked by issue
    /// #424); only the Analytic arm is ported here. Because the single arm
    /// calibrates straight from the seed, the `model.setParams(params)` reset the
    /// C++ multi-engine loop needs between arms (cpp:348-350) is not required.
    #[test]
    fn heston_calibrates_to_dax_vol_data() {
        let market = dax_market_data();

        let process = shared(HestonProcess::new(
            market.risk_free.clone(),
            market.dividend.clone(),
            market.s0.clone(),
            0.1,
            1.0,
            0.1,
            0.5,
            -0.5,
        ));
        let model = HestonModel::new(process).unwrap();
        let engine = shared_mut(AnalyticHestonEngine::new(SharedMut::clone(&model), 64).unwrap())
            as SharedMut<dyn PricingEngine>;

        for helper in &market.options {
            helper
                .borrow_mut()
                .base_mut()
                .set_pricing_engine(SharedMut::clone(&engine));
        }
        let dyn_helpers: Vec<SharedMut<dyn CalibrationHelper>> = market
            .options
            .iter()
            .map(|helper| SharedMut::clone(helper) as SharedMut<dyn CalibrationHelper>)
            .collect();

        let mut method = LevenbergMarquardt::new(1e-8, 1e-8, 1e-8, false);
        let end_criteria = EndCriteria::new(400, Some(40), 1e-8, 1e-8, Some(1e-8)).unwrap();
        calibrate(
            &model,
            &dyn_helpers,
            &mut method,
            &end_criteria,
            None,
            Vec::new(),
            Vec::new(),
        )
        .unwrap();

        let mut sse = 0.0;
        for helper in &market.options {
            let diff = helper.borrow_mut().calibration_error().unwrap() * 100.0;
            sse += diff * diff;
        }
        assert!(
            (sse - 177.2).abs() < 1.0,
            "sse {sse} vs expected 177.2 (error {})",
            (sse - 177.2).abs()
        );
    }
}