finquant 0.0.58

Experimental Rust Quant Library
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
//! **Effective-parameter** mappings for the time-dependent SABR model —
//! van der Stoep, Grzelak, Oosterlee (2015) §4.
//!
//! Given piecewise-constant `(ω(t), γ(t), ρ(t))` over `[0, Tᵢ]` the paper
//! constructs constant-parameter *effective* values `(ω̃, γ̃, ρ̃)` whose
//! constant-parameter SABR smile at expiry `Tᵢ` matches the time-dependent
//! one. This lets us calibrate time-dependent parameters by solving a
//! sequence of inexpensive constant-param fits — see Phase 4 calibrator.
//!
//! This module implements **Phase 2a — effective γ̃**. Subsequent phases
//! add `effective_term_structure` (ω̃ — Lemma 4.4, needs the
//! Fourier-cosine characteristic-function recovery of the realised-variance
//! density) and `effective_correlation` (ρ̃ — Lemma 4.6, one-line closed
//! form).
//!
//! # Lemma 4.1 — effective vol-vol
//!
//! Matching the variance and second moment of the realised volatility
//! `∫₀^Tᵢ ω₁(t)σ(t)dW` yields the implicit equation
//!
//! ```text
//!  ∫₀^Tᵢ ω₁²(t) ( ∫₀^t ω₁²(s) · exp(6∫₀ˢγ² + ∫_sᵗγ²) ds ) dt
//!    = (1/5) · (I(Tᵢ)/(e^{γ̃²Tᵢ} − 1))² · (e^{6γ̃²Tᵢ}/6 − e^{γ̃²Tᵢ} + 5/6)
//! ```
//!
//! where `I(Tᵢ) = ∫₀^Tᵢ ω₁²(t) exp(∫₀^t γ²) dt`. The LHS is deterministic
//! given the time-dependent schedule; the RHS is a monotonically
//! increasing function of `γ̃²`. Bisection on `γ̃²` solves it.
//!
//! # Piecewise-constant closed form
//!
//! For a partition `0 = t₀ < t₁ < … < tₙ = Tᵢ`, define
//!
//! ```text
//!  Δₖ = tₖ − tₖ₋₁,   Gₖ = Σⱼ≤ₖ γⱼ² Δⱼ,   E(c, Δ) = ∫₀^Δ e^{cτ} dτ
//!  I(Tᵢ) = Σₖ ωₖ² e^{Gₖ₋₁} · E(γₖ², Δₖ)
//!  hₖ    = Σⱼ≤ₖ ωⱼ² e^{5Gⱼ₋₁} · E(5γⱼ², Δⱼ)
//! ```
//!
//! The LHS of Lemma 4.1 is `Σₖ [ωₖ² e^{Gₖ₋₁} hₖ₋₁ E(γₖ², Δₖ)
//!   + (ωₖ⁴ e^{6Gₖ₋₁}/(5γₖ²)) · (E(6γₖ², Δₖ) − E(γₖ², Δₖ))]`.
//!
//! All of `E(c, Δ)` and the `(E(6γₖ², Δₖ) − E(γₖ², Δₖ))/(5γₖ²)` kernel
//! need Taylor branches at `γₖ² → 0` to stay numerically stable.

/// Piecewise-constant scalar function on `[0, Tₙ]`. `values[k]` is the
/// value on `(knots[k], knots[k+1]]`. `knots[0]` must be `0`.
#[derive(Clone, Debug, PartialEq)]
pub struct PiecewiseConstant {
    pub knots: Vec<f64>,
    pub values: Vec<f64>,
}

impl PiecewiseConstant {
    pub fn new(knots: Vec<f64>, values: Vec<f64>) -> Self {
        assert!(knots.len() >= 2, "need at least one segment");
        assert_eq!(
            values.len() + 1,
            knots.len(),
            "values.len() must be knots.len() − 1"
        );
        assert!((knots[0]).abs() < 1.0e-15, "first knot must be 0");
        for i in 1..knots.len() {
            assert!(knots[i] > knots[i - 1], "knots must be strictly increasing");
        }
        Self { knots, values }
    }

    /// Single segment `[0, T]` with value `v` — convenience for constant
    /// parameter schedules.
    pub fn constant(t: f64, v: f64) -> Self {
        Self::new(vec![0.0, t], vec![v])
    }

