libitofin 0.18.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
//! Piecewise-bootstrapped year-on-year optionlet volatility curve.
//!
//! Port of `ql/experimental/inflation/piecewiseyoyoptionletvolatility.hpp`:
//! [`YoYInflationVolatilityTraits`] (`hpp:36-96`) drives the bootstrap's seed,
//! guesses and brackets, and [`PiecewiseYoYOptionletVolatilityCurve`]
//! (`hpp:105-175`) is the curve, one per strike of the stripper, fitted to
//! [`YoYOptionletVolatilityHelper`]s by the same [`IterativeBootstrap`] every
//! other piecewise curve runs. "We use a flat smile for bootstrapping at
//! constant K" (`hpp:100-103`): the smile is flat, the strike bounds a thin
//! band around the quoted K.
//!
//! It mirrors [`PiecewiseYoYInflationCurve`] field for field; C++ derives from
//! `InterpolatedYoYOptionletVolatilityCurve<Interpolator>` *and* `LazyObject`
//! (`hpp:108-110`), and Rust has no inheritance, so the node storage lives
//! here and the volatility lookup reads it directly.
//!
//! ## Node zero carries the base level
//!
//! `YoYInflationVolatilityTraits::initialDate` is the curve's own base date
//! and `initialValue` its own base level (`hpp:41-51` - "REALLLYYYY important
//! because generally don't have a clue what this should be"), both read off
//! the curve being bootstrapped. They land here as the
//! [`PiecewiseCurve::initial_date`]/[`PiecewiseCurve::initial_value`] hook
//! overrides, the same seam [`PiecewiseYoYInflationCurve`] uses for its base
//! rate; `updateGuess` writes only node `i` (`hpp:89-93`), so the seeded level
//! survives the whole solve.
//!
//! ## Divergences from QuantLib
//!
//! - The moving reference date takes the shared [`Settings`] handle (D5).
//! - The `accuracy` constructor argument (`hpp:133`) is not exposed, matching
//!   the sibling curves; the field carries the C++ default `1.0e-12`.
//! - Only [`Linear`] is constructible, the impls staying generic, exactly as
//!   on [`PiecewiseYoYInflationCurve`].
//!
//! [`PiecewiseYoYInflationCurve`]: crate::termstructures::inflation::piecewiseyoyinflationcurve::PiecewiseYoYInflationCurve
//! [`IterativeBootstrap`]: crate::termstructures::iterativebootstrap::IterativeBootstrap
//! [`PiecewiseCurve::initial_date`]: crate::termstructures::iterativebootstrap::PiecewiseCurve::initial_date
//! [`PiecewiseCurve::initial_value`]: crate::termstructures::iterativebootstrap::PiecewiseCurve::initial_value

use std::cell::RefCell;
use std::rc::Weak;

use crate::errors::QlResult;
use crate::math::interpolations::linear::Linear;
use crate::math::interpolations::{Interpolation, Interpolator};
use crate::patterns::lazyobject::LazyObject;
use crate::patterns::observable::{AsObservable, Observable, Observer};
use crate::require;
use crate::settings::Settings;
use crate::shared::{Shared, SharedMut, shared_mut};
use crate::termstructures::bootstraptraits::{BootstrapTraits, CurveData};
use crate::termstructures::iterativebootstrap::{IterativeBootstrap, PiecewiseCurve};
use crate::termstructures::volatility::VolatilityTermStructure;
use crate::termstructures::{TermStructure, TermStructureBase};
use crate::time::businessdayconvention::BusinessDayConvention;
use crate::time::calendar::Calendar;
use crate::time::date::Date;
use crate::time::daycounter::DayCounter;
use crate::time::frequency::Frequency;
use crate::time::period::Period;
use crate::time::timeunit::TimeUnit;
use crate::types::{Natural, Rate, Real, Size, Time, Volatility};

use super::yoyoptionlethelpers::YoYOptionletVolatilityHelper;
use super::{YoYOptionletVolatilitySurface, YoYOptionletVolatilitySurfaceBase};

/// Traits for the inflation-volatility bootstrap
/// (`YoYInflationVolatilityTraits`, `hpp:36-96`).
pub struct YoYInflationVolatilityTraits;

