quantsupport 0.1.5

Rust library for derivative pricing and risk analytics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
use std::{cell::RefCell, collections::HashMap, rc::Rc};

use nalgebra::{DMatrix, DVector};

use crate::{
    ad::{dual::DualFwd, scalar::Scalar},
    calibration::{
        calibrationpricer::CalibrationInstrumentPricer, calibrationprocess::CalibrationProcess,
    },
    core::{
        elements::curveelement::{ADCurveElement, DiscountCurveElement},
        marketdatahandling::constructedelementstore::SharedElement,
    },
    indices::marketindex::MarketIndex,
    math::{
        interpolation::interpolator::Interpolator,
        solvers::{
            solvertraits::{ContFunc, JacobianFunc, VectorFunc},
            vectornewton::VectorNewton,
        },
    },
    quotes::{
        calibrationinstrument::CalibrationInstrument, fxstore::FxStore, quote::Level,
        quoteselector::QuoteSelector,
    },
    rates::{
        bootstrapping::{
            bootstrapcalibrationinstrument::BootstrapStepEvaluation,
            bootstrapdiscountpolicy::BootstrapDiscountPolicy,
            bootstrappedcurve::BootstrappedCurve,
            bootstrapstep::BootstrapStep,
            bootstraputils::{dependency_order, CrossCurveDep},
            curveconfiguration::CurveConfiguration,
        },
        yieldtermstructure::discounttermstructure::DiscountTermStructure,
    },
    time::{date::Date, daycounter::DayCounter},
    utils::errors::{QSError, Result},
};

/// Multi-curve bootstrapping engine.
///
/// Accepts a set of [`CurveConfiguration`]s and a [`BootstrapDiscountPolicy`] that
/// will determine how to bootstrap each curve. It resolves dependencies between [`CurveConfiguration`].
///
/// ## Parameters
/// * `curve_specs`: the list of curve specifications to bootstrap. Each spec includes the market index, currency, day count convention, interpolation method, and the list of pillar instruments (identified by their quote IDs).
/// * `discount_policy`: the discount policy defines how to determine the discount curve for each instrument during bootstrapping, including handling of cross-currency instruments and collateralization. See [`BootstrapDiscountPolicy`] for details.
///
/// ## Example
/// ```ignore
/// use quantsupport::prelude::*;
/// use std::collections::HashMap;
///
/// // We create a simple QuoteSelector that holds the market quotes in a HashMap.
/// struct MapSelector {
///     reference_date: Date,
///     quotes: HashMap<String, f64>,
/// }
///
/// impl MapSelector {
///     fn new(reference_date: Date) -> Self {
///         Self {
///             reference_date,
///             quotes: HashMap::new(),
///         }
///     }
///
///     fn add(&mut self, id: &str, rate: f64) {
///         self.quotes.insert(id.to_string(), rate);
///     }
/// }
///
/// impl QuoteSelector for MapSelector {
///         fn select(&self, identifier: &str) -> Option<Quote> {
///             let rate = self.quotes.get(identifier)?;
///             let det: QuoteDetails = identifier.parse().ok()?;
///             let q = Quote::new(det, QuoteLevels::with_mid(*rate));
///             if q.build_instrument(self.reference_date, Level::Mid, None).is_ok() {
///                 Some(q)
///             } else {
///                 None
///             }
///         }
///         fn reference_date(&self) -> Date {
///             self.reference_date
///         }
///     }
///
/// // We pass the market data to the selector
/// let rd = Date::new(2024, 6, 1);
/// let mut selector = MapSelector::new(rd);
/// selector.add("FixedRateDeposit_USD_SOFR_3M", 0.05);
/// selector.add("FixedRateDeposit_USD_SOFR_6M", 0.051);
/// selector.add("OIS_USD_SOFR_1Y", 0.048);
/// selector.add("OIS_USD_SOFR_2Y", 0.045);
///
/// // We configure a single curve for the SOFR index, with 4 pillars.
/// let spec = CurveConfiguration::new(
///     MarketIndex::SOFR,
///     Currency::USD,
///     DayCounter::Actual360,
///     Interpolator::LogLinear,
///     true,
///     vec![
///         "FixedRateDeposit_USD_SOFR_3M".into(),
///         "FixedRateDeposit_USD_SOFR_6M".into(),
///         "OIS_USD_SOFR_1Y".into(),
///         "OIS_USD_SOFR_2Y".into(),
///     ],
/// );
///
/// // Setup the discount policy and bootstrap.
/// let policy = BootstrapDiscountPolicy::new(MarketIndex::SOFR, Currency::USD);
/// let bootstrapper = MultiCurveBootstrapper::new(vec![spec], policy);
/// let result = bootstrapper.bootstrap(&selector, Level::Mid);
/// assert!(result.is_ok(), "Bootstrap failed: {:?}", result.err());
/// ```
pub struct MultiCurveBootstrapper {
    curve_specs: Vec<CurveConfiguration>,
    discount_policy: BootstrapDiscountPolicy,
    fx_store: FxStore,
}