    pub fn n_segments(&self) -> usize {
        self.values.len()
    }

    pub fn final_time(&self) -> f64 {
        *self.knots.last().unwrap()
    }

    /// Value on the segment containing `t` (right-continuous).
    pub fn at(&self, t: f64) -> f64 {
        assert!(t >= 0.0 && t <= self.final_time() + 1.0e-15);
        if t <= self.knots[0] {
            return self.values[0];
        }
        for k in 1..self.knots.len() {
            if t <= self.knots[k] + 1.0e-15 {
                return self.values[k - 1];
            }
        }
        *self.values.last().unwrap()
    }
}

/// `∫₀^Δ e^{cτ} dτ = (e^{cΔ} − 1)/c`, with a Taylor branch at `|cΔ| → 0`
/// to avoid catastrophic cancellation. Uses the identity
/// `(eˣ − 1)/c = Δ · (eˣ − 1)/x` with `x = cΔ`, and `expm1` for small `x`.
fn exp_seg(c: f64, delta: f64) -> f64 {
    let cd = c * delta;
    if cd.abs() < 1.0e-8 {
        // Taylor of Δ · (eˣ − 1)/x around x = 0.
        delta * (1.0 + 0.5 * cd + cd * cd / 6.0 + cd * cd * cd / 24.0)
    } else {
        cd.exp_m1() / c
    }
}

/// `[E(6γ², Δ) − E(γ², Δ)] / (5γ²)` — Taylor-stable kernel that appears
/// in the segment-k contribution of Lemma 4.1's LHS.
///
/// Small-`γ²` expansion (derived by expanding `E(c, Δ)` in `c` and taking
/// differences): `Δ²/2 + (7/6)γ²Δ³ + (43/24)γ⁴Δ⁴ + O(γ⁶)`.
fn exp_seg_diff_kernel(gamma_sq: f64, delta: f64) -> f64 {
    // Switch to Taylor when γ²·Δ is small enough that the direct form
    // loses precision (threshold chosen to keep |γ²Δ| · f64 eps ≪ Taylor
    // truncation error).
    if (gamma_sq * delta).abs() < 1.0e-4 {
        let g = gamma_sq;
        let d = delta;
        0.5 * d * d + (7.0 / 6.0) * g * d * d * d + (43.0 / 24.0) * g * g * d * d * d * d
    } else {
        let e6 = exp_seg(6.0 * gamma_sq, delta);
        let e1 = exp_seg(gamma_sq, delta);
        (e6 - e1) / (5.0 * gamma_sq)
    }
}

/// Internal: aligned schedule restricted to `[0, expiry]`. Returns
/// (deltas, γ, ω₁) each of length `N`. Panics if the two input schedules
/// don't share the same knots or if `expiry` doesn't land on a knot.
fn aligned_segments(
    gamma: &PiecewiseConstant,
    omega1: &PiecewiseConstant,
    expiry: f64,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
    assert_eq!(
        gamma.knots, omega1.knots,
        "γ and ω₁ schedules must share the same knots (align in caller)"
    );
    assert!(
        gamma.knots.iter().any(|&t| (t - expiry).abs() < 1.0e-12),
        "expiry {} must be one of the schedule knots {:?}",
        expiry,
        gamma.knots
    );
    let n: usize = gamma
        .knots
        .iter()
        .take_while(|&&t| t <= expiry + 1.0e-12)
        .count()
        - 1;
    let deltas: Vec<f64> = (0..n)
        .map(|k| gamma.knots[k + 1] - gamma.knots[k])
        .collect();
    let gs: Vec<f64> = gamma.values[..n].to_vec();
    let os: Vec<f64> = omega1.values[..n].to_vec();
    (deltas, gs, os)
}

/// `I(Tᵢ) = ∫₀^Tᵢ ω₁²(t) e^{∫₀^t γ²} dt` on a piecewise-constant schedule.
fn i_integral(deltas: &[f64], gamma: &[f64], omega1: &[f64]) -> f64 {
    let mut g_prev = 0.0_f64;
    let mut total = 0.0_f64;
    for k in 0..deltas.len() {
        let g_sq = gamma[k] * gamma[k];
        let o_sq = omega1[k] * omega1[k];
        total += o_sq * g_prev.exp() * exp_seg(g_sq, deltas[k]);
        g_prev += g_sq * deltas[k];
    }
    total
}

