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
//! Swaption volatility cube base.
//!
//! Port of `ql/termstructures/volatility/swaption/swaptionvolcube.{hpp,cpp}`:
//! `class SwaptionVolatilityCube : public SwaptionVolatilityDiscrete`. This is
//! the framework the two concrete cubes extend - the interpolated cube (#595)
//! and the SABR cube (#596). It holds the at-the-money surface as a
//! [`Handle`], the strike spreads relative to the ATM level, a grid of
//! per-node volatility-spread quotes, and the long and short base
//! [`SwapIndex`]es from whose conventions [`atm_strike`](SwaptionVolatilityCube::atm_strike)
//! rebuilds an on-the-fly swap rate.
//!
//! ## Composition, not a trait
//!
//! C++ derives from `SwaptionVolatilityDiscrete`; Rust has no inheritance, so -
//! exactly as [`SwaptionVolatilityMatrix`](super::SwaptionVolatilityMatrix)
//! does - this is a reusable struct embedding [`SwaptionVolatilityDiscrete`] for
//! the shared tenor/date/time grid. A concrete cube embeds this base in turn and
//! implements the [`SwaptionVolatilityStructure`] trait, routing its
//! `volatility_impl` through the [`SwaptionCubeSmileSection`] smile hook.
//!
//! ## The smile seam
//!
//! C++'s `volatilityImpl` calls the pure-virtual `smileSectionImpl` and takes
//! its `volatility(strike)`. The base struct cannot call up into the concrete
//! that embeds it, so the hook is the [`SwaptionCubeSmileSection`] trait: the
//! concrete supplies [`smile_section_impl`](SwaptionCubeSmileSection::smile_section_impl)
//! and the provided [`cube_volatility_impl`](SwaptionCubeSmileSection::cube_volatility_impl)
//! is the faithful port of the routing. The base is therefore complete except
//! for that one hook.
//!
//! ## Divergences from QuantLib
//!
//! - The embedded discrete grid is built through
//!   [`SwaptionVolatilityDiscrete::moving`], which per D5 takes the shared
//!   [`Settings`] handle explicitly (C++ reads the global singleton). This
//!   follows [`SwaptionVolatilityMatrix::moving`]'s signature; the cube
//!   constructor threads the same handle.
//! - The `nStrikes >= requiredNumberOfStrikes()` check is C++'s
//!   `performCalculations` guard (it defers because the required count is
//!   virtual). Here the base count is a fixed constant, so the check runs at
//!   construction and returns `Err` per D4, rather than on first use.
//! - `atmStrike` calls the reconstructed index's `.fixing(optionDate, false)`,
//!   as C++ does (`.fixing(optionD)`, whose default `forecastTodaysFixing` is
//!   false): a strictly-future date forecasts the underlying swap's fair rate, a
//!   past or today date routes to the D11 fixing store.
//! - The embedded discrete grid anchors to the moving reference date
//!   (`eval_date + 0` settlement days), whereas C++ overrides `referenceDate()`
//!   to delegate to `atmVol_->referenceDate()` (hpp:55) and builds its
//!   option-date grid off that. The two agree for the expected case - a
//!   settlement-0 moving ATM surface - and diverge for a fixed-reference or
//!   non-zero-settlement ATM surface. `atm_strike` takes an explicit option date
//!   and is unaffected either way; the grid this anchors is what the interpolated
//!   cube (#595) will read, so #595 must confirm the anchoring against its ATM
//!   surface before interpolating.

use crate::errors::QlResult;
use crate::handle::Handle;
use crate::indexes::{Index, InterestRateIndex, SwapIndex};
use crate::patterns::observable::Observable;
use crate::quotes::Quote;
use crate::settings::Settings;
use crate::shared::Shared;
use crate::termstructures::TermStructureBase;
use crate::termstructures::volatility::{SmileSection, VolatilityType};
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::date::Date;
use crate::time::period::Period;
use crate::types::{Rate, Real, Time, Volatility};
use crate::{fail, require};

use super::{SwaptionVolatilityDiscrete, SwaptionVolatilityStructure};