impl BootstrapTraits for YoYInflationVolatilityTraits {
    /// C++ has no constant here: `initialValue` reads the bootstrapped curve's
    /// own `baseLevel()` (`hpp:45-51`), which lands as
    /// [`PiecewiseYoYOptionletVolatilityCurve`]'s `initial_value` hook
    /// override, so this static is never the seeding path. A zero volatility
    /// stands in for the total function the trait requires.
    fn initial_value() -> Real {
        0.0
    }

    /// The per-node guess (`hpp:54-68`): the stored node on a seeded pass,
    /// `0.005` at the first pillar, `0.002` after it.
    fn guess(i: Size, _times: &[Time], data: &[Real], valid_data: bool) -> Real {
        if valid_data {
            return data[i];
        }
        if i == 1 {
            return 0.005;
        }
        0.002
    }

    /// The lower bracket (`hpp:71-78`): two vol points under the previous
    /// node, floored at zero - "vol cannot be negative".
    fn min_value_after(i: Size, _times: &[Time], data: &[Real], _valid_data: bool) -> Real {
        (data[i - 1] - 0.02).max(0.0)
    }

    /// The upper bracket (`hpp:79-86`): two vol points over the previous node.
    fn max_value_after(i: Size, _times: &[Time], data: &[Real], _valid_data: bool) -> Real {
        data[i - 1] + 0.02
    }

    /// Writes a solved level back (`hpp:89-93`): node `i` takes it and nothing
    /// else moves, so the seeded base level is never overwritten.
    fn update_guess(data: &mut [Real], value: Real, i: Size) {
        data[i] = value;
    }

    /// The convergence-loop cap (`hpp:95`).
    fn max_iterations() -> Size {
        25
    }
}

/// Feeds a helper-quote or evaluation-date notification into the curve's lazy
/// core: it invalidates the bootstrap cache and re-broadcasts to the curve's
/// own observers (the port of `update()`, `hpp:226-230`).
struct CurveUpdater {
    lazy: SharedMut<LazyObject>,
}

impl Observer for CurveUpdater {
    fn update(&mut self) {
        if let Some(update) = LazyObject::deferred_update(&self.lazy) {
            update.notify_observers();
        }
    }
}

/// Piecewise year-on-year optionlet volatility curve
/// (`PiecewiseYoYOptionletVolatilityCurve`, `hpp:105-175`).
///
/// `I` is the interpolation factory ([`Linear`]); the shape traits are always
/// [`YoYInflationVolatilityTraits`], the nodes being the optionlet
/// volatilities themselves.
pub struct PiecewiseYoYOptionletVolatilityCurve<I: Interpolator> {
    vol_base: YoYOptionletVolatilitySurfaceBase,
    min_strike: Rate,
    max_strike: Rate,
    instruments: Vec<Shared<dyn YoYOptionletVolatilityHelper>>,
    interpolator: I,
    data: RefCell<CurveData<I>>,
    lazy: SharedMut<LazyObject>,
    observable: Shared<Observable>,
    updater: SharedMut<CurveUpdater>,
    bootstrap: IterativeBootstrap,
    accuracy: Real,
    self_weak: Weak<dyn YoYOptionletVolatilitySurface>,
}