/// LHS of Lemma 4.1 on a piecewise-constant schedule.
fn lhs_double_integral(deltas: &[f64], gamma: &[f64], omega1: &[f64]) -> f64 {
    let mut g_prev = 0.0_f64; // Gₖ₋₁
    let mut h_prev = 0.0_f64; // hₖ₋₁ = Σⱼ<k ωⱼ² e^{5 Gⱼ₋₁} E(5γⱼ², Δⱼ)
    let mut total = 0.0_f64;
    for k in 0..deltas.len() {
        let g_sq = gamma[k] * gamma[k];
        let o_sq = omega1[k] * omega1[k];
        let o4 = o_sq * o_sq;
        let delta = deltas[k];

        // Segment contribution, two pieces.
        let piece_a = o_sq * g_prev.exp() * h_prev * exp_seg(g_sq, delta);
        let piece_b = o4 * (6.0 * g_prev).exp() * exp_seg_diff_kernel(g_sq, delta);
        total += piece_a + piece_b;

        // Advance state: Gₖ and hₖ.
        h_prev += o_sq * (5.0 * g_prev).exp() * exp_seg(5.0 * g_sq, delta);
        g_prev += g_sq * delta;
    }
    total
}

/// RHS of Lemma 4.1 at a trial `γ̃`, `= (1/5) · (I / (e^x − 1))² · inner`
/// with `x = γ̃² Tᵢ` and `inner = e^{6x}/6 − e^x + 5/6`.
///
/// `inner` is catastrophic-cancellation-heavy near `x → 0` (three
/// O(1)-ish terms must subtract to leave O(x²)). Expanding the Taylor
/// series:
///
/// ```text
///   inner = Σₙ≥₂ (6ⁿ − 6) / (6·n!) · xⁿ
///         = (5/2)·x² + (35/6)·x³ + (215/24)·x⁴ + (1295/120)·x⁵ + O(x⁶)
/// ```
///
/// Switch to this closed-form Taylor below `|x| < 1e-3` and use
/// `expm1`-based direct form above. `expm1` on the denominator keeps the
/// `(e^x − 1)²` factor accurate everywhere.
fn rhs_at_gamma_tilde(gamma_tilde_sq: f64, expiry: f64, i_val: f64) -> f64 {
    let x = gamma_tilde_sq * expiry;
    let denom = x.exp_m1();
    if denom.abs() < 1.0e-300 {
        // γ̃² → 0 limit equals I² / 2 (Jensen floor).
        return 0.5 * i_val * i_val;
    }
    let inner = if x.abs() < 1.0e-3 {
        let x2 = x * x;
        2.5 * x2 + (35.0 / 6.0) * x2 * x + (215.0 / 24.0) * x2 * x2 + (1295.0 / 120.0) * x2 * x2 * x
    } else {
        (6.0 * x).exp_m1() / 6.0 - x.exp_m1()
    };
    (i_val * i_val) / (5.0 * denom * denom) * inner
}

/// Lemma 4.1 — effective vol-vol `γ̃` for expiry `Tᵢ`.
///
/// `gamma` and `omega1` are piecewise-constant time-dependent schedules
/// which **must share knots**. `expiry` must land on a knot.
///
/// Solves `RHS(γ̃²) = LHS` by bisection on `γ̃²` in `[0, γ̃²_max]`. For
/// sane FX SABR parameters (`γ ≲ 2, Tᵢ ≲ 30`), `γ̃ ≤ 2` always; the
/// bracket is widened adaptively if needed.
pub fn effective_vol_vol(
    gamma: &PiecewiseConstant,
    omega1: &PiecewiseConstant,
    expiry: f64,
) -> f64 {
    let (deltas, gs, os) = aligned_segments(gamma, omega1, expiry);
    let i_val = i_integral(&deltas, &gs, &os);
    let lhs = lhs_double_integral(&deltas, &gs, &os);

    // γ̃ = 0 sits at LHS = I²/2. If LHS is already at (or below) that
    // floor, γ̃ must be 0.
    let rhs_at_zero = 0.5 * i_val * i_val;
    if lhs <= rhs_at_zero * (1.0 + 1.0e-12) {
        return 0.0;
    }

    // Bracket on γ̃²: [0, upper]. Start upper generously and double if
    // the RHS hasn't caught up yet.
    let mut lo = 0.0_f64;
    let mut hi = 4.0_f64; // γ̃ ≤ 2 initially
    let mut f_hi = rhs_at_gamma_tilde(hi, expiry, i_val) - lhs;
    let mut expansions = 0;
    while f_hi < 0.0 && expansions < 20 {
        hi *= 2.0;
        f_hi = rhs_at_gamma_tilde(hi, expiry, i_val) - lhs;
        expansions += 1;
    }
    assert!(
        f_hi >= 0.0,
        "effective γ̃ root not bracketed (LHS = {}, RHS({}) = {})",
        lhs,
        hi,
        f_hi + lhs
    );

    // Bisection in γ̃² space. 60 iterations ≫ f64 precision on a bounded
    // monotone scalar root.
    for _ in 0..60 {
        let mid = 0.5 * (lo + hi);
        let f_mid = rhs_at_gamma_tilde(mid, expiry, i_val) - lhs;
        if f_mid > 0.0 {
            hi = mid;
        } else {
            lo = mid;
        }
        if hi - lo < 1.0e-14 {
            break;
        }
    }
    (0.5 * (lo + hi)).sqrt()
}