impl MultiCurveBootstrapper {
    /// Creates a bootstrapper from a set of curve specifications.
    #[must_use]
    pub fn new(
        curve_specs: Vec<CurveConfiguration>,
        discount_policy: BootstrapDiscountPolicy,
    ) -> Self {
        Self {
            curve_specs,
            discount_policy,
            fx_store: FxStore::new(),
        }
    }

    /// Registers an [`FxStore`] for FX spot rates. Required for
    /// instruments referencing multiple currencies (e.g. cross-currency swaps, FX forwards).
    #[must_use]
    pub fn with_fx_store(mut self, store: FxStore) -> Self {
        self.fx_store = store;
        self
    }

    /// Resolves quotes, determines dependency order, and bootstraps every
    /// configured curve.
    ///
    /// ## Parameters
    /// * `selector`: the quote selector to resolve market quotes for the pillar instruments. The selector should be able to build the corresponding `CalibrationInstrumentType`s for each quote ID, as these are needed for bootstrapping.
    ///
    /// ## Errors
    /// Returns an error if quote resolution fails, a dependency cycle or
    /// missing curve is detected, or if the Newton solver does not converge
    /// for any curve.
    pub fn bootstrap(
        &self,
        selector: &impl QuoteSelector,
        level: Level,
    ) -> Result<HashMap<MarketIndex, DiscountCurveElement>> {
        // 1. Resolve all curve specs into concrete instruments.
        let mut resolved = HashMap::new();
        for spec in &self.curve_specs {
            let mut resolved_spec = (*spec).clone();
            // For cross-currency curve specs (Collateral), pass FX spot so
            // that xccy swap notionals are FX-adjusted at inception.
            let fx_spot = if let MarketIndex::Collateral(ccy, coll_ccy) = spec.market_index() {
                self.fx_store
                    .get_fx_rate(*coll_ccy, *ccy)
                    .ok()
                    .map(|r| r.value())
            } else {
                None
            };
            resolved_spec.resolve(selector, level, fx_spot)?;
            resolved.insert(resolved_spec.market_index().clone(), resolved_spec);
        }

        // 2. Topological sort respecting curve dependencies.
        let order = dependency_order(&resolved, &self.discount_policy)?;

        // 3. Iteratively bootstrap in dependency order.
        let mut solved_curves: HashMap<MarketIndex, BootstrappedCurve> = HashMap::new();
        let mut pillar_values: HashMap<MarketIndex, Vec<DualFwd>> = HashMap::new();

        for index in &order {
            let spec = resolved.get(index).ok_or_else(|| {
                QSError::NotFoundErr(format!("Missing resolved spec for {index}"))
            })?;
            let calibrated = self.bootstrap_next_curve(index, spec, &solved_curves)?;
            let calibrated_pillar_values = calibrated.pillar_values()?.to_vec();
            solved_curves.insert(index.clone(), calibrated);
            pillar_values.insert(index.clone(), calibrated_pillar_values);
        }

        // 4. Convert to DiscountCurveElements.
        let mut result = HashMap::new();
        for index in &order {
            let sc = solved_curves
                .get(index)
                .ok_or_else(|| QSError::NotFoundErr(format!("Missing solved curve for {index}")))?;
            let spec = resolved.get(index).ok_or_else(|| {
                QSError::NotFoundErr(format!("Missing resolved spec for {index}"))
            })?;
            let pv = pillar_values.get(index).ok_or_else(|| {
                QSError::NotFoundErr(format!("Missing pillar values for {index}"))
            })?;

            // Build pillar dates: reference_date followed by each instrument's pillar.
            let reference_date = spec.reference_date()?;
            let mut dates = vec![reference_date];
            dates.extend(spec.pillar_dates());

            // Use IFT-connected AD discount factors when available,
            // otherwise fall back to unconnected AD nodes.
            let ad_dfs = sc.output_discount_factors().map_or_else(
                |_| {
                    sc.discount_factors()
                        .iter()
                        .map(|&df| DualFwd::new(df))
                        .collect()
                },
                <[DualFwd]>::to_vec,
            );

            let mut ts = DiscountTermStructure::<DualFwd>::new(
                dates,
                ad_dfs,
                spec.day_counter(),
                spec.interpolator(),
                spec.enable_extrapolation(),
            )?;

            ts = ts.with_pillar_values(pv.clone())?;
            let labels = sc
                .pillar_labels()
                .map_or_else(|| spec.pillar_labels(), <[String]>::to_vec);
            ts = ts.with_pillar_labels(labels)?;
            if let Some(ift_sens) = sc.ift_sensitivities() {
                ts = ts.with_ift_sensitivities(ift_sens.clone());
            }

            let shared: SharedElement<dyn ADCurveElement> = Rc::new(RefCell::new(ts));
            let elem = DiscountCurveElement::new(index.clone(), shared);
            result.insert(index.clone(), elem);
        }
        Ok(result)
    }