impl PiecewiseYoYOptionletVolatilityCurve<Linear> {
    /// Builds a linearly interpolated curve over `instruments`
    /// (`hpp:121-148`). Construction is cheap; the bootstrap runs on first
    /// use. `base_yoy_volatility` is the artificial volatility at the base
    /// date - the C++ constructor forwards it into the protected
    /// interpolated-curve constructor, whose whole job is `setBaseLevel`
    /// (`yoyinflationoptionletvolatilitystructure2.hpp:156-176`) - and it is
    /// what node zero is seeded with and keeps.
    ///
    /// # Errors
    ///
    /// Rejects an empty helper set.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        settlement_days: Natural,
        calendar: Calendar,
        business_day_convention: BusinessDayConvention,
        day_counter: DayCounter,
        observation_lag: Period,
        frequency: Frequency,
        index_is_interpolated: bool,
        min_strike: Rate,
        max_strike: Rate,
        base_yoy_volatility: Volatility,
        instruments: Vec<Shared<dyn YoYOptionletVolatilityHelper>>,
        settings: Shared<Settings<Date>>,
    ) -> QlResult<Shared<PiecewiseYoYOptionletVolatilityCurve<Linear>>> {
        require!(!instruments.is_empty(), "no bootstrap helpers given");

        let curve = Shared::new_cyclic(
            |weak: &Weak<PiecewiseYoYOptionletVolatilityCurve<Linear>>| {
                let self_weak: Weak<dyn YoYOptionletVolatilitySurface> = weak.clone();
                let lazy = shared_mut(LazyObject::new(true));
                let observable = lazy.borrow().observable_handle();
                let updater = shared_mut(CurveUpdater {
                    lazy: SharedMut::clone(&lazy),
                });
                let vol_base = YoYOptionletVolatilitySurfaceBase::new(
                    settlement_days,
                    calendar,
                    business_day_convention,
                    day_counter,
                    observation_lag,
                    frequency,
                    index_is_interpolated,
                    settings,
                );
                vol_base.set_base_level(base_yoy_volatility);
                PiecewiseYoYOptionletVolatilityCurve {
                    vol_base,
                    min_strike,
                    max_strike,
                    instruments,
                    interpolator: Linear,
                    data: RefCell::new(CurveData::new()),
                    lazy,
                    observable,
                    updater,
                    bootstrap: IterativeBootstrap::new(),
                    accuracy: 1.0e-12,
                    self_weak,
                }
            },
        );

        let observer = SharedMut::clone(&curve.updater) as SharedMut<dyn Observer>;
        for helper in &curve.instruments {
            helper.observable().register_observer(&observer);
        }
        // The reference date moves with the evaluation date, whose change must
        // invalidate the bootstrap; the term base broadcasts it and the lazy
        // core turns it into a re-solve on the next read.
        curve
            .vol_base
            .term_structure_base()
            .observable()
            .register_observer(&observer);
        Ok(curve)
    }
}

impl<I: Interpolator + 'static> PiecewiseYoYOptionletVolatilityCurve<I> {
    /// Runs the bootstrap if the cache is stale, caching the result
    /// (`performCalculations`, `hpp:220-224`; the stripper calls C++'s
    /// `recalculate()` on a fresh curve, which this equals). Re-entrant: a
    /// helper repricing mid-bootstrap - every one does, through the engine
    /// reading this same surface - returns on the pre-set flag and answers off
    /// the solved prefix.
    pub fn calculate(&self) -> QlResult<()> {
        if self.lazy.borrow().is_calculated() {
            return Ok(());
        }
        if !self.lazy.borrow_mut().start_calculation() {
            return Ok(());
        }
        let result = self.bootstrap.calculate(self);
        self.lazy.borrow_mut().finish_calculation(&result);
        result
    }

    /// The node times, after bootstrapping (`hpp:192-197`). The first is
    /// negative, the base date preceding the reference date.
    pub fn times(&self) -> QlResult<Vec<Time>> {
        self.calculate()?;
        Ok(self.data.borrow().times().to_vec())
    }

    /// The node dates, after bootstrapping (`hpp:199-204`). The first is the
    /// base date.
    pub fn dates(&self) -> QlResult<Vec<Date>> {
        self.calculate()?;
        Ok(self.data.borrow().dates().to_vec())
    }

    /// The node volatilities, after bootstrapping (`hpp:206-211`). The first
    /// is the base level the curve was built with.
    pub fn data(&self) -> QlResult<Vec<Real>> {
        self.calculate()?;
        Ok(self.data.borrow().data().to_vec())
    }

    /// The (date, volatility) nodes, after bootstrapping (`hpp:213-218`).
    pub fn nodes(&self) -> QlResult<Vec<(Date, Real)>> {
        self.calculate()?;
        Ok(self.data.borrow().nodes())
    }

    /// Registers a downstream observer of the curve's notifications.
    pub fn register_observer(&self, observer: &SharedMut<dyn Observer>) -> bool {
        self.observable.register_observer(observer)
    }

    /// For the curve the strike is ignored, the smile being flat; C++
    /// evaluates without extrapolation
    /// (`yoyinflationoptionletvolatilitystructure2.hpp:180-186`), and every
    /// read of the bootstrap - the last coupon of pillar `i`'s helper fixes
    /// *on* node `i` - lands inside the solved prefix.
    fn volatility_impl(&self, t: Time) -> QlResult<Volatility> {
        self.calculate()?;
        let data = self.data.borrow();
        data.interpolation()?.value(t)
    }
}

impl<I: Interpolator> AsObservable for PiecewiseYoYOptionletVolatilityCurve<I> {
    fn observable(&self) -> &Observable {
        &self.observable
    }
}