/// The smallest number of strikes the base cube accepts, C++'s
/// `requiredNumberOfStrikes()` base return (swaptionvolcube.hpp:97). A concrete
/// cube that needs more enforces the stronger bound itself.
const REQUIRED_NUMBER_OF_STRIKES: usize = 2;

/// The smile-section hook a swaption vol cube's concrete surfaces provide.
///
/// Port of `SwaptionVolatilityCube::smileSectionImpl` (pure virtual,
/// swaptionvolcube.hpp:98-100). The interpolated cube (#595) and the SABR cube
/// (#596) each build a [`SmileSection`] for an (option time, swap length) node;
/// the base's volatility routing (`volatilityImpl`, hpp:118-123) is the provided
/// [`cube_volatility_impl`](Self::cube_volatility_impl), the port of
/// `smileSectionImpl(optionTime, swapLength)->volatility(strike)`.
pub trait SwaptionCubeSmileSection {
    /// The smile section at `option_time` and `swap_length`.
    fn smile_section_impl(
        &self,
        option_time: Time,
        swap_length: Time,
    ) -> QlResult<Shared<dyn SmileSection>>;

    /// The cube volatility at `strike`: the smile section's volatility there.
    fn cube_volatility_impl(
        &self,
        option_time: Time,
        swap_length: Time,
        strike: Rate,
    ) -> QlResult<Volatility> {
        self.smile_section_impl(option_time, swap_length)?
            .volatility(strike)
    }
}

/// Swaption volatility cube base, embedding the discrete tenor/date/time grid.
pub struct SwaptionVolatilityCube {
    discrete: SwaptionVolatilityDiscrete,
    atm_vol: Handle<dyn SwaptionVolatilityStructure>,
    strike_spreads: Vec<Real>,
    vol_spreads: Vec<Vec<Handle<dyn Quote>>>,
    swap_index_base: Shared<SwapIndex>,
    short_swap_index_base: Shared<SwapIndex>,
    vega_weighted_smile_fit: bool,
}

impl SwaptionVolatilityCube {
    /// Builds the cube framework off the ATM surface, the strike/vol-spread grid
    /// and the two base swap indexes (C++'s single constructor,
    /// swaptionvolcube.cpp:28-79).
    ///
    /// The discrete grid is built moving with zero settlement days from the ATM
    /// surface's calendar, business-day convention and day counter, mirroring
    /// C++'s `SwaptionVolatilityDiscrete(optionTenors, swapTenors, 0,
    /// atmVol->calendar(), atmVol->businessDayConvention(),
    /// atmVol->dayCounter())`; `settings` is the D5 handle that constructor
    /// needs.
    ///
    /// `vol_spreads` is row-major over the `(option tenor, swap tenor)` nodes:
    /// row `i*nSwapTenors + j` is the option-`i`, swap-`j` node, and every row
    /// holds one quote per strike spread.
    ///
    /// # Errors
    ///
    /// Returns `Err` when the ATM handle is empty or lacks a calendar or day
    /// counter, when there are fewer than [`REQUIRED_NUMBER_OF_STRIKES`] strike
    /// spreads or they are not strictly increasing, when the vol-spread grid does
    /// not match `nOptionTenors * nSwapTenors` rows by `nStrikes` columns, or
    /// when the short index tenor exceeds the long index tenor.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        atm_vol: Handle<dyn SwaptionVolatilityStructure>,
        option_tenors: Vec<Period>,
        swap_tenors: Vec<Period>,
        strike_spreads: Vec<Real>,
        vol_spreads: Vec<Vec<Handle<dyn Quote>>>,
        swap_index_base: Shared<SwapIndex>,
        short_swap_index_base: Shared<SwapIndex>,
        vega_weighted_smile_fit: bool,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<SwaptionVolatilityCube> {
        let atm = atm_vol.current_link()?;
        let Some(calendar) = atm.calendar() else {
            fail!("atm vol structure has no calendar");
        };
        let business_day_convention = atm.business_day_convention();
        let Some(day_counter) = atm.day_counter() else {
            fail!("atm vol structure has no day counter");
        };

        let discrete = SwaptionVolatilityDiscrete::moving(
            option_tenors,
            swap_tenors,
            0,
            calendar,
            business_day_convention,
            day_counter,
            settings,
        )?;

        let n_strikes = strike_spreads.len();
        require!(
            n_strikes >= REQUIRED_NUMBER_OF_STRIKES,
            "too few strikes ({n_strikes}): at least {REQUIRED_NUMBER_OF_STRIKES} are required"
        );
        for i in 1..n_strikes {
            let increasing = strike_spreads[i - 1] < strike_spreads[i];
            require!(
                increasing,
                "non increasing strike spreads: {} is {}, {} is {}",
                i,
                strike_spreads[i - 1],
                i + 1,
                strike_spreads[i]
            );
        }

        require!(!vol_spreads.is_empty(), "empty vol spreads matrix");
        let n_options = discrete.option_tenors().len();
        let n_swaps = discrete.swap_tenors().len();
        require!(
            n_options * n_swaps == vol_spreads.len(),
            "mismatch between number of option tenors * swap tenors ({}) and number of rows ({})",
            n_options * n_swaps,
            vol_spreads.len()
        );
        for (i, row) in vol_spreads.iter().enumerate() {
            require!(
                row.len() == n_strikes,
                "mismatch between number of strikes ({n_strikes}) and number of columns ({}) in the {} row",
                row.len(),
                i + 1
            );
        }

        let updater = discrete.base().updater();
        atm_vol.register_observer(&updater);
        atm.enable_extrapolation();

        swap_index_base
            .base()
            .observable()
            .register_observer(&updater);
        short_swap_index_base
            .base()
            .observable()
            .register_observer(&updater);

        let short_not_longer = short_swap_index_base.tenor() <= swap_index_base.tenor();
        require!(
            short_not_longer,
            "short index tenor ({}) is not less or equal than index tenor ({})",
            short_swap_index_base.tenor(),
            swap_index_base.tenor()
        );

        for row in &vol_spreads {
            for handle in row {
                handle.register_observer(&updater);
            }
        }

        Ok(SwaptionVolatilityCube {
            discrete,
            atm_vol,
            strike_spreads,
            vol_spreads,
            swap_index_base,
            short_swap_index_base,
            vega_weighted_smile_fit,
        })
    }

