libitofin 0.52.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
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
//! Swaption instrument and its settlement conventions.
//!
//! Port of `ql/instruments/swaption.{hpp,cpp}`. A [`Swaption`] is an option to
//! enter a [`FixedVsFloatingSwap`](crate::instruments::FixedVsFloatingSwap) at a
//! given [`Exercise`] date, settled per a [`SettlementType`] /
//! [`SettlementMethod`] pair.
//!
//! ## Divergences from QuantLib
//!
//! - `Swaption : Option` passes a null payoff (`swaption.cpp:137`) and
//!   `arguments::validate` never reaches `Option::arguments`'s payoff
//!   requirement, so there is no Rust option base: the type owns an
//!   [`InstrumentBase`](crate::instrument::InstrumentBase) directly and carries
//!   only the `exercise` that `Option::arguments` contributes.
//! - The `swap_` member is `SharedMut<FixedVsFloatingSwap>`, not the immutable
//!   [`Shared`], because the engine (#361, `blackswaptionengine.hpp:248-259`)
//!   sets a pricing engine on the swap and reads its `fairRate`, `fixedLegBPS`
//!   and `floatingLegBPS`, all of which take `&mut`. C++'s
//!   `shared_ptr<FixedVsFloatingSwap>` permits that mutation; the faithful Rust
//!   shared-mutable pointer is [`SharedMut`].
//! - `Settlement::Type`, `Settlement::Method` and
//!   `Settlement::checkTypeAndMethodConsistency` become the free
//!   [`SettlementType`], [`SettlementMethod`] and
//!   [`check_type_and_method_consistency`]; the consistency check returns a
//!   [`QlResult`] rather than throwing.
//! - [`Swaption::implied_volatility`] uses temporary Black or Bachelier
//!   engines and NewtonSafe, including spot and forward price conventions.
//!   The `deepUpdate` observer optimisation remains deferred.
//!
//! [`MakeSwaption`](crate::instruments::MakeSwaption) builds vanilla swaptions
//! from a [`SwapIndex`](crate::indexes::SwapIndex).

use std::any::Any;
use std::cell::RefCell;

use crate::errors::QlResult;
use crate::event::event_has_occurred;
use crate::exercise::{Exercise, ExerciseType};
use crate::handle::Handle;
use crate::instrument::{Instrument, InstrumentBase, InstrumentResults};
use crate::instruments::fixedvsfloatingswap::{FixedVsFloatingSwap, FixedVsFloatingSwapArguments};
use crate::instruments::swap::SwapType;
use crate::math::solver1d::{DerivativeSolver, Function1D};
use crate::math::solvers1d::newtonsafe::NewtonSafe;
use crate::pricingengine::{Arguments, GenericEngine, PricingEngine};
use crate::pricingengines::swaption::{
    BachelierSwaptionEngine, BlackSwaptionEngine, CashAnnuityModel,
};
use crate::quotes::{Quote, SimpleQuote};
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut, shared};
use crate::termstructures::volatility::VolatilityType;
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::time::date::Date;
use crate::time::daycounters::actual365fixed::Actual365Fixed;
use crate::types::{Real, Size, Volatility};
use crate::{fail, require};

/// Whether an implied-vol target is a spot NPV or a forward price
/// (`Swaption::PriceType`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SwaptionPriceType {
    /// Spot NPV (`Swaption::Spot`).
    #[default]
    Spot,
    /// Forward price (`Swaption::Forward`); converted to spot via the discount
    /// to the exercise date before the Newton solve.
    Forward,
}

/// How a swaption is settled on exercise (`Settlement::Type`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SettlementType {
    /// The holder enters the physical swap.
    #[default]
    Physical,
    /// The swap's value is settled in cash.
    Cash,
}