impl<I: Interpolator + 'static> TermStructure for PiecewiseYoYOptionletVolatilityCurve<I> {
    fn base(&self) -> &TermStructureBase {
        self.vol_base.term_structure_base()
    }

    /// `maxDate` triggers the bootstrap (`hpp:186-190`) and then runs the base
    /// curve's approximation: the reference date advanced by the last node
    /// time rounded up to whole years
    /// (`yoyinflationoptionletvolatilitystructure2.hpp:73-76`). Fallbacks
    /// follow the sibling piecewise curves: the reference date, then the null
    /// date.
    fn max_date(&self) -> Date {
        let _ = self.calculate();
        let t_max = self.data.borrow().times().last().copied();
        match t_max {
            Some(t_max) => self
                .option_date_from_tenor(Period::new(t_max.ceil() as i32, TimeUnit::Years))
                .unwrap_or_else(|_| Date::null()),
            None => self
                .vol_base
                .term_structure_base()
                .reference_date()
                .unwrap_or_else(|_| Date::null()),
        }
    }
}

impl<I: Interpolator + 'static> VolatilityTermStructure
    for PiecewiseYoYOptionletVolatilityCurve<I>
{
    fn business_day_convention(&self) -> BusinessDayConvention {
        self.vol_base.business_day_convention()
    }

    fn min_strike(&self) -> Rate {
        self.min_strike
    }

    fn max_strike(&self) -> Rate {
        self.max_strike
    }
}

impl<I: Interpolator + 'static> YoYOptionletVolatilitySurface
    for PiecewiseYoYOptionletVolatilityCurve<I>
{
    /// `baseDate` triggers the bootstrap first (`hpp:180-184`), then runs the
    /// shared date arithmetic.
    fn base_date(&self) -> QlResult<Date> {
        self.calculate()?;
        self.vol_base.base_date()
    }

    fn volatility(&self, date: Date, strike: Rate, obs_lag: Period) -> QlResult<Volatility> {
        let observed = self.vol_base.observed(date - obs_lag)?;
        self.vol_base.check_range(
            observed,
            strike,
            self.min_strike,
            self.max_strike,
            TermStructure::max_date(self),
        )?;
        self.volatility_impl(TermStructure::time_from_reference(self, observed)?)
    }

    fn total_variance(&self, date: Date, strike: Rate, obs_lag: Period) -> QlResult<Real> {
        let volatility = self.volatility(date, strike, obs_lag)?;
        Ok(volatility * volatility * self.vol_base.time_from_base(date, obs_lag)?)
    }

    fn base_level(&self) -> QlResult<Volatility> {
        self.vol_base.base_level()
    }
}

impl<I: Interpolator + 'static> PiecewiseCurve for PiecewiseYoYOptionletVolatilityCurve<I> {
    type Traits = YoYInflationVolatilityTraits;
    type Interp = I;
    type TS = dyn YoYOptionletVolatilitySurface;
    type Helper = dyn YoYOptionletVolatilityHelper;

    fn instruments(&self) -> &[Shared<dyn YoYOptionletVolatilityHelper>] {
        &self.instruments
    }

    fn interpolator(&self) -> &I {
        &self.interpolator
    }

    fn curve_data(&self) -> &RefCell<CurveData<I>> {
        &self.data
    }

    fn accuracy(&self) -> Real {
        self.accuracy
    }

    fn reference_date(&self) -> QlResult<Date> {
        self.vol_base.term_structure_base().reference_date()
    }

    /// The curve's own base date (`Traits::initialDate`, `hpp:41-43`), which
    /// precedes the reference date, so node zero sits at a negative time.
    fn initial_date(&self) -> QlResult<Date> {
        self.vol_base.base_date()
    }

    /// The curve's own base level (`Traits::initialValue`, `hpp:45-51`),
    /// where the yield conventions take a traits constant; an `Err` if it was
    /// never set, though the public constructor always sets it.
    fn initial_value(&self) -> QlResult<Real> {
        self.vol_base.base_level()
    }

    fn time_from_reference(&self, date: Date) -> QlResult<Time> {
        TermStructure::time_from_reference(self, date)
    }

    fn term_structure_shared(&self) -> QlResult<Shared<dyn YoYOptionletVolatilitySurface>> {
        match self.self_weak.upgrade() {
            Some(curve) => Ok(curve),
            None => crate::fail!("curve dropped before bootstrap"),
        }
    }
}