    /// The embedded discrete grid, for a concrete cube to read its option
    /// times/dates and swap lengths and to route its `TermStructure` impl.
    pub fn discrete(&self) -> &SwaptionVolatilityDiscrete {
        &self.discrete
    }

    /// The embedded term-structure holder, for the concrete's `TermStructure`
    /// impl to route through.
    pub fn base(&self) -> &TermStructureBase {
        self.discrete.base()
    }

    /// The observable the cube notifies downstream observers through.
    pub fn observable(&self) -> &Observable {
        self.discrete.observable()
    }

    /// Rebuilds the discrete grid if the reference date has moved. A concrete
    /// cube calls this before a grid-dependent query.
    pub fn calculate(&self) -> QlResult<()> {
        self.discrete.calculate()
    }

    /// The business-day convention used in tenor-to-date conversion.
    pub fn business_day_convention(&self) -> BusinessDayConvention {
        self.discrete.business_day_convention()
    }

    /// The at-the-money surface (`atmVol()`).
    pub fn atm_vol(&self) -> Handle<dyn SwaptionVolatilityStructure> {
        self.atm_vol.clone()
    }

    /// The strike spreads relative to the ATM level (`strikeSpreads()`).
    pub fn strike_spreads(&self) -> &[Real] {
        &self.strike_spreads
    }

    /// The per-node volatility-spread quotes, row-major over the
    /// `(option tenor, swap tenor)` nodes (`volSpreads()`).
    pub fn vol_spreads(&self) -> &[Vec<Handle<dyn Quote>>] {
        &self.vol_spreads
    }

    /// The long base swap index (`swapIndexBase()`).
    pub fn swap_index_base(&self) -> Shared<SwapIndex> {
        Shared::clone(&self.swap_index_base)
    }

    /// The short base swap index (`shortSwapIndexBase()`).
    pub fn short_swap_index_base(&self) -> Shared<SwapIndex> {
        Shared::clone(&self.short_swap_index_base)
    }