/// The convention used to settle a swaption (`Settlement::Method`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SettlementMethod {
    /// Physical delivery, over-the-counter.
    #[default]
    PhysicalOTC,
    /// Physical delivery, cleared.
    PhysicalCleared,
    /// Cash settled at the collateralised cash price.
    CollateralizedCashPrice,
    /// Cash settled off the par-yield curve.
    ParYieldCurve,
}

/// Checks that a settlement type and method are compatible
/// (`Settlement::checkTypeAndMethodConsistency`, `swaption.cpp:207`).
///
/// Physical settlement pairs with [`PhysicalOTC`](SettlementMethod::PhysicalOTC)
/// or [`PhysicalCleared`](SettlementMethod::PhysicalCleared); cash settlement
/// pairs with
/// [`CollateralizedCashPrice`](SettlementMethod::CollateralizedCashPrice) or
/// [`ParYieldCurve`](SettlementMethod::ParYieldCurve).
///
/// # Errors
///
/// The type and method must match.
pub fn check_type_and_method_consistency(
    settlement_type: SettlementType,
    settlement_method: SettlementMethod,
) -> QlResult<()> {
    match settlement_type {
        SettlementType::Physical => require!(
            matches!(
                settlement_method,
                SettlementMethod::PhysicalOTC | SettlementMethod::PhysicalCleared
            ),
            "invalid settlement method for physical settlement"
        ),
        SettlementType::Cash => require!(
            matches!(
                settlement_method,
                SettlementMethod::CollateralizedCashPrice | SettlementMethod::ParYieldCurve
            ),
            "invalid settlement method for cash settlement"
        ),
    }
    Ok(())
}

/// Argument bundle a `Swaption::engine` prices (`Swaption::arguments`).
///
/// The C++ `Swaption::arguments` derives from both
/// `FixedVsFloatingSwap::arguments` (the swap half) and `Option::arguments`
/// (which contributes only `exercise`, the payoff being null); here the swap
/// half is embedded and the exercise carried directly.
#[derive(Default)]
pub struct SwaptionArguments {
    /// The underlying swap's arguments.
    pub swap_arguments: FixedVsFloatingSwapArguments,
    /// The underlying swap.
    pub swap: Option<SharedMut<FixedVsFloatingSwap>>,
    /// How the swaption settles on exercise.
    pub settlement_type: SettlementType,
    /// The settlement method.
    pub settlement_method: SettlementMethod,
    /// The exercise schedule (the C++ `Option::arguments::exercise`).
    pub exercise: Option<Shared<dyn Exercise>>,
}

impl Arguments for SwaptionArguments {
    fn validate(&self) -> QlResult<()> {
        self.swap_arguments.validate()?;
        require!(self.swap.is_some(), "swap not set");
        require!(self.exercise.is_some(), "exercise not set");
        check_type_and_method_consistency(self.settlement_type, self.settlement_method)
    }
}

/// Engine base for swaptions (the C++ `Swaption::engine`).
pub type SwaptionEngine = GenericEngine<SwaptionArguments, InstrumentResults>;

/// An option to enter a [`FixedVsFloatingSwap`] at the exercise date.
///
/// Wraps the underlying swap through a [`SharedMut`] so that a pricing engine
/// (#361) can set an engine on it and read its fair rate and leg BPS.
pub struct Swaption {
    base: InstrumentBase,
    swap: SharedMut<FixedVsFloatingSwap>,
    settlement_type: SettlementType,
    settlement_method: SettlementMethod,
    exercise: Shared<dyn Exercise>,
    settings: Shared<Settings<Date>>,
}