    /// Bootstraps a single curve by solving for discount factors that
    /// reprice all its instruments to zero residual.
    #[allow(clippy::too_many_lines)]
    fn bootstrap_next_curve(
        &self,
        target_index: &MarketIndex,
        curve_config: &CurveConfiguration,
        other_curves: &HashMap<MarketIndex, BootstrappedCurve>,
    ) -> Result<BootstrappedCurve> {
        let reference_date = curve_config.reference_date()?;
        let dc = curve_config.day_counter();
        let interp = curve_config.interpolator();

        // Build pillar time grid: [0, t_1, t_2, …]
        let instruments = curve_config.instruments()?;
        let mut times = vec![0.0_f64];
        times.extend(
            instruments
                .iter()
                .map(|instr| dc.year_fraction(reference_date, instr.pillar_date())),
        );

        let n = instruments.len();

        // Initial guess: slight discount (safe for positive-rate environments).
        let x0 = vec![0.99; n];

        // Build the problem.
        let problem = BootstrapObjectiveFunc {
            target_index: target_index.clone(),
            reference_date,
            times: times.clone(),
            day_counter: dc,
            interpolator: interp,
            instruments,
            other_curves,
            discount_policy: &self.discount_policy,
            fx_store: &self.fx_store,
        };

        // Solve.
        let solver = VectorNewton::new(1e-12, 200);
        let solution = solver.solve(&problem, &x0)?;

        // -----------------------------------------------------------------
        // IFT post-processing
        //
        // Given the implicit relation  F(x, q, z) = 0  where x are the
        // discount factors, q the market quotes, and z the parent curve
        // discount factors, the implicit function theorem gives:
        //
        //   dx/dq = −J⁻¹ G           (own-curve sensitivity)
        //   dx/dz = −J⁻¹ (∂F/∂z)    (cross-curve sensitivity)
        //
        // where J = ∂F/∂x is the Jacobian at the solution and
        // G = ∂F/∂q is diagonal (quote q_i only enters residual F_i).
        //
        // Downstream pricers that call `backward()` on the AD tape will
        // propagate through DF → own quotes AND DF → parent DFs → parent
        // quotes correctly.
        // -----------------------------------------------------------------
        let converged_x = &solution.x;

        let mut solved_dfs = vec![1.0_f64];
        solved_dfs.extend(converged_x.iter().copied());

        // Retrieve quote values and the Jacobian J = ∂F/∂x.
        let quote_vals = curve_config.quote_values();
        let j_raw = solution
            .jacobian
            .ok_or_else(|| QSError::SolverErr("Newton solver did not return a Jacobian".into()))?;

        // Compute diagonal of G = ∂F/∂q analytically.
        let g_diag = Self::compute_quote_sensitivities(&problem, converged_x)?;

        // Build nalgebra objects and solve  J · S_col = −g_col  for each
        // quote j (only one non-zero entry per column).
        let j_data: Vec<f64> = j_raw.iter().flat_map(|row| row.iter().copied()).collect();
        let j_mat = DMatrix::from_row_slice(n, n, &j_data);
        let lu = j_mat.lu();

        // sensitivity[i][j] = ∂DF_{i+1}/∂q_j
        let mut sensitivity = vec![vec![0.0_f64; n]; n];
        for j in 0..n {
            let mut rhs = DVector::zeros(n);
            rhs[j] = g_diag[j];
            if let Some(col) = lu.solve(&rhs) {
                for i in 0..n {
                    sensitivity[i][j] = -col[i];
                }
            }
        }

        // -----------------------------------------------------------------
        // Cross-curve IFT: compute ∂DF_self/∂DF_parent for each parent.
        //
        // For each parent curve present in `other_curves`, compute the
        // matrix ∂F/∂z (how residuals depend on parent DFs) via central
        // finite differences, then solve  J · cross_col = −(∂F/∂z)_col.
        // -----------------------------------------------------------------
        let _base_residual = problem.call(converged_x)?;
        let mut cross_deps: Vec<CrossCurveDep> = Vec::new();

        for (parent_idx, parent_curve) in other_curves {
            let parent_dfs = parent_curve.discount_factors();
            let parent_n = parent_dfs.len() - 1; // excluding DF(0) = 1

            // Skip parent curves that provide no pillar IFT data
            let parent_ift = match parent_curve.ift_sensitivities() {
                Some(ift) => ift.clone(),
                None => continue,
            };
            let parent_labels: Vec<String> = parent_curve.pillar_labels().map_or_else(
                || {
                    parent_curve
                        .pillar_values()
                        .map(|pv| pv.iter().map(|_| String::new()).collect())
                        .unwrap_or_default()
                },
                <[String]>::to_vec,
            );

            // Compute ∂F/∂z by bumping each parent DF (indices 1..=parent_n)
            // dF_dz[row][col] = ∂F_row / ∂z_{col+1}
            let mut df_dz = vec![vec![0.0_f64; parent_n]; n];

            for m in 0..parent_n {
                let bump = (parent_dfs[m + 1].abs() * 1e-6).max(1e-10);

                let (up_res, up_bump) =
                    bumped_residual(&problem, parent_idx, parent_curve, m + 1, bump, converged_x)?;
                let (dn_res, dn_bump) = bumped_residual(
                    &problem,
                    parent_idx,
                    parent_curve,
                    m + 1,
                    -bump,
                    converged_x,
                )?;

                let denom = up_bump - dn_bump;
                for row in 0..n {
                    df_dz[row][m] = (up_res[row] - dn_res[row]) / denom;
                }
            }

            // Solve  J · cross_S_col = −(∂F/∂z)_col  for each parent DF
            // cross_df_sens[i][m] = ∂DF_self(i+1)/∂DF_parent(m+1)
            let mut cross_df_sens = vec![vec![0.0_f64; parent_n]; n];
            let mut has_nonzero = false;
            for m in 0..parent_n {
                let mut rhs = DVector::zeros(n);
                for row in 0..n {
                    rhs[row] = df_dz[row][m];
                }
                if let Some(col) = lu.solve(&rhs) {
                    for i in 0..n {
                        let val = -col[i];
                        if val.abs() > 1e-16 {
                            cross_df_sens[i][m] = val;
                            has_nonzero = true;
                        }
                    }
                }
            }

            if has_nonzero {
                // Retrieve parent quote values
                let parent_quote_vals: Vec<f64> = parent_curve
                    .pillar_values()
                    .map(|pv| pv.iter().map(Scalar::value).collect())
                    .unwrap_or_default();

                cross_deps.push(CrossCurveDep {
                    cross_df_sens,
                    parent_ift_sens: parent_ift,
                    parent_quote_values: parent_quote_vals,
                    parent_pillar_labels: parent_labels,
                });
            }
        }

        // Build DualFwd discount factors whose derivatives flow to the
        // quote DualFwds via the computed sensitivities.
        let quote_ad: Vec<DualFwd> = quote_vals.iter().map(|&v| DualFwd::new(v)).collect();

        // Pre-compose cross-curve dependencies into the IFT matrix.
        // For each parent, compose:  combined[i][k] = Σ_m cross_df_sens[i][m] * parent_ift_sens[m][k]
        // Extend pillar_values and pillar_labels with parent quotes.
        let mut full_sensitivity = sensitivity.clone();
        let mut full_quotes = quote_ad;
        let mut full_labels = curve_config.pillar_labels();

        for dep in &cross_deps {
            let parent_n_quotes = dep.parent_quote_values.len();
            let m_count = dep.parent_ift_sens.len();
            for (i, sensitivity_row) in full_sensitivity.iter_mut().enumerate().take(n) {
                let mut row_ext = Vec::with_capacity(parent_n_quotes);
                for k in 0..parent_n_quotes {
                    let mut combined = 0.0_f64;
                    for m in 0..m_count {
                        combined = f64::mul_add(dep.cross_df_sens[i][m], dep.parent_ift_sens[m][k], combined);
                    }
                    row_ext.push(combined);
                }
                sensitivity_row.extend(row_ext);
            }
            for &v in &dep.parent_quote_values {
                full_quotes.push(DualFwd::new(v));
            }
            full_labels.extend(dep.parent_pillar_labels.clone());
        }

        // Build output discount factors: DF_0 = 1 (constant), then each
        // DF_{i+1} = converged_value + Σ_j  S[i][j] * (q_j − q_j_value).
        // Since (q_j − q_j_value) = 0 in value, the numeric result is
        // exact; but the AD graph records ∂DF/∂q correctly.
        let n_total = full_quotes.len();
        let mut ad_dfs: Vec<DualFwd> = Vec::with_capacity(n + 1);
        ad_dfs.push(DualFwd::new(1.0)); // DF(0) = 1
        for i in 0..n {
            let mut df_ad = DualFwd::new(converged_x[i]);
            for j in 0..n_total {
                let s = full_sensitivity[i][j];
                if s.abs() > 1e-16 {
                    let delta = full_quotes[j] - DualFwd::new(full_quotes[j].value());
                    df_ad = (df_ad + DualFwd::new(s) * delta).into();
                }
            }
            ad_dfs.push(df_ad);
        }

        Ok(BootstrappedCurve::new(
            target_index.clone(),
            reference_date,
            times,
            solved_dfs,
            dc,
            interp,
        )
        .with_pillar_values(full_quotes)
        .with_pillar_labels(full_labels)
        .with_output_discount_factors(ad_dfs)
        .with_ift_sensitivities(full_sensitivity))
    }