#[cfg(test)]
mod tests {
    //! The C++ suite reaches this curve only through the stripper, whose
    //! numeric oracle closes with the K-interpolated surface; what is checked
    //! here is what the curve decides on its own, against a helper written to
    //! make those decisions visible. The mock reprices off *two* points of the
    //! surface, its pillar and the base date, so its solved node is
    //! `2 * quote - base_level`: a curve seeded from anything but its own base
    //! level lands every node somewhere else while still repricing perfectly.

    use super::super::yoyoptionlethelpers::YoYOptionletVolHelperBase;
    use super::*;
    use crate::handle::Handle;
    use crate::quotes::{Quote, SimpleQuote};
    use crate::shared::shared;
    use crate::time::calendars::target::Target;
    use crate::time::date::Month::{April, June};
    use crate::time::daycounters::actual365fixed::Actual365Fixed;

    /// Distinct from every solved pillar and from the traits' guesses.
    const BASE_LEVEL: Volatility = 0.01;
    const QUOTES: [Real; 3] = [0.012, 0.013, 0.011];
    const MATURITY_YEARS: [i32; 3] = [1, 2, 3];

    fn zero_lag() -> Period {
        Period::new(0, TimeUnit::Days)
    }

    /// A helper whose implied quote is the mean of the surface's volatility at
    /// its pillar and at the base date, both read at the quoted strike with no
    /// further lag; the fixture's index interpolates, so the observed date is
    /// the query date itself and the reads land on nodes.
    struct MeanVolHelper {
        base: YoYOptionletVolHelperBase,
    }

    impl MeanVolHelper {
        fn new(quote: &Shared<SimpleQuote>, pillar: Date) -> Shared<MeanVolHelper> {
            let base = YoYOptionletVolHelperBase::new(Handle::new(
                Shared::clone(quote) as Shared<dyn Quote>
            ));
            base.set_pillar_date(pillar);
            base.set_latest_relevant_date(pillar);
            base.set_maturity_date(pillar);
            shared(MeanVolHelper { base })
        }
    }

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

    impl YoYOptionletVolatilityHelper for MeanVolHelper {
        fn base(&self) -> &YoYOptionletVolHelperBase {
            &self.base
        }

        fn implied_quote(&self) -> QlResult<Real> {
            let surface = self.base.term_structure()?;
            let at_pillar = surface.volatility(self.base.pillar_date(), 0.02, zero_lag())?;
            let at_base = surface.volatility(surface.base_date()?, 0.02, zero_lag())?;
            Ok(0.5 * (at_pillar + at_base))
        }
    }

    struct Fixture {
        helpers: Vec<Shared<dyn YoYOptionletVolatilityHelper>>,
        curve: Shared<PiecewiseYoYOptionletVolatilityCurve<Linear>>,
        quotes: Vec<Shared<SimpleQuote>>,
    }

    /// Settlement days 0 and a 2-month lag on an interpolated monthly index:
    /// the base date is 15 April 2026, two months before the reference, at a
    /// negative time.
    fn a_curve() -> Fixture {
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(Date::new(15, June, 2026));
        let quotes: Vec<Shared<SimpleQuote>> = QUOTES
            .iter()
            .map(|quote| shared(SimpleQuote::new(Some(*quote))))
            .collect();
        let helpers: Vec<Shared<dyn YoYOptionletVolatilityHelper>> = quotes
            .iter()
            .zip(MATURITY_YEARS)
            .map(|(quote, years)| {
                MeanVolHelper::new(
                    quote,
                    Date::new(15, June, 2026) + Period::new(years, TimeUnit::Years),
                ) as Shared<dyn YoYOptionletVolatilityHelper>
            })
            .collect();
        let curve = PiecewiseYoYOptionletVolatilityCurve::new(
            0,
            Target::new(),
            BusinessDayConvention::ModifiedFollowing,
            Actual365Fixed::new(),
            Period::new(2, TimeUnit::Months),
            Frequency::Monthly,
            true,
            0.018,
            0.022,
            BASE_LEVEL,
            helpers.clone(),
            settings,
        )
        .unwrap();
        Fixture {
            helpers,
            curve,
            quotes,
        }
    }