impl Swaption {
    /// Builds a swaption over `swap`, exercisable per `exercise` and settled by
    /// the `settlement_type` / `settlement_method` pair (the C++ ctor,
    /// `swaption.cpp:133`).
    ///
    /// The swaption observes the swap (the C++ `registerWith(swap_)`) and, per
    /// D5, the `settings` evaluation date its expiry check reads. The
    /// (type, method) pair is not checked here; the consistency check runs in
    /// [`SwaptionArguments::validate`], matching C++.
    pub fn new(
        swap: SharedMut<FixedVsFloatingSwap>,
        exercise: Shared<dyn Exercise>,
        settlement_type: SettlementType,
        settlement_method: SettlementMethod,
        settings: Shared<Settings<Date>>,
    ) -> Swaption {
        let base = InstrumentBase::new();
        swap.borrow().base().register_observer(&base.observer());
        settings.register_eval_date_observer(&base.observer());
        Swaption {
            base,
            swap,
            settlement_type,
            settlement_method,
            exercise,
            settings,
        }
    }

    /// How the swaption settles on exercise (`settlementType()`).
    pub fn settlement_type(&self) -> SettlementType {
        self.settlement_type
    }

    /// The settlement method (`settlementMethod()`).
    pub fn settlement_method(&self) -> SettlementMethod {
        self.settlement_method
    }

    /// Whether the underlying swap pays or receives the fixed leg (`type()`,
    /// forwarded to the swap).
    pub fn swap_type(&self) -> SwapType {
        self.swap.borrow().swap_type()
    }

    /// The underlying swap (`underlying()`).
    pub fn underlying(&self) -> &SharedMut<FixedVsFloatingSwap> {
        &self.swap
    }

    /// The exercise schedule (`exercise()`, on the C++ `Option` base).
    pub fn exercise(&self) -> &Shared<dyn Exercise> {
        &self.exercise
    }

    /// Implied term volatility that reprices this swaption to `target_value`
    /// (`Swaption::impliedVolatility`, `swaption.cpp:182-205`).
    ///
    /// Uses [`NewtonSafe`] on a temporary Black or Bachelier engine whose flat
    /// vol is a [`SimpleQuote`], matching `ImpliedSwaptionVolHelper`. Defaults
    /// in C++: `accuracy = 1e-4`, `max_evaluations = 100`, `min_vol = 1e-7`,
    /// `max_vol = 4.0`, `ShiftedLognormal`, `displacement = 0.0`, Spot.
    ///
    /// A [`SwaptionPriceType::Forward`] target is converted to spot by
    /// multiplying by the discount to the first exercise date.
    ///
    /// # Errors
    ///
    /// Rejects expired or non-European options, non-finite inputs, negative
    /// target prices or volatility bounds, failed engine pricing, unbracketed
    /// targets and solver exhaustion. The installed swaption engine is unchanged.
    #[allow(clippy::too_many_arguments)]
    pub fn implied_volatility(
        &self,
        mut target_value: Real,
        discount_curve: Handle<dyn YieldTermStructure>,
        guess: Volatility,
        accuracy: Real,
        max_evaluations: Size,
        min_vol: Volatility,
        max_vol: Volatility,
        vol_type: VolatilityType,
        displacement: Real,
        price_type: SwaptionPriceType,
    ) -> QlResult<Volatility> {
        require!(
            target_value.is_finite() && target_value >= 0.0,
            "invalid target value"
        );
        require!(displacement.is_finite(), "invalid displacement");
        require!(
            min_vol.is_finite() && min_vol >= 0.0,
            "invalid minimum volatility"
        );
        require!(
            max_vol.is_finite() && max_vol > min_vol,
            "invalid maximum volatility"
        );
        require!(max_evaluations > 0, "maximum evaluations must be positive");
        require!(!self.is_expired()?, "instrument expired");
        require!(
            self.exercise.exercise_type() == ExerciseType::European,
            "not a European option"
        );

        if price_type == SwaptionPriceType::Forward {
            let exercise_date = self.exercise.dates()[0];
            target_value *= discount_curve
                .current_link()?
                .discount_date(exercise_date, false)?;
        }

        let vol = shared(SimpleQuote::new(-1.0));
        let vol_handle = Handle::new(Shared::clone(&vol) as Shared<dyn Quote>);
        let model = CashAnnuityModel::DiscountCurve;
        let mut engine: Box<dyn PricingEngine> = match vol_type {
            VolatilityType::ShiftedLognormal => Box::new(BlackSwaptionEngine::with_flat_vol(
                discount_curve,
                vol_handle,
                Actual365Fixed::new(),
                displacement,
                model,
                Shared::clone(&self.settings),
            )),
            VolatilityType::Normal => Box::new(BachelierSwaptionEngine::with_flat_vol(
                discount_curve,
                vol_handle,
                Actual365Fixed::new(),
                0.0,
                model,
                Shared::clone(&self.settings),
            )),
        };
        self.setup_arguments(engine.arguments_mut())?;
        engine.arguments_mut().validate()?;

        let failure = RefCell::new(None);
        let helper = ImpliedSwaptionVolHelper {
            engine,
            vol,
            target_value,
            failure: &failure,
        };
        let solver = NewtonSafe::new().with_max_evaluations(max_evaluations);
        let root = solver.solve_bracketed(helper, accuracy, guess, min_vol, max_vol);
        match failure.into_inner() {
            Some(error) => Err(error),
            None => root,
        }
    }
}