    /// Computes the diagonal of the G = ∂F/∂q matrix analytically.
    ///
    /// Each quote only enters its own residual, so only the diagonal is
    /// non-zero.  The per-instrument `quote_sensitivity` returns `∂F_j/∂q_j`
    /// directly.
    fn compute_quote_sensitivities(
        problem: &BootstrapObjectiveFunc,
        x: &[f64],
    ) -> Result<Vec<f64>> {
        let trial = problem.create_trial_curve(x);
        let step = BootstrapStep::new(
            &trial,
            problem.other_curves,
            problem.discount_policy,
            problem.fx_store,
        );
        let evaluator = BootstrapStepEvaluation::new(&step);
        problem
            .instruments
            .iter()
            .map(|inst| evaluator.sensitivity(inst))
            .collect()
    }
}

fn bumped_residual(
    problem: &BootstrapObjectiveFunc,
    parent_idx: &MarketIndex,
    parent_curve: &BootstrappedCurve,
    parent_df_idx: usize,
    bump: f64,
    x: &[f64],
) -> Result<(Vec<f64>, f64)> {
    let original_df = parent_curve.discount_factors()[parent_df_idx];
    let bumped_df = (original_df + bump).max(1e-10);

    let mut bumped_parent = parent_curve.clone();
    bumped_parent.discount_factors_mut()[parent_df_idx] = bumped_df;

    let mut bumped_others = problem.other_curves.clone();
    bumped_others.insert(parent_idx.clone(), bumped_parent);

    let bumped_problem = BootstrapObjectiveFunc {
        target_index: problem.target_index.clone(),
        reference_date: problem.reference_date,
        times: problem.times.clone(),
        day_counter: problem.day_counter,
        interpolator: problem.interpolator,
        instruments: problem.instruments,
        other_curves: &bumped_others,
        discount_policy: problem.discount_policy,
        fx_store: problem.fx_store,
    };

    Ok((bumped_problem.call(x)?, bumped_df - original_df))
}