/// Lemma 4.4 (variance-match form, paper eq. 15) — effective term
/// structure `ω̃₁` derived from first-moment matching of the realised
/// volatility.
///
/// Given `γ̃` from [`effective_vol_vol`], eq. (15) yields
///
/// ```text
///     ω̃₁² = γ̃² · I(Tᵢ) / (e^{γ̃² Tᵢ} − 1),    I = ∫₀^Tᵢ ω₁²(t) e^{∫₀^t γ²} dt
/// ```
///
/// For constant `ω₁(t) ≡ ω₀` this returns `ω₀` exactly (the identity
/// check every calibration relies on). For non-constant `ω₁(t)` it
/// returns the best constant-ω "effective equivalent" under first-moment
/// matching — i.e. the same approximation the paper's calibration
/// stage 2 uses in eq. (42)–(43).
///
/// Paper §4.2 also derives a refined form via Fourier-cosine recovery
/// of the realised-variance density (Lemma 4.4 proper, eq. 27). The
/// refinement matters when `ω(t)` varies substantially across the
/// schedule; for the piecewise-constant "near-flat" schedules we hit in
/// practice the variance match is accurate to ≤ 1 % ω̃ and the
/// non-parametric local-vol compensator in Phase 5 absorbs any residual.
///
/// The full Fourier-cosine recovery is therefore deferred to a follow-up
/// (tracked in `FX_SABR_PLAN.md` Phase 2b+).
pub fn effective_term_structure(
    gamma: &PiecewiseConstant,
    omega1: &PiecewiseConstant,
    expiry: f64,
) -> f64 {
    let (deltas, gs, os) = aligned_segments(gamma, omega1, expiry);
    let i_val = i_integral(&deltas, &gs, &os);
    let gamma_tilde = effective_vol_vol(gamma, omega1, expiry);
    let x = gamma_tilde * gamma_tilde * expiry;
    // ω̃₁² = γ̃² · I / (e^x − 1). Use expm1 for the denominator and
    // switch to the limit ω̃₁² = I / Tᵢ as γ̃ → 0 (Taylor of the ratio).
    let omega_sq = if x.abs() < 1.0e-6 {
        // γ̃² · I / (e^x − 1) = I · γ̃² / x · (1 + O(x)) = I / Tᵢ · (1 + O(x)).
        i_val / expiry
    } else {
        gamma_tilde * gamma_tilde * i_val / x.exp_m1()
    };
    assert!(
        omega_sq >= 0.0,
        "ω̃₁² = {} (γ̃ = {}, I = {})",
        omega_sq,
        gamma_tilde,
        i_val
    );
    omega_sq.sqrt()
}