    /// Whether the smiles are fitted with vega weighting (`vegaWeightedSmileFit()`).
    pub fn vega_weighted_smile_fit(&self) -> bool {
        self.vega_weighted_smile_fit
    }

    /// The volatility type the cube quotes, taken from the ATM surface
    /// (`volatilityType()`).
    ///
    /// # Errors
    ///
    /// Returns `Err` when the ATM handle is empty.
    pub fn volatility_type(&self) -> QlResult<VolatilityType> {
        Ok(self.atm_vol.current_link()?.volatility_type())
    }

    /// The at-the-money strike for an option date and swap tenor
    /// (`atmStrike`, swaptionvolcube.cpp:89-144).
    ///
    /// Reconstructs a [`SwapIndex`] with `swap_tenor` from the conventions of the
    /// long base index when `swap_tenor` exceeds the short index tenor, else the
    /// short base index, and takes its `.fixing(option_date, false)`: the fair
    /// rate of the underlying swap for a strictly-future date, or the stored
    /// fixing (D11) for a past or today date.
    ///
    /// # Errors
    ///
    /// Propagates the reconstructed index's fixing.
    pub fn atm_strike(&self, option_date: Date, swap_tenor: Period) -> QlResult<Rate> {
        let chosen = if swap_tenor > self.short_swap_index_base.tenor() {
            &self.swap_index_base
        } else {
            &self.short_swap_index_base
        };
        let settings = chosen.base().settings().clone();
        let index = if chosen.exogenous_discount() {
            SwapIndex::with_exogenous_discount(
                chosen.family_name().to_string(),
                swap_tenor,
                chosen.fixing_days(),
                chosen.currency().clone(),
                chosen.fixing_calendar(),
                chosen.fixed_leg_tenor(),
                chosen.fixed_leg_convention(),
                chosen.day_counter().clone(),
                chosen.ibor_index(),
                chosen.discounting_term_structure(),
                settings,
            )
        } else {
            SwapIndex::new(
                chosen.family_name().to_string(),
                swap_tenor,
                chosen.fixing_days(),
                chosen.currency().clone(),
                chosen.fixing_calendar(),
                chosen.fixed_leg_tenor(),
                chosen.fixed_leg_convention(),
                chosen.day_counter().clone(),
                chosen.ibor_index(),
                settings,
            )
        };
        index.fixing(option_date, false)
    }

    /// The at-the-money strike for an option tenor and swap tenor (C++'s inline
    /// `atmStrike(optionTenor, swapTenor)`, swaptionvolcube.hpp:71-75): resolves
    /// the option date off the reference date, then delegates to
    /// [`atm_strike`](Self::atm_strike).
    ///
    /// # Errors
    ///
    /// Returns `Err` when the grid has no calendar or reference date, or
    /// propagates [`atm_strike`](Self::atm_strike).
    pub fn atm_strike_from_tenor(
        &self,
        option_tenor: Period,
        swap_tenor: Period,
    ) -> QlResult<Rate> {
        let Some(calendar) = self.discrete.base().calendar() else {
            fail!("no calendar for swaption vol cube");
        };
        let reference = self.discrete.base().reference_date()?;
        let option_date = calendar.advance_by_period(
            reference,
            option_tenor,
            self.business_day_convention(),
            false,
        );
        self.atm_strike(option_date, swap_tenor)
    }
}

/// These tests pin the cube framework standalone; the ATM-recovery oracle
/// (`testAtmVols`) needs a concrete smile and folds into #595. They cover:
/// `atm_strike`'s branch selection and convention plumbing against
/// independently built swap indexes (long-and-exogenous vs short-and-plain, two
/// of the four C++ branches - the two remaining exogenous/plain mirrors are
/// deferred with #596's calibration tests), the four construction guards, and
/// the smile-hook routing through a minimal stub concrete.
#[cfg(test)]
mod tests {
    use super::*;

    use crate::currency::Currency;
    use crate::indexes::{Euribor, IborIndex};
    use crate::interestrate::Compounding;
    use crate::patterns::observable::AsObservable;
    use crate::quotes::make_quote_handle;
    use crate::shared::shared;
    use crate::termstructures::volatility::FlatSmileSection;
    use crate::termstructures::yields::FlatForward;
    use crate::termstructures::yieldtermstructure::YieldTermStructure;
    use crate::termstructures::{TermStructure, volatility::VolatilityTermStructure};
    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::daycounters::thirty360::{Convention, Thirty360};
    use crate::time::frequency::Frequency;
    use crate::time::timeunit::TimeUnit;