/// Maps a trial vector of discount factors into the residual vector used by
/// the Newton solver.
///
/// For each instrument the residual is:
/// * **Deposits / Swaps / Basis-swaps / XCcy-swaps** → NPV (should be ≈ 0)
/// * **Rate futures** → `implied_forward - market_rate`
/// * **FX forwards** → `implied_FX - market_FX`
struct BootstrapObjectiveFunc<'a> {
    pub target_index: MarketIndex,
    pub reference_date: Date,
    pub times: Vec<f64>,
    pub day_counter: DayCounter,
    pub interpolator: Interpolator,
    pub instruments: &'a [CalibrationInstrument],
    pub other_curves: &'a HashMap<MarketIndex, BootstrappedCurve>,
    pub discount_policy: &'a BootstrapDiscountPolicy,
    pub fx_store: &'a FxStore,
}

impl BootstrapObjectiveFunc<'_> {
    fn create_trial_curve(&self, x: &[f64]) -> BootstrappedCurve {
        let mut dfs = Vec::with_capacity(self.times.len());
        dfs.push(1.0_f64); // DF(0) = 1
        dfs.extend_from_slice(x);
        BootstrappedCurve::new(
            self.target_index.clone(),
            self.reference_date,
            self.times.clone(),
            dfs,
            self.day_counter,
            self.interpolator,
        )
    }
}