/// Newton objective for [`Swaption::implied_volatility`] (`ImpliedSwaptionVolHelper`).
struct ImpliedSwaptionVolHelper<'a> {
    engine: Box<dyn PricingEngine>,
    vol: Shared<SimpleQuote>,
    target_value: Real,
    failure: &'a RefCell<Option<crate::errors::QlError>>,
}

impl ImpliedSwaptionVolHelper<'_> {
    fn ensure_priced(&mut self, x: Volatility) {
        if self.failure.borrow().is_some() {
            return;
        }
        let current = self.vol.value().ok();
        if current != Some(x) {
            self.vol.set_value(x);
            if let Err(error) = self.engine.calculate() {
                self.failure.borrow_mut().get_or_insert(error);
            }
        }
    }

    fn npv(&self) -> Option<Real> {
        self.engine
            .results()
            .as_instrument_results()
            .and_then(|r| r.value)
    }

    fn vega(&self) -> Option<Real> {
        self.engine
            .results()
            .as_instrument_results()
            .and_then(|r| r.additional_results.get("vega"))
            .and_then(|v| v.as_ref().downcast_ref::<Real>().copied())
    }
}

impl Function1D for ImpliedSwaptionVolHelper<'_> {
    fn value(&mut self, x: Real) -> Real {
        self.ensure_priced(x);
        if self.failure.borrow().is_some() {
            return Real::NAN;
        }
        match self.npv() {
            Some(value) => value - self.target_value,
            None => {
                self.failure.borrow_mut().get_or_insert_with(|| {
                    crate::errors::QlError::new(
                        "no results returned from pricing engine",
                        file!(),
                        line!(),
                    )
                });
                Real::NAN
            }
        }
    }

    fn derivative(&mut self, x: Real) -> Real {
        self.ensure_priced(x);
        if self.failure.borrow().is_some() {
            return Real::NAN;
        }
        match self.vega() {
            Some(vega) => vega,
            None => {
                self.failure.borrow_mut().get_or_insert_with(|| {
                    crate::errors::QlError::new("vega not provided", file!(), line!())
                });
                Real::NAN
            }
        }
    }
}

impl Instrument for Swaption {
    fn base(&self) -> &InstrumentBase {
        &self.base
    }

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

    fn is_expired(&self) -> QlResult<bool> {
        event_has_occurred(self.exercise.last_date(), &self.settings, None, None)
    }