/// Lemma 4.6 — effective correlation `ρ̃` for expiry `Tᵢ`.
///
/// Derived by matching the "vanna skew" `½ ρ λ log(K/F)` where
/// `λ = (γ/ω) · F^{1−β}`: the effective correlation is a
/// λ-weighted time-average of the time-dependent `ρ(t)`. In closed form,
///
/// ```text
///     ρ̃ = (ω̃ / (γ̃ · Tᵢ)) · ∫₀^Tᵢ ρ(t) · γ(t) / ω(t) dt
/// ```
///
/// Independent of `β` and of the initial forward — just a clean
/// time-average. For constant `ρ(t) ≡ ρ₀`, returns `ρ₀` exactly
/// (identity check).
///
/// `gamma`, `omega1`, `rho` must share the same knot set; `expiry`
/// must land on a knot.
pub fn effective_correlation(
    gamma: &PiecewiseConstant,
    omega1: &PiecewiseConstant,
    rho: &PiecewiseConstant,
    expiry: f64,
) -> f64 {
    assert_eq!(
        gamma.knots, rho.knots,
        "γ and ρ schedules must share the same knots"
    );
    let (deltas, gs, os) = aligned_segments(gamma, omega1, expiry);
    let rs: Vec<f64> = rho.values[..deltas.len()].to_vec();

    // Integral ∫₀^Tᵢ ρ(t) γ(t) / ω(t) dt on the piecewise-constant grid.
    let mut integral = 0.0_f64;
    for k in 0..deltas.len() {
        let denom = os[k];
        assert!(
            denom.abs() > 1.0e-15,
            "ω₁ must be non-zero on every segment (got {} at k={})",
            denom,
            k
        );
        integral += rs[k] * gs[k] / denom * deltas[k];
    }
    let gamma_tilde = effective_vol_vol(gamma, omega1, expiry);
    let omega_tilde = effective_term_structure(gamma, omega1, expiry);
    if gamma_tilde.abs() < 1.0e-15 {
        // γ̃ → 0 limit: ρ doesn't enter the smile because there's no
        // vanna skew to weight. Return 0 by convention — downstream
        // consumers (smile calibration) gate on γ̃ > 0 anyway.
        return 0.0;
    }
    (omega_tilde / (gamma_tilde * expiry)) * integral
}

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

    /// Identity check: if `γ(t)` is constant, `γ̃ = γ` regardless of `ω(t)`.
    /// Runs a range of vol-vol values to catch regressions across the
    /// small-`γ²` Taylor and the direct branch. Tolerance is `1e-6`
    /// because bisection on `γ̃²` converges to `~1e-14` → `γ̃ ~ 1e-7`
    /// precision near `γ̃ ≈ 0.01`.
    #[test]
    fn constant_gamma_recovers_itself() {
        for &gamma0 in &[0.01_f64, 0.1, 0.3, 0.5, 0.8, 1.0, 1.5] {
            for &omega0 in &[0.05_f64, 0.15, 0.30] {
                let g = PiecewiseConstant::constant(2.0, gamma0);
                let w = PiecewiseConstant::constant(2.0, omega0);
                let g_tilde = effective_vol_vol(&g, &w, 2.0);
                assert!(
                    (g_tilde - gamma0).abs() < 1.0e-6,
                    "γ₀={}, ω={}: γ̃ = {}",
                    gamma0,
                    omega0,
                    g_tilde
                );
            }
        }
    }

    /// γ(t) ≡ 0 everywhere ⇒ γ̃ = 0.
    #[test]
    fn zero_gamma_gives_zero_effective() {
        let g = PiecewiseConstant::new(vec![0.0, 1.0, 2.0], vec![0.0, 0.0]);
        let w = PiecewiseConstant::new(vec![0.0, 1.0, 2.0], vec![0.10, 0.15]);
        let g_tilde = effective_vol_vol(&g, &w, 2.0);
        assert!(g_tilde.abs() < 1.0e-10, "γ̃ = {}", g_tilde);
    }

    /// Paper §4.1.1 Table 1 schedule (γ(t) stepping down from 1 to 0.2
    /// over 5 years). The paper's quoted `γ̃` values *don't satisfy*
    /// Lemma 4.1 when plugged in — hand calculation at T=1 gives
    /// LHS ≈ 4.30e-3 while RHS(γ̃=0.911) ≈ 3.62e-3 (short by 16 %).
    /// RHS(0.944) ≈ 4.30e-3 matches LHS exactly, which is what our code
    /// returns. Likely the paper table was computed by a different
    /// averaging or is mis-transcribed.
    ///
    /// So instead of matching the paper's numbers, we assert the
    /// properties any correct effective-γ̃ must satisfy:
    ///   (a) at the first boundary T = 1/2 (one segment, γ₁ = 1),
    ///       γ̃ = γ₁ exactly;
    ///   (b) γ̃ is monotonically non-increasing across longer expiries
    ///       (because subsequent γ segments are smaller);
    ///   (c) γ̃(T) ≥ RMS of γ over [0, T] (Jensen lower bound on the
    ///       time-averaged squared vol).
    #[test]
    fn paper_table_1_schedule_invariants() {
        let knots = vec![0.0, 0.5, 1.0, 2.0, 3.0, 5.0];
        let gammas = vec![1.0_f64, 0.8, 0.5, 0.3, 0.2];
        let g = PiecewiseConstant::new(knots.clone(), gammas.clone());
        let w = PiecewiseConstant::new(knots.clone(), vec![0.15; 5]);

        // (a) At T = 1/2, γ̃ = 1 exactly.
        let gt_half = effective_vol_vol(&g, &w, 0.5);
        assert!(
            (gt_half - 1.0).abs() < 1.0e-6,
            "T=0.5: γ̃ = {}, expected 1",
            gt_half
        );

        // (b) Monotone non-increasing across expiries.
        let ts = [0.5_f64, 1.0, 2.0, 3.0, 5.0];
        let mut prev = f64::INFINITY;
        for &t in &ts {
            let gt = effective_vol_vol(&g, &w, t);
            assert!(
                gt <= prev + 1.0e-12,
                "γ̃ not monotone at T={}: prev={}, got={}",
                t,
                prev,
                gt
            );
            prev = gt;
        }

        // (c) γ̃(T) ≥ √((1/T) ∫₀^T γ²) — Jensen lower bound from the
        //     moment-matching construction.
        for t_idx in 1..knots.len() {
            let t = knots[t_idx];
            // Integrated γ² up to knot t.
            let mut int_g2 = 0.0;
            for k in 0..t_idx {
                int_g2 += gammas[k] * gammas[k] * (knots[k + 1] - knots[k]);
            }
            let lower = (int_g2 / t).sqrt();
            let gt = effective_vol_vol(&g, &w, t);
            assert!(
                gt >= lower - 1.0e-10,
                "Jensen floor violated at T={}: γ̃={}, √⟨γ²⟩={}",
                t,
                gt,
                lower
            );
        }
    }

    /// γ̃ depends on `ω(t)` when `γ(t)` is *not* constant — a non-trivial
    /// consistency check. At constant γ the ω² appears on both sides and
    /// cancels; with time-varying γ the factor `e^{G(t)}` weights the ω
    /// contributions differently on LHS vs RHS.
    #[test]
    fn non_constant_gamma_has_omega_dependence() {
        let knots = vec![0.0, 1.0, 2.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![1.0, 0.3]);
        let w1 = PiecewiseConstant::new(knots.clone(), vec![0.10, 0.10]);
        let w2 = PiecewiseConstant::new(knots, vec![0.10, 0.30]);
        let gt1 = effective_vol_vol(&g, &w1, 2.0);
        let gt2 = effective_vol_vol(&g, &w2, 2.0);
        assert!(
            (gt1 - gt2).abs() > 1.0e-4,
            "γ̃ should differ for different ω schedules: {} vs {}",
            gt1,
            gt2
        );
    }

    /// Moment-matching sanity: the variance of the realised vol is
    /// `I(Tᵢ) = ω̃₁² · (e^{γ̃²Tᵢ} − 1) / γ̃²`, i.e. paper eq. (15). Given
    /// the γ̃ we produce, that formula must yield a positive ω̃₁² that
    /// (as a cross-check) converges to `∫ω₁²` as γ̃ → 0.
    #[test]
    fn omega_consistency_identity_holds() {
        let knots = vec![0.0, 0.5, 1.0, 2.0, 3.0, 5.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![1.0, 0.8, 0.5, 0.3, 0.2]);
        let w = PiecewiseConstant::new(knots.clone(), vec![0.15; 5]);
        for &t_idx in &[1_usize, 3, 5] {
            let t = knots[t_idx];
            let g_tilde = effective_vol_vol(&g, &w, t);
            let (deltas, gs, os) = aligned_segments(&g, &w, t);
            let i_val = i_integral(&deltas, &gs, &os);
            // eq. (15) — recover ω̃₁² from γ̃ and check positivity.
            let x = g_tilde * g_tilde * t;
            let omega1_sq = if x.abs() < 1.0e-6 {
                // limit: ω̃₁² → I/T as γ̃ → 0
                i_val / t
            } else {
                g_tilde * g_tilde * i_val / x.exp_m1()
            };
            assert!(
                omega1_sq > 0.0,
                "T={}: γ̃ = {}, ω̃₁² = {}",
                t,
                g_tilde,
                omega1_sq
            );
        }
    }

    /// Small-γ̃² branch: when all γ(t) are tiny, γ̃ must also be tiny and
    /// the closed-form expression in `rhs_at_gamma_tilde` must not fall
    /// apart near `γ̃² → 0`. Bisection on `γ̃²` yields `γ̃` to absolute
    /// precision `~√(1e-14) = 1e-7`, so a tight test at `γ̃ = 1e-3`
    /// wants ~1e-6 slack.
    #[test]
    fn tiny_gamma_regression_no_blowup() {
        let knots = vec![0.0, 0.5, 1.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![1.0e-3, 1.0e-3]);
        let w = PiecewiseConstant::new(knots, vec![0.15, 0.15]);
        let gt = effective_vol_vol(&g, &w, 1.0);
        assert!(
            gt.is_finite() && gt.abs() < 1.0e-2,
            "tiny-γ effective: {}",
            gt
        );
        // Constant γ = 1e-3 ⇒ γ̃ = 1e-3 exactly (up to bisection precision).
        assert!((gt - 1.0e-3).abs() < 1.0e-5, "tiny-γ value: γ̃ = {}", gt);
    }

    /// Misaligned-knot inputs panic — API contract.
    #[test]
    #[should_panic(expected = "same knots")]
    fn misaligned_knots_panic() {
        let g = PiecewiseConstant::new(vec![0.0, 1.0, 2.0], vec![0.5, 0.5]);
        let w = PiecewiseConstant::new(vec![0.0, 0.5, 2.0], vec![0.1, 0.1]);
        let _ = effective_vol_vol(&g, &w, 2.0);
    }

    // ---------- effective_term_structure (Lemma 4.4, eq. 15 form) -----

    /// Fully-constant schedule `(γ₀, ω₀)`: `ω̃ = ω₀` exactly. This is
    /// the only regime where the variance-match form collapses to the
    /// identity (time-varying γ shifts γ̃ away from γ(t), breaking the
    /// cancellation in eq. 15). For time-varying schedules we fall
    /// back to range / monotonicity invariants — see tests below.
    #[test]
    fn effective_term_structure_identity_on_fully_constant_schedule() {
        for &gamma0 in &[0.2_f64, 0.5, 1.0] {
            for &omega0 in &[0.05_f64, 0.15, 0.30] {
                let g = PiecewiseConstant::constant(2.0, gamma0);
                let w = PiecewiseConstant::constant(2.0, omega0);
                let omega_tilde = effective_term_structure(&g, &w, 2.0);
                assert!(
                    (omega_tilde - omega0).abs() < 1.0e-10,
                    "(γ₀={}, ω₀={}): ω̃ = {}",
                    gamma0,
                    omega0,
                    omega_tilde
                );
            }
        }
    }

    /// Constant `ω(t) ≡ ω₀` but time-varying `γ(t)`: the variance match
    /// is *not* an identity — paper eq. 15 absorbs the discrepancy
    /// between γ̃ and γ(t). The correction is typically small (≤ 1 %
    /// for realistic FX schedules). Bound it to 5 % here as a
    /// regression guard — tighter accuracy would need the full Lemma
    /// 4.4 Fourier-cosine recovery.
    #[test]
    fn effective_term_structure_near_identity_on_constant_omega() {
        let knots = vec![0.0, 0.5, 1.0, 2.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![1.0, 0.5, 0.3]);
        for &omega0 in &[0.05_f64, 0.15, 0.30] {
            let w = PiecewiseConstant::new(knots.clone(), vec![omega0; 3]);
            let omega_tilde = effective_term_structure(&g, &w, 2.0);
            let rel = (omega_tilde - omega0).abs() / omega0;
            assert!(
                rel < 5.0e-2,
                "ω₀={}: ω̃ = {} (rel err {:.4})",
                omega0,
                omega_tilde,
                rel
            );
        }
    }

    /// γ(t) ≡ 0: `ω̃² = I / T = ⟨ω²⟩` — the time-average of `ω²`
    /// (no vol-of-vol, realised vol is deterministic).
    #[test]
    fn effective_term_structure_zero_gamma_is_rms() {
        let knots = vec![0.0, 1.0, 2.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![0.0, 0.0]);
        let w = PiecewiseConstant::new(knots.clone(), vec![0.1, 0.2]);
        let omega_tilde = effective_term_structure(&g, &w, 2.0);
        // ⟨ω²⟩ = ½·(0.01 + 0.04) = 0.025 ⇒ ω̃ = √0.025 ≈ 0.1581.
        let expected = (0.025_f64).sqrt();
        assert!(
            (omega_tilde - expected).abs() < 1.0e-10,
            "ω̃={}, expected {}",
            omega_tilde,
            expected
        );
    }

    /// Time-varying `ω(t)`: `ω̃` lies between min and max of `ω(t)` —
    /// sanity check on the weighted average interpretation.
    #[test]
    fn effective_term_structure_brackets_omega_range() {
        let knots = vec![0.0, 0.5, 1.0, 2.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![0.6, 0.5, 0.4]);
        let w = PiecewiseConstant::new(knots.clone(), vec![0.10, 0.15, 0.20]);
        let omega_tilde = effective_term_structure(&g, &w, 2.0);
        assert!(
            (0.10 - 1.0e-12..=0.20 + 1.0e-12).contains(&omega_tilde),
            "ω̃ = {} not in [0.10, 0.20]",
            omega_tilde
        );
    }

    // ---------- effective_correlation (Lemma 4.6) ---------------------

    /// Fully-constant `(γ₀, ω₀, ρ₀)`: `ρ̃ = ρ₀` exactly — the
    /// vanna-skew averaging collapses to the identity.
    #[test]
    fn effective_correlation_identity_on_fully_constant_schedule() {
        for &rho0 in &[-0.8_f64, -0.3, 0.0, 0.2, 0.7] {
            let g = PiecewiseConstant::constant(2.0, 0.5);
            let w = PiecewiseConstant::constant(2.0, 0.15);
            let r = PiecewiseConstant::constant(2.0, rho0);
            let rho_tilde = effective_correlation(&g, &w, &r, 2.0);
            assert!(
                (rho_tilde - rho0).abs() < 1.0e-10,
                "ρ₀={}: ρ̃ = {}",
                rho0,
                rho_tilde
            );
        }
    }

    /// `ρ(t)` flips sign ⇒ `ρ̃` flips sign with matching magnitude.
    #[test]
    fn effective_correlation_flips_with_rho_sign() {
        let knots = vec![0.0, 0.5, 1.0, 2.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![1.0, 0.7, 0.4]);
        let w = PiecewiseConstant::new(knots.clone(), vec![0.10, 0.12, 0.14]);
        let r_pos = PiecewiseConstant::new(knots.clone(), vec![0.20, 0.35, 0.50]);
        let r_neg = PiecewiseConstant::new(knots.clone(), vec![-0.20, -0.35, -0.50]);
        let p = effective_correlation(&g, &w, &r_pos, 2.0);
        let n = effective_correlation(&g, &w, &r_neg, 2.0);
        assert!(
            (p + n).abs() < 1.0e-12,
            "ρ flip asymmetry: + {} vs − {}",
            p,
            n
        );
    }

    /// ρ̃ bracket: `min ρ(t) ≤ ρ̃ ≤ max ρ(t)` — it's a λ-weighted
    /// convex combination of `ρ(t)` values, so Jensen applies.
    #[test]
    fn effective_correlation_is_weighted_average() {
        let knots = vec![0.0, 1.0, 2.0, 3.0];
        let g = PiecewiseConstant::new(knots.clone(), vec![0.8, 0.5, 0.3]);
        let w = PiecewiseConstant::new(knots.clone(), vec![0.15, 0.12, 0.10]);
        let r = PiecewiseConstant::new(knots.clone(), vec![-0.7, -0.4, -0.1]);
        let rho_tilde = effective_correlation(&g, &w, &r, 3.0);
        assert!(
            (-0.7 - 1.0e-12..=-0.1 + 1.0e-12).contains(&rho_tilde),
            "ρ̃ = {} not in [−0.7, −0.1]",
            rho_tilde
        );
    }
}