impl ContFunc<[f64], Vec<f64>> for BootstrapObjectiveFunc<'_> {
    fn call(&self, x: &[f64]) -> Result<Vec<f64>> {
        let trial = self.create_trial_curve(x);
        let step = BootstrapStep::new(
            &trial,
            self.other_curves,
            self.discount_policy,
            self.fx_store,
        );
        let evaluator = BootstrapStepEvaluation::new(&step);
        evaluator.residual(self.instruments)
    }
}

impl JacobianFunc<f64, f64, f64> for BootstrapObjectiveFunc<'_> {
    fn jacobian(&self, x: &[f64]) -> Result<Vec<Vec<f64>>> {
        let n = x.len();
        let mut jacobian = vec![vec![0.0; n]; n];

        for col in 0..n {
            let base_bump = (x[col].abs().max(1.0) * 1e-6).max(1e-8);
            let bump = base_bump.min((x[col] * 0.25).max(1e-8));

            let mut up = x.to_vec();
            let mut dn = x.to_vec();
            up[col] += bump;
            dn[col] = (dn[col] - bump).max(1e-8);

            let up_res = self.call(&up)?;
            let dn_res = self.call(&dn)?;
            let denom = up[col] - dn[col];

            for row in 0..n {
                jacobian[row][col] = (up_res[row] - dn_res[row]) / denom;
            }
        }

        Ok(jacobian)
    }
}