    const BDC: BusinessDayConvention = BusinessDayConvention::ModifiedFollowing;

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

    fn option_date() -> Date {
        Date::new(15, Month::June, 2027)
    }

    /// A flat swaption vol surface standing in for the ATM matrix: the cube reads
    /// its calendar, business-day convention and day counter and enables its
    /// extrapolation. Its own reference date is unused by the cube's grid, which
    /// is moving off `Settings`.
    struct MockAtmVol {
        base: TermStructureBase,
        vol: Volatility,
    }

    impl AsObservable for MockAtmVol {
        fn observable(&self) -> &Observable {
            self.base.observable()
        }
    }

    impl TermStructure for MockAtmVol {
        fn base(&self) -> &TermStructureBase {
            &self.base
        }
        fn max_date(&self) -> Date {
            Date::max_date()
        }
    }

    impl VolatilityTermStructure for MockAtmVol {
        fn business_day_convention(&self) -> BusinessDayConvention {
            BDC
        }
        fn min_strike(&self) -> Rate {
            Rate::MIN
        }
        fn max_strike(&self) -> Rate {
            Rate::MAX
        }
    }

    impl SwaptionVolatilityStructure for MockAtmVol {
        fn volatility_impl(&self, _t: Time, _l: Time, _strike: Rate) -> QlResult<Volatility> {
            Ok(self.vol)
        }
        fn max_swap_tenor(&self) -> Period {
            Period::new(100, TimeUnit::Years)
        }
    }

    fn settings_today() -> Shared<Settings<Date>> {
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(today());
        settings
    }