    /// Every helper reprices its quote off the bootstrapped curve, the pillars
    /// land where the helpers put them, and node zero sits at the base date's
    /// negative time.
    #[test]
    fn the_bootstrapped_curve_reproduces_every_helpers_quote() {
        let fixture = a_curve();
        fixture.curve.calculate().unwrap();

        for (helper, quote) in fixture.helpers.iter().zip(QUOTES) {
            let error = helper.quote_error().unwrap();
            assert!(
                error.abs() < 1.0e-10,
                "quote error {error} on the {quote} helper"
            );
        }

        let dates = fixture.curve.dates().unwrap();
        assert_eq!(dates.len(), 4);
        assert_eq!(dates[0], Date::new(15, April, 2026));
        for (i, helper) in fixture.helpers.iter().enumerate() {
            assert_eq!(dates[i + 1], helper.pillar_date());
        }
        assert!(fixture.curve.times().unwrap()[0] < 0.0);
    }

    /// The two halves of the traits transcription: node zero is seeded from
    /// the curve's own base level through the `initial_value` hook, and
    /// `update_guess` never writes to it, so it holds that level bit for bit
    /// once every pillar is solved to `2 * quote - base_level`.
    #[test]
    fn the_base_node_keeps_the_curves_own_base_level_through_the_bootstrap() {
        let fixture = a_curve();
        let data = fixture.curve.data().unwrap();

        assert_eq!(data[0], BASE_LEVEL);
        for (i, quote) in QUOTES.iter().enumerate() {
            let expected = 2.0 * quote - BASE_LEVEL;
            assert!(
                (data[i + 1] - expected).abs() < 1.0e-10,
                "node {} solved to {} against {expected}",
                i + 1,
                data[i + 1]
            );
        }
        assert_eq!(
            fixture.curve.base_level().unwrap(),
            BASE_LEVEL,
            "the surface reports the level it was seeded with"
        );
    }

    /// The traits' statics against `hpp:54-95`: the two fresh-pass guesses,
    /// the vol-cannot-be-negative floor on the lower bracket, and the
    /// one-node-only write.
    #[test]
    fn the_traits_statics_match_the_cpp_header() {
        let times = [0.0, 1.0, 2.0];
        let data = [0.01, 0.005, 0.0];
        assert_eq!(
            YoYInflationVolatilityTraits::guess(1, &times, &data, false),
            0.005
        );
        assert_eq!(
            YoYInflationVolatilityTraits::guess(2, &times, &data, false),
            0.002
        );
        assert_eq!(
            YoYInflationVolatilityTraits::guess(2, &times, &data, true),
            0.0
        );
        assert_eq!(
            YoYInflationVolatilityTraits::min_value_after(1, &times, &data, false),
            0.0,
            "0.01 - 0.02 floors at zero"
        );
        assert_eq!(
            YoYInflationVolatilityTraits::max_value_after(1, &times, &data, false),
            0.03
        );
        let mut nodes = [0.01, 0.0, 0.0];
        YoYInflationVolatilityTraits::update_guess(&mut nodes, 0.007, 1);
        assert_eq!(nodes, [0.01, 0.007, 0.0]);
        assert_eq!(YoYInflationVolatilityTraits::max_iterations(), 25);
    }

    /// Construction lays down no nodes; the first read bootstraps; a quote
    /// move invalidates the cache and the next read re-solves.
    #[test]
    fn the_bootstrap_is_lazy_and_reruns_on_a_quote_change() {
        let fixture = a_curve();
        assert!(!fixture.curve.lazy.borrow().is_calculated());

        let first = fixture.curve.data().unwrap()[1];
        assert!(fixture.curve.lazy.borrow().is_calculated());

        fixture.quotes[0].set_value(Some(0.015));
        assert!(!fixture.curve.lazy.borrow().is_calculated());
        assert!(
            fixture.curve.data().unwrap()[1] > first,
            "a higher quoted price must lift the curve"
        );
    }

    #[test]
    fn an_empty_helper_set_is_rejected() {
        let settings = shared(Settings::<Date>::new());
        settings.set_evaluation_date(Date::new(15, June, 2026));
        let built = PiecewiseYoYOptionletVolatilityCurve::new(
            0,
            Target::new(),
            BusinessDayConvention::ModifiedFollowing,
            Actual365Fixed::new(),
            Period::new(2, TimeUnit::Months),
            Frequency::Monthly,
            true,
            0.018,
            0.022,
            BASE_LEVEL,
            Vec::new(),
            settings,
        );
        let err = match built {
            Ok(_) => panic!("expected a construction error"),
            Err(err) => err,
        };
        assert!(err.message().contains("no bootstrap helpers"));
    }
}