impl VectorFunc<f64, f64> for BootstrapObjectiveFunc<'_> {}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use crate::{
        ad::dual::DualFwd,
        currencies::currency::Currency,
        indices::marketindex::MarketIndex,
        math::interpolation::interpolator::Interpolator,
        quotes::{
            fxstore::FxStore,
            quote::{Level, Quote, QuoteDetails, QuoteLevels},
            quoteselector::QuoteSelector,
        },
        rates::bootstrapping::{
            bootstrapdiscountpolicy::BootstrapDiscountPolicy,
            curveconfiguration::CurveConfiguration, multicurvebootstrapper::MultiCurveBootstrapper,
        },
        time::{date::Date, daycounter::DayCounter},
        utils::errors::Result,
    };

    struct MapSelector {
        reference_date: Date,
        quotes: HashMap<String, f64>,
    }

    impl MapSelector {
        fn new(reference_date: Date) -> Self {
            Self {
                reference_date,
                quotes: HashMap::new(),
            }
        }
        fn add(&mut self, id: &str, rate: f64) {
            self.quotes.insert(id.to_string(), rate);
        }
    }

    impl QuoteSelector for MapSelector {
        fn select(&self, identifier: &str) -> Option<Quote> {
            let rate = self.quotes.get(identifier)?;
            let det: QuoteDetails = identifier.parse().ok()?;
            let q = Quote::new(det, QuoteLevels::with_mid(*rate));
            if q.build_instrument(self.reference_date, Level::Mid, None)
                .is_ok()
            {
                Some(q)
            } else {
                None
            }
        }
        fn reference_date(&self) -> Date {
            self.reference_date
        }
    }

    fn rd() -> Date {
        Date::new(2024, 6, 1)
    }

    fn default_policy() -> BootstrapDiscountPolicy {
        BootstrapDiscountPolicy::new(MarketIndex::SOFR, Currency::USD)
    }

    #[test]
    fn bootstrap_single_deposit() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.05);

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec!["FixedRateDeposit_USD_SOFR_6M".into()],
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        assert!(result.contains_key(&MarketIndex::SOFR));
        let curve = result[&MarketIndex::SOFR].curve();
        let df = curve.discount_factor(Date::new(2024, 12, 1))?;
        assert!(
            df.value() > 0.0 && df.value() < 1.0,
            "DF should be in (0,1)"
        );
        Ok(())
    }

    #[test]
    fn bootstrap_deposits_and_swaps() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        selector.add("FixedRateDeposit_USD_SOFR_3M", 0.05);
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.051);
        selector.add("OIS_USD_SOFR_1Y", 0.048);
        selector.add("OIS_USD_SOFR_2Y", 0.045);

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_3M".into(),
                "FixedRateDeposit_USD_SOFR_6M".into(),
                "OIS_USD_SOFR_1Y".into(),
                "OIS_USD_SOFR_2Y".into(),
            ],
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        let curve = result[&MarketIndex::SOFR].curve();

        // DFs should be monotonically decreasing for positive rates.
        let dates = [
            Date::new(2024, 9, 1),
            Date::new(2024, 12, 1),
            Date::new(2025, 6, 1),
            Date::new(2026, 6, 1),
        ];
        let mut prev_df = 1.0;
        for d in &dates {
            let df = curve.discount_factor(*d)?.value();
            assert!(df < prev_df, "DF at {d} should be < previous DF");
            assert!(df > 0.0, "DF should be positive");
            prev_df = df;
        }
        Ok(())
    }

    #[test]
    fn bootstrap_result_has_ift_sensitivities() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        selector.add("FixedRateDeposit_USD_SOFR_3M", 0.05);
        selector.add("OIS_USD_SOFR_1Y", 0.048);

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_3M".into(),
                "OIS_USD_SOFR_1Y".into(),
            ],
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        let elem = &result[&MarketIndex::SOFR];
        let curve = elem.curve();
        let ift = curve.ift_sensitivities();
        assert!(ift.is_some(), "IFT sensitivities should be present");

        let sens = ift.unwrap();
        assert_eq!(sens.len(), 2, "Should have 2 pillar rows");
        assert_eq!(sens[0].len(), 2, "Should have 2 quote columns");
        Ok(())
    }

    #[test]
    fn bootstrap_missing_quote_errors() {
        let selector = MapSelector::new(rd());
        // Not adding any quotes to the selector.

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec!["OIS_USD_SOFR_1Y".into()],
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid);
        assert!(result.is_err());
    }

    #[test]
    fn bootstrap_basis_swap_two_curves() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        // SOFR curve pillars
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.05);
        selector.add("OIS_USD_SOFR_1Y", 0.048);
        // TermSOFR3m curve via basis swap
        selector.add("BasisSwap_USD_SOFR_TermSOFR3m_1Y", 0.001);

        let sofr_spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_6M".into(),
                "OIS_USD_SOFR_1Y".into(),
            ],
        );
        let term_spec = CurveConfiguration::new(
            MarketIndex::TermSOFR3m,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec!["BasisSwap_USD_SOFR_TermSOFR3m_1Y".into()],
        );

        let bootstrapper =
            MultiCurveBootstrapper::new(vec![sofr_spec, term_spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        assert!(result.contains_key(&MarketIndex::SOFR));
        assert!(result.contains_key(&MarketIndex::TermSOFR3m));

        // TermSOFR3m curve should produce valid DFs.
        let term_curve = result[&MarketIndex::TermSOFR3m].curve();
        let df = term_curve.discount_factor(Date::new(2025, 6, 1))?.value();
        assert!(df > 0.0 && df < 1.0);
        Ok(())
    }

    #[test]
    fn bootstrap_fx_forward_cross_currency_missing_fx() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        // USD SOFR curve
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.05);
        selector.add("OIS_USD_SOFR_1Y", 0.048);
        // EUR collateral curve via FX forward points
        selector.add("FxForwardPoints_EURUSD_6M", 0.005);
        selector.add("FxForwardPoints_EURUSD_1Y", 0.008);

        let sofr_spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_6M".into(),
                "OIS_USD_SOFR_1Y".into(),
            ],
        );
        let collateral_spec = CurveConfiguration::new(
            MarketIndex::Collateral(Currency::EUR, Currency::USD),
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FxForwardPoints_EURUSD_6M".into(),
                "FxForwardPoints_EURUSD_1Y".into(),
            ],
        );

        let bootstrapper =
            MultiCurveBootstrapper::new(vec![sofr_spec, collateral_spec], default_policy());
        assert!(bootstrapper.bootstrap(&selector, Level::Mid).is_err());
        Ok(())
    }

    #[test]
    fn bootstrap_fx_forward_cross_currency() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        // USD SOFR curve
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.05);
        selector.add("OIS_USD_SOFR_1Y", 0.048);
        // EUR collateral curve via FX forward points
        selector.add("FxForwardPoints_EURUSD_6M", 0.005);
        selector.add("FxForwardPoints_EURUSD_1Y", 0.008);

        let sofr_spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_6M".into(),
                "OIS_USD_SOFR_1Y".into(),
            ],
        );
        let collateral_spec = CurveConfiguration::new(
            MarketIndex::Collateral(Currency::EUR, Currency::USD),
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FxForwardPoints_EURUSD_6M".into(),
                "FxForwardPoints_EURUSD_1Y".into(),
            ],
        );

        let mut fx_store = FxStore::new();
        fx_store.add_fx_rate(Currency::USD, Currency::EUR, DualFwd::new(1.08));

        let bootstrapper =
            MultiCurveBootstrapper::new(vec![sofr_spec, collateral_spec], default_policy())
                .with_fx_store(fx_store);
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        assert!(result.contains_key(&MarketIndex::SOFR));
        assert!(result.contains_key(&MarketIndex::Collateral(Currency::EUR, Currency::USD)));

        let coll_curve = result[&MarketIndex::Collateral(Currency::EUR, Currency::USD)].curve();
        let df = coll_curve.discount_factor(Date::new(2025, 6, 1))?.value();
        assert!(df > 0.0 && df < 1.5, "Collateral DF should be reasonable");
        Ok(())
    }

    #[test]
    fn bootstrap_fx_forward_cross_currency_inverse_parity() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        // USD SOFR curve
        selector.add("FixedRateDeposit_USD_SOFR_6M", 0.05);
        selector.add("OIS_USD_SOFR_1Y", 0.048);
        // EUR collateral curve via FX forward points
        selector.add("FxForwardPoints_EURUSD_6M", 0.005);
        selector.add("FxForwardPoints_EURUSD_1Y", 0.008);

        let sofr_spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FixedRateDeposit_USD_SOFR_6M".into(),
                "OIS_USD_SOFR_1Y".into(),
            ],
        );
        let collateral_spec = CurveConfiguration::new(
            MarketIndex::Collateral(Currency::EUR, Currency::USD),
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec![
                "FxForwardPoints_EURUSD_6M".into(),
                "FxForwardPoints_EURUSD_1Y".into(),
            ],
        );

        let mut fx_store = FxStore::new();
        fx_store.add_fx_rate(Currency::EUR, Currency::USD, DualFwd::new(1.0/1.08));
        fx_store.add_fx_rate(Currency::CLP, Currency::USD, DualFwd::new(900.0));

        let bootstrapper =
            MultiCurveBootstrapper::new(vec![sofr_spec, collateral_spec], default_policy())
                .with_fx_store(fx_store);
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        assert!(result.contains_key(&MarketIndex::SOFR));
        assert!(result.contains_key(&MarketIndex::Collateral(Currency::EUR, Currency::USD)));

        let coll_curve = result[&MarketIndex::Collateral(Currency::EUR, Currency::USD)].curve();
        let df = coll_curve.discount_factor(Date::new(2025, 6, 1))?.value();
        assert!(df > 0.0 && df < 1.5, "Collateral DF should be reasonable");
        Ok(())
    }

    #[test]
    fn bootstrap_rate_futures() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        selector.add("Future_USD_SOFR_U4", 95.0);
        selector.add("Future_USD_SOFR_Z4", 95.5);

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            vec!["Future_USD_SOFR_U4".into(), "Future_USD_SOFR_Z4".into()],
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        assert!(result.contains_key(&MarketIndex::SOFR));
        let curve = result[&MarketIndex::SOFR].curve();
        let df = curve.discount_factor(Date::new(2024, 12, 18))?.value();
        assert!(df > 0.0 && df < 1.0);
        Ok(())
    }

    #[test]
    fn bootstrap_reprices_inputs() -> Result<()> {
        let mut selector = MapSelector::new(rd());
        let rates = [
            ("FixedRateDeposit_USD_SOFR_3M", 0.05),
            ("FixedRateDeposit_USD_SOFR_6M", 0.051),
            ("OIS_USD_SOFR_1Y", 0.048),
        ];
        for (id, rate) in &rates {
            selector.add(id, *rate);
        }

        let spec = CurveConfiguration::new(
            MarketIndex::SOFR,
            DayCounter::Actual360,
            Interpolator::LogLinear,
            true,
            rates.iter().map(|(id, _)| (*id).into()).collect(),
        );

        let bootstrapper = MultiCurveBootstrapper::new(vec![spec], default_policy());
        let result = bootstrapper.bootstrap(&selector, Level::Mid)?;

        // The curve should have pillar labels matching the input quotes.
        let elem = &result[&MarketIndex::SOFR];
        let curve = elem.curve();
        let nodes = curve.nodes();
        assert!(nodes.is_some(), "Nodes should be available");
        let nodes = nodes.unwrap();
        // reference_date + 3 pillars = 4 nodes
        assert_eq!(nodes.len(), 4);
        // All DFs should be in (0, 1) for positive rates.
        for (_date, df) in &nodes {
            assert!(df.value() > 0.0 && df.value() <= 1.0);
        }
        Ok(())
    }
}