    fn flat_curve(rate: Rate) -> Handle<dyn YieldTermStructure> {
        Handle::new(shared(FlatForward::with_rate(
            today(),
            rate,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>)
    }

    fn atm_handle(vol: Volatility) -> Handle<dyn SwaptionVolatilityStructure> {
        Handle::new(shared(MockAtmVol {
            base: TermStructureBase::with_reference_date(
                today(),
                Some(Target::new()),
                Some(Actual365Fixed::new()),
            ),
            vol,
        }) as Shared<dyn SwaptionVolatilityStructure>)
    }

    /// The long base index: 5Y, annual fixed leg, discounting off a separate
    /// curve. The exogenous discount and the annual leg are what make the
    /// long-branch oracle discriminating against the short base.
    fn long_index(
        euribor6m: &Shared<IborIndex>,
        discount: &Handle<dyn YieldTermStructure>,
        settings: &Shared<Settings<Date>>,
    ) -> SwapIndex {
        SwapIndex::with_exogenous_discount(
            "LongSwap".into(),
            Period::new(5, TimeUnit::Years),
            2,
            Currency::eur(),
            Target::new(),
            Period::new(1, TimeUnit::Years),
            BDC,
            Thirty360::with_convention(Convention::BondBasis),
            Shared::clone(euribor6m),
            discount.clone(),
            Shared::clone(settings),
        )
    }

    /// The short base index: 1Y, semiannual fixed leg, no exogenous discount.
    fn short_index(euribor6m: &Shared<IborIndex>, settings: &Shared<Settings<Date>>) -> SwapIndex {
        SwapIndex::new(
            "ShortSwap".into(),
            Period::new(1, TimeUnit::Years),
            2,
            Currency::eur(),
            Target::new(),
            Period::new(6, TimeUnit::Months),
            BDC,
            Thirty360::with_convention(Convention::BondBasis),
            Shared::clone(euribor6m),
            Shared::clone(settings),
        )
    }

    struct Parts {
        settings: Shared<Settings<Date>>,
        euribor6m: Shared<IborIndex>,
        discount: Handle<dyn YieldTermStructure>,
        long: Shared<SwapIndex>,
        short: Shared<SwapIndex>,
    }

    fn parts() -> Parts {
        let settings = settings_today();
        let euribor6m = shared(Euribor::six_months(
            flat_curve(0.05),
            Shared::clone(&settings),
        ));
        let discount = flat_curve(0.03);
        let long = shared(long_index(&euribor6m, &discount, &settings));
        let short = shared(short_index(&euribor6m, &settings));
        Parts {
            settings,
            euribor6m,
            discount,
            long,
            short,
        }
    }

    fn option_tenors() -> Vec<Period> {
        vec![
            Period::new(1, TimeUnit::Years),
            Period::new(2, TimeUnit::Years),
        ]
    }

    fn swap_tenors() -> Vec<Period> {
        vec![
            Period::new(1, TimeUnit::Years),
            Period::new(5, TimeUnit::Years),
        ]
    }

    fn vol_spreads(n_rows: usize, n_strikes: usize) -> Vec<Vec<Handle<dyn Quote>>> {
        (0..n_rows)
            .map(|_| {
                (0..n_strikes)
                    .map(|_| make_quote_handle(0.001).handle())
                    .collect()
            })
            .collect()
    }

    fn build_cube(
        p: &Parts,
        strike_spreads: Vec<Real>,
        vol_spreads: Vec<Vec<Handle<dyn Quote>>>,
    ) -> QlResult<SwaptionVolatilityCube> {
        SwaptionVolatilityCube::new(
            atm_handle(0.2),
            option_tenors(),
            swap_tenors(),
            strike_spreads,
            vol_spreads,
            Shared::clone(&p.long),
            Shared::clone(&p.short),
            false,
            Shared::clone(&p.settings),
        )
    }

    fn valid_cube(p: &Parts) -> SwaptionVolatilityCube {
        build_cube(p, vec![-0.01, 0.0, 0.01], vol_spreads(4, 3)).unwrap()
    }

    #[test]
    fn atm_strike_long_branch_uses_the_long_base_conventions() {
        let p = parts();
        let cube = valid_cube(&p);
        let swap_tenor = Period::new(2, TimeUnit::Years);

        let mut expected_index = long_index(&p.euribor6m, &p.discount, &p.settings);
        expected_index = SwapIndex::with_exogenous_discount(
            "LongSwap".into(),
            swap_tenor,
            2,
            Currency::eur(),
            Target::new(),
            Period::new(1, TimeUnit::Years),
            BDC,
            Thirty360::with_convention(Convention::BondBasis),
            expected_index.ibor_index(),
            p.discount.clone(),
            Shared::clone(&p.settings),
        );
        let expected = expected_index.fixing(option_date(), false).unwrap();

        let got = cube.atm_strike(option_date(), swap_tenor).unwrap();
        assert!(
            (got - expected).abs() < 1e-14,
            "long-branch atm strike {got} vs independently built {expected}"
        );
        assert!(got > 0.0, "a positive swap rate off a 5% forwarding curve");
    }

    #[test]
    fn atm_strike_short_branch_uses_the_short_base_conventions() {
        let p = parts();
        let cube = valid_cube(&p);
        let swap_tenor = Period::new(1, TimeUnit::Years);

        let expected_index = SwapIndex::new(
            "ShortSwap".into(),
            swap_tenor,
            2,
            Currency::eur(),
            Target::new(),
            Period::new(6, TimeUnit::Months),
            BDC,
            Thirty360::with_convention(Convention::BondBasis),
            Shared::clone(&p.euribor6m),
            Shared::clone(&p.settings),
        );
        let expected = expected_index.fixing(option_date(), false).unwrap();

        let got = cube.atm_strike(option_date(), swap_tenor).unwrap();
        assert!(
            (got - expected).abs() < 1e-14,
            "short-branch atm strike {got} vs independently built {expected}"
        );
    }

    #[test]
    fn atm_strike_branches_differ_by_base() {
        let p = parts();
        let cube = valid_cube(&p);
        let long_branch = cube
            .atm_strike(option_date(), Period::new(2, TimeUnit::Years))
            .unwrap();
        let short_branch = cube
            .atm_strike(option_date(), Period::new(1, TimeUnit::Years))
            .unwrap();
        assert!(
            (long_branch - short_branch).abs() > 1e-6,
            "the two bases must produce distinct rates, got {long_branch} and {short_branch}"
        );
    }

    #[test]
    fn too_few_strikes_is_rejected() {
        let p = parts();
        assert!(build_cube(&p, vec![0.0], vol_spreads(4, 1)).is_err());
    }

    #[test]
    fn non_increasing_strike_spreads_are_rejected() {
        let p = parts();
        assert!(build_cube(&p, vec![0.01, 0.0, -0.01], vol_spreads(4, 3)).is_err());
    }

    #[test]
    fn wrong_shaped_vol_spreads_are_rejected() {
        let p = parts();
        assert!(
            build_cube(&p, vec![-0.01, 0.0, 0.01], vol_spreads(3, 3)).is_err(),
            "row count must equal option tenors * swap tenors"
        );
        assert!(
            build_cube(&p, vec![-0.01, 0.0, 0.01], vol_spreads(4, 2)).is_err(),
            "each row must hold one quote per strike"
        );
    }

    #[test]
    fn short_tenor_longer_than_long_tenor_is_rejected() {
        let p = parts();
        let swapped = SwaptionVolatilityCube::new(
            atm_handle(0.2),
            option_tenors(),
            swap_tenors(),
            vec![-0.01, 0.0, 0.01],
            vol_spreads(4, 3),
            Shared::clone(&p.short),
            Shared::clone(&p.long),
            false,
            Shared::clone(&p.settings),
        );
        assert!(
            swapped.is_err(),
            "short (5Y) longer than long (1Y) must be rejected"
        );
    }

    /// A minimal concrete cube supplying the smile hook, proving
    /// `volatility_impl` routes through `cube_volatility_impl` into the smile
    /// section's `volatility`.
    struct StubCube {
        cube: SwaptionVolatilityCube,
        flat_vol: Volatility,
    }

    impl SwaptionCubeSmileSection for StubCube {
        fn smile_section_impl(
            &self,
            option_time: Time,
            swap_length: Time,
        ) -> QlResult<Shared<dyn SmileSection>> {
            let _ = swap_length;
            let section = FlatSmileSection::with_exercise_time(
                option_time,
                self.flat_vol,
                Actual365Fixed::new(),
                Some(0.03),
                VolatilityType::ShiftedLognormal,
                0.0,
            )?;
            Ok(shared(section) as Shared<dyn SmileSection>)
        }
    }

    impl AsObservable for StubCube {
        fn observable(&self) -> &Observable {
            self.cube.observable()
        }
    }

    impl TermStructure for StubCube {
        fn base(&self) -> &TermStructureBase {
            self.cube.base()
        }
        fn max_date(&self) -> Date {
            self.cube
                .atm_vol()
                .current_link()
                .map(|a| a.max_date())
                .unwrap_or_else(|_| Date::max_date())
        }
    }

    impl VolatilityTermStructure for StubCube {
        fn business_day_convention(&self) -> BusinessDayConvention {
            self.cube.business_day_convention()
        }
        fn min_strike(&self) -> Rate {
            Rate::MIN
        }
        fn max_strike(&self) -> Rate {
            Rate::MAX
        }
    }

    impl SwaptionVolatilityStructure for StubCube {
        fn volatility_impl(
            &self,
            option_time: Time,
            swap_length: Time,
            strike: Rate,
        ) -> QlResult<Volatility> {
            self.cube_volatility_impl(option_time, swap_length, strike)
        }
        fn max_swap_tenor(&self) -> Period {
            Period::new(100, TimeUnit::Years)
        }
        fn volatility_type(&self) -> VolatilityType {
            self.cube
                .volatility_type()
                .unwrap_or(VolatilityType::ShiftedLognormal)
        }
    }

    #[test]
    fn volatility_impl_routes_through_the_smile_hook() {
        let p = parts();
        let stub = StubCube {
            cube: valid_cube(&p),
            flat_vol: 0.17,
        };
        for strike in [0.01, 0.03, 0.08] {
            let got = stub.volatility_impl(1.0, 5.0, strike).unwrap();
            assert!(
                (got - 0.17).abs() < 1e-15,
                "routing must return the flat smile vol at strike {strike}, got {got}"
            );
        }
    }
}