    fn setup_arguments(&self, arguments: &mut dyn Arguments) -> QlResult<()> {
        let Some(args) = (arguments as &mut dyn Any).downcast_mut::<SwaptionArguments>() else {
            fail!("wrong argument type");
        };
        self.swap
            .borrow()
            .setup_arguments(&mut args.swap_arguments)?;
        args.swap = Some(SharedMut::clone(&self.swap));
        args.settlement_type = self.settlement_type;
        args.settlement_method = self.settlement_method;
        args.exercise = Some(Shared::clone(&self.exercise));
        Ok(())
    }
}

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

    /// Physical pairs with the two physical methods, cash with the two cash
    /// methods, and every cross pair is rejected (all eight combinations).
    #[test]
    fn consistency_accepts_matching_pairs_and_rejects_the_rest() {
        use SettlementMethod::{
            CollateralizedCashPrice, ParYieldCurve, PhysicalCleared, PhysicalOTC,
        };
        use SettlementType::{Cash, Physical};

        assert!(check_type_and_method_consistency(Physical, PhysicalOTC).is_ok());
        assert!(check_type_and_method_consistency(Physical, PhysicalCleared).is_ok());
        assert!(check_type_and_method_consistency(Cash, CollateralizedCashPrice).is_ok());
        assert!(check_type_and_method_consistency(Cash, ParYieldCurve).is_ok());

        assert_eq!(
            check_type_and_method_consistency(Physical, CollateralizedCashPrice)
                .unwrap_err()
                .message(),
            "invalid settlement method for physical settlement"
        );
        assert!(check_type_and_method_consistency(Physical, ParYieldCurve).is_err());
        assert_eq!(
            check_type_and_method_consistency(Cash, PhysicalOTC)
                .unwrap_err()
                .message(),
            "invalid settlement method for cash settlement"
        );
        assert!(check_type_and_method_consistency(Cash, PhysicalCleared).is_err());
    }

    use crate::cashflow::CashFlow;
    use crate::cashflows::SimpleCashFlow;
    use crate::exercise::EuropeanExercise;
    use crate::handle::Handle;
    use crate::indexes::IborIndex;
    use crate::indexes::ibor::Euribor;
    use crate::instruments::fixedvsfloatingswap::FloatingArgumentsFn;
    use crate::shared::{shared, shared_mut};
    use crate::termstructures::yieldtermstructure::YieldTermStructure;
    use crate::time::businessdayconvention::BusinessDayConvention;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month;
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::frequency::Frequency;
    use crate::time::schedule::MakeSchedule;

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

    /// A two-period annual schedule the fixed leg is built over.
    fn fixed_schedule() -> crate::time::schedule::Schedule {
        MakeSchedule::new()
            .from(Date::new(7, Month::July, 2027))
            .to(Date::new(7, Month::July, 2029))
            .with_frequency(Frequency::Annual)
            .with_calendar(Target::new())
            .with_convention(BusinessDayConvention::Following)
            .build()
    }

    fn euribor(settings: &Shared<Settings<Date>>) -> Shared<IborIndex> {
        shared(Euribor::three_months(
            Handle::<dyn YieldTermStructure>::empty(),
            Shared::clone(settings),
        ))
    }

    /// A one-flow stub standing in for a derived swap's floating leg, enough to
    /// build the base without a full ibor leg.
    fn floating_stub_leg() -> crate::cashflow::Leg {
        vec![
            shared(SimpleCashFlow::new(1.0, Date::new(7, Month::July, 2028)).unwrap())
                as Shared<dyn CashFlow>,
        ]
    }

    /// A payer fixed-vs-floating swap wrapped in [`SharedMut`], the shape a
    /// swaption holds.
    fn shared_swap(settings: &Shared<Settings<Date>>) -> SharedMut<FixedVsFloatingSwap> {
        let noop: FloatingArgumentsFn = Box::new(|_, _| Ok(()));
        shared_mut(
            FixedVsFloatingSwap::new(
                SwapType::Payer,
                vec![100.0],
                fixed_schedule(),
                0.05,
                Some(Actual360::new()),
                vec![100.0],
                fixed_schedule(),
                euribor(settings),
                0.001,
                Actual360::new(),
                None,
                0,
                None,
                floating_stub_leg(),
                noop,
                Shared::clone(settings),
            )
            .unwrap(),
        )
    }

    fn european(date: Date) -> Shared<dyn Exercise> {
        shared(EuropeanExercise::new(date)) as Shared<dyn Exercise>
    }

    /// `validate()` walks the C++ decision tree (`swaption.cpp:175-180`): the
    /// swap half first, then swap present, then exercise present, then the
    /// settlement consistency check.
    #[test]
    fn validate_walks_the_swap_exercise_and_consistency_checks() {
        let settings = settings_on(Date::new(7, Month::July, 2026));

        let mut args = SwaptionArguments::default();
        assert_eq!(args.validate().unwrap_err().message(), "swap not set");

        args.swap = Some(shared_swap(&settings));
        assert_eq!(args.validate().unwrap_err().message(), "exercise not set");

        args.exercise = Some(european(Date::new(7, Month::July, 2028)));
        args.settlement_type = SettlementType::Physical;
        args.settlement_method = SettlementMethod::CollateralizedCashPrice;
        assert_eq!(
            args.validate().unwrap_err().message(),
            "invalid settlement method for physical settlement"
        );

        args.settlement_method = SettlementMethod::PhysicalOTC;
        assert!(args.validate().is_ok(), "a consistent pair validates");
    }

    /// `isExpired` follows the last exercise date against the evaluation date
    /// (`detail::simple_event(exercise_->dates().back()).hasOccurred()`).
    #[test]
    fn is_expired_tracks_the_last_exercise_date() {
        let settings = settings_on(Date::new(7, Month::July, 2026));
        let swaption = Swaption::new(
            shared_swap(&settings),
            european(Date::new(7, Month::July, 2028)),
            SettlementType::Physical,
            SettlementMethod::PhysicalOTC,
            Shared::clone(&settings),
        );

        assert!(!swaption.is_expired().unwrap());
        settings.set_evaluation_date(Date::new(8, Month::July, 2028));
        assert!(swaption.is_expired().unwrap());
    }

    /// `setupArguments` fills the swap half through the swap's own
    /// `setupArguments` and then the swaption fields; the carried swap keeps the
    /// wrapped swap's identity.
    #[test]
    fn setup_arguments_fills_the_swap_half_and_the_swaption_fields() {
        let settings = settings_on(Date::new(7, Month::July, 2026));
        let swap = shared_swap(&settings);
        let swaption = Swaption::new(
            SharedMut::clone(&swap),
            european(Date::new(7, Month::July, 2028)),
            SettlementType::Cash,
            SettlementMethod::ParYieldCurve,
            Shared::clone(&settings),
        );

        let mut args = SwaptionArguments::default();
        swaption.setup_arguments(&mut args).unwrap();

        assert_eq!(
            args.swap_arguments.swap_type,
            Some(SwapType::Payer),
            "the swap's own setupArguments ran"
        );
        assert_eq!(
            args.swap_arguments.fixed_pay_dates.len(),
            2,
            "two annual fixed coupons filled by the swap half"
        );
        assert_eq!(args.settlement_type, SettlementType::Cash);
        assert_eq!(args.settlement_method, SettlementMethod::ParYieldCurve);
        assert_eq!(
            args.exercise.as_ref().unwrap().last_date(),
            Date::new(7, Month::July, 2028)
        );
        assert!(
            SharedMut::ptr_eq(args.swap.as_ref().unwrap(), &swap),
            "the carried swap is the wrapped swap, not a copy"
        );
    }

    /// `underlying()` and the forwarded `type()` reach the wrapped swap; the
    /// pointer identity is shared (one `Rc`, C++'s `shared_ptr`).
    #[test]
    fn underlying_shares_identity_and_forwards_type() {
        let settings = settings_on(Date::new(7, Month::July, 2026));
        let swap = shared_swap(&settings);
        let swaption = Swaption::new(
            SharedMut::clone(&swap),
            european(Date::new(7, Month::July, 2028)),
            SettlementType::Physical,
            SettlementMethod::PhysicalOTC,
            Shared::clone(&settings),
        );

        assert!(SharedMut::ptr_eq(swaption.underlying(), &swap));
        assert_eq!(swaption.swap_type(), SwapType::Payer);
        assert_eq!(swaption.settlement_type(), SettlementType::Physical);
        assert_eq!(swaption.settlement_method(), SettlementMethod::PhysicalOTC);
    }

    /// A bundle of the wrong type is rejected by `setupArguments`.
    #[test]
    fn setup_arguments_rejects_a_foreign_bundle() {
        let settings = settings_on(Date::new(7, Month::July, 2026));
        let swaption = Swaption::new(
            shared_swap(&settings),
            european(Date::new(7, Month::July, 2028)),
            SettlementType::Physical,
            SettlementMethod::PhysicalOTC,
            settings,
        );

        let mut foreign = FixedVsFloatingSwapArguments::default();
        assert_eq!(
            swaption
                .setup_arguments(&mut foreign)
                .unwrap_err()
                .message(),
            "wrong argument type"
        );
    }
    fn oracle_swaption(cash: bool) -> (Swaption, Handle<dyn YieldTermStructure>) {
        use crate::instruments::MakeVanillaSwap;
        use crate::interestrate::Compounding;
        use crate::termstructures::yields::FlatForward;
        use crate::time::period::Period;
        use crate::time::timeunit::TimeUnit;
        let today = Date::new(7, Month::July, 2026);
        let settings = settings_on(today);
        let curve = Handle::new(shared(FlatForward::with_rate(
            today,
            0.02,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>);
        let index = shared(Euribor::six_months(curve.clone(), Shared::clone(&settings)));
        let swap = MakeVanillaSwap::new(
            Period::new(5, TimeUnit::Years),
            index,
            Some(0.03),
            Period::new(0, TimeUnit::Days),
            Shared::clone(&settings),
        )
        .with_effective_date(Date::new(9, Month::July, 2027))
        .build()
        .unwrap();
        (
            Swaption::new(
                shared_mut(swap.into_fixed_vs_floating()),
                european(Date::new(7, Month::July, 2027)),
                if cash {
                    SettlementType::Cash
                } else {
                    SettlementType::Physical
                },
                if cash {
                    SettlementMethod::ParYieldCurve
                } else {
                    SettlementMethod::PhysicalOTC
                },
                settings,
            ),
            curve,
        )
    }

    /// QuantLib 1.43 Black/Bachelier engines, with their DiscountCurve annuity default.
    #[test]
    fn implied_volatility_matches_independent_quantlib_prices() {
        let cases = [
            (
                false,
                false,
                0.2,
                0.0,
                0.00025057295935918054,
                0.0002557058884618845,
            ),
            (
                false,
                true,
                0.2,
                0.0,
                0.0002505730263925663,
                0.00025570595686843367,
            ),
            (
                false,
                false,
                0.3,
                0.01,
                0.004793571124123376,
                0.004891766319613821,
            ),
            (
                false,
                true,
                0.3,
                0.01,
                0.004793572406501582,
                0.004891767628261249,
            ),
            (
                true,
                false,
                0.01,
                0.0,
                0.004228008592218679,
                0.0043146183700853045,
            ),
            (
                true,
                true,
                0.01,
                0.0,
                0.004228009723297353,
                0.004314619524333864,
            ),
        ];
        for (normal, cash, expected, shift, spot, forward) in cases {
            let (swaption, curve) = oracle_swaption(cash);
            let vol_type = if normal {
                VolatilityType::Normal
            } else {
                VolatilityType::ShiftedLognormal
            };
            for (target, price_type) in [
                (spot, SwaptionPriceType::Spot),
                (forward, SwaptionPriceType::Forward),
            ] {
                let recovered = swaption
                    .implied_volatility(
                        target,
                        curve.clone(),
                        if normal { 0.02 } else { 0.1 },
                        1e-10,
                        100,
                        1e-7,
                        4.0,
                        vol_type,
                        shift,
                        price_type,
                    )
                    .unwrap();
                assert!(
                    (recovered - expected).abs() < 1e-9,
                    "normal={normal} cash={cash} recovered={recovered}"
                );
            }
        }
    }

    #[test]
    fn implied_volatility_rejects_invalid_targets_bounds_and_preserves_engine_errors() {
        let (swaption, curve) = oracle_swaption(false);
        let solve = |target, curve, min, max, evaluations| {
            swaption.implied_volatility(
                target,
                curve,
                0.1,
                1e-10,
                evaluations,
                min,
                max,
                VolatilityType::ShiftedLognormal,
                0.0,
                SwaptionPriceType::Spot,
            )
        };
        for target in [-1.0, Real::NAN, Real::INFINITY, 100.0] {
            assert!(solve(target, curve.clone(), 1e-7, 4.0, 100).is_err());
        }
        assert!(solve(0.001, curve.clone(), -1.0, 4.0, 100).is_err());
        assert!(solve(0.001, curve.clone(), 1.0, 0.5, 100).is_err());
        assert!(solve(0.001, curve.clone(), 1e-7, 4.0, 1).is_err());
        let error = solve(0.001, Handle::empty(), 1e-7, 4.0, 100).unwrap_err();
        assert!(
            !error.message().contains("non-finite"),
            "engine error must propagate: {error}"
        );
    }
    #[test]
    fn implied_volatility_rejects_expired_and_non_european_exercise() {
        use crate::exercise::AmericanExercise;
        let (mut swaption, curve) = oracle_swaption(false);
        let solve = |s: &Swaption| {
            s.implied_volatility(
                0.001,
                curve.clone(),
                0.1,
                1e-8,
                100,
                1e-7,
                4.0,
                VolatilityType::ShiftedLognormal,
                0.0,
                SwaptionPriceType::Spot,
            )
        };
        swaption.exercise = shared(
            AmericanExercise::new(
                Date::new(7, Month::July, 2026),
                Date::new(7, Month::July, 2027),
                false,
            )
            .unwrap(),
        );
        assert_eq!(
            solve(&swaption).unwrap_err().message(),
            "not a European option"
        );
        swaption.exercise = european(Date::new(6, Month::July, 2026));
        assert_eq!(
            solve(&swaption).unwrap_err().message(),
            "instrument expired"
        );
    }

    #[test]
    fn implied_volatility_preserves_installed_swaption_engine() {
        let (mut swaption, curve) = oracle_swaption(false);
        let engine: SharedMut<dyn PricingEngine> = shared_mut(BlackSwaptionEngine::with_flat_vol(
            curve.clone(),
            Handle::new(shared(SimpleQuote::new(0.2)) as Shared<dyn Quote>),
            Actual365Fixed::new(),
            0.0,
            CashAnnuityModel::DiscountCurve,
            Shared::clone(&swaption.settings),
        ));
        swaption
            .base_mut()
            .set_pricing_engine(SharedMut::clone(&engine));
        let before = swaption.npv().unwrap();
        let vol = swaption
            .implied_volatility(
                0.004793571124123376,
                curve,
                0.1,
                1e-10,
                100,
                1e-7,
                4.0,
                VolatilityType::ShiftedLognormal,
                0.01,
                SwaptionPriceType::Spot,
            )
            .unwrap();
        assert!((vol - 0.3).abs() < 1e-9);
        assert!(SharedMut::ptr_eq(
            swaption.base().pricing_engine().unwrap(),
            &engine
        ));
        assert!((swaption.npv().unwrap() - before).abs() < 1e-14);
    }
}