libitofin 0.31.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Close-price and OHLC volatility estimators aligned with chart input bars.

use crate::errors::QlResult;
use crate::math::chart::ChartSeries;
use crate::prices::IntervalPrice;
use crate::require;
use crate::types::Real;

/// Annualized point estimates aligned with every input OHLC bar.
#[derive(Clone, Debug, PartialEq)]
pub struct OhlcPointEstimates {
    pub simple_sigma: ChartSeries,
    pub parkinson_sigma: ChartSeries,
    pub garman_klass_sigma4: ChartSeries,
    pub garman_klass_sigma5: ChartSeries,
}

/// Annualized overnight-aware estimates aligned with every input OHLC bar.
#[derive(Clone, Debug, PartialEq)]
pub struct OhlcOvernightEstimates {
    pub garman_klass_sigma1: ChartSeries,
    pub garman_klass_sigma3: ChartSeries,
    pub garman_klass_sigma6: ChartSeries,
}

/// Estimates three QuantLib overnight volatilities from consecutive OHLC bars.
/// `year_fractions[i]` belongs to the interval ending at `i`; index zero is unused.
/// `overnight_fraction` is the fraction of each interval while the market is closed.
///
/// # Errors
/// Returns an error for mismatched lengths, invalid OHLC prices or used fractions,
/// or a negative or nonfinite annualized variance.
pub fn ohlc_overnight_volatility(
    prices: &[IntervalPrice],
    year_fractions: &[Real],
    overnight_fraction: Real,
) -> QlResult<OhlcOvernightEstimates> {
    require!(
        prices.len() == year_fractions.len(),
        "OHLC and year-fraction lengths differ"
    );
    for (index, fraction) in year_fractions.iter().enumerate().skip(1) {
        require!(
            fraction.is_finite() && *fraction > 0.0,
            "invalid year fraction at index {index}"
        );
    }
    ohlc_overnight(prices, overnight_fraction, |index| year_fractions[index])
}

/// Estimates three QuantLib overnight volatilities with a common year fraction.
/// The first bar is a zero placeholder because it has no preceding close.
///
/// # Errors
/// Returns an error for invalid OHLC prices or fractions, or a negative or
/// nonfinite annualized variance.
pub fn ohlc_overnight_volatility_constant_fraction(
    prices: &[IntervalPrice],
    year_fraction: Real,
    overnight_fraction: Real,
) -> QlResult<OhlcOvernightEstimates> {
    require!(
        year_fraction.is_finite() && year_fraction > 0.0,
        "year fraction must be positive and finite"
    );
    ohlc_overnight(prices, overnight_fraction, |_| year_fraction)
}

fn ohlc_overnight(
    prices: &[IntervalPrice],
    overnight_fraction: Real,
    year_fraction: impl Fn(usize) -> Real,
) -> QlResult<OhlcOvernightEstimates> {
    require!(
        overnight_fraction.is_finite() && overnight_fraction > 0.0 && overnight_fraction < 1.0,
        "overnight fraction must be finite and between zero and one"
    );
    let len = prices.len();
    let mut result = OhlcOvernightEstimates {
        garman_klass_sigma1: ChartSeries::zeroed(len, 1)?,
        garman_klass_sigma3: ChartSeries::zeroed(len, 1)?,
        garman_klass_sigma6: ChartSeries::zeroed(len, 1)?,
    };
    for (index, price) in prices.iter().copied().enumerate() {
        let [simple, parkinson, sigma4, _] = ohlc_point_terms(price, index)?;
        if index == 0 {
            continue;
        }
        let gap = log_ratio(price.open(), prices[index - 1].close());
        for (weight, point, series) in [
            (0.5, simple, &mut result.garman_klass_sigma1),
            (0.17, parkinson, &mut result.garman_klass_sigma3),
            (0.012, sigma4, &mut result.garman_klass_sigma6),
        ] {
            series.values[index] = overnight_volatility(
                gap,
                point,
                weight,
                overnight_fraction,
                year_fraction(index),
                index,
            )?;
        }
    }
    Ok(result)
}

fn overnight_volatility(
    gap: Real,
    point: Real,
    weight: Real,
    overnight_fraction: Real,
    year_fraction: Real,
    index: usize,
) -> QlResult<Real> {
    let variance = weight * gap * gap / overnight_fraction
        + (1.0 - weight) * point / (1.0 - overnight_fraction);
    let root = if variance.is_finite() {
        require!(
            variance.is_sign_positive() || variance == 0.0,
            "negative overnight variance at index {index}"
        );
        variance.sqrt()
    } else {
        let overnight = gap.abs() * weight.sqrt() / overnight_fraction.sqrt();
        let intraday =
            point.abs().sqrt() * (1.0 - weight).sqrt() / (1.0 - overnight_fraction).sqrt();
        if point < 0.0 {
            require!(
                overnight.total_cmp(&intraday).is_ge(),
                "negative overnight variance at index {index}"
            );
            overnight * (1.0 - (intraday / overnight).powi(2)).sqrt()
        } else {
            overnight.hypot(intraday)
        }
    };
    let volatility = root / year_fraction.sqrt();
    require!(
        volatility.is_finite(),
        "nonfinite overnight volatility at index {index}"
    );
    Ok(volatility)
}

/// Estimates four QuantLib point volatilities using one fraction per OHLC bar.
/// All bars, including the first, have a valid estimate.
///
/// # Errors
/// Returns an error for mismatched lengths, nonpositive or nonfinite OHLC
/// prices or year fractions, or a nonfinite annualized estimate.
pub fn ohlc_point_volatility(
    prices: &[IntervalPrice],
    year_fractions: &[Real],
) -> QlResult<OhlcPointEstimates> {
    require!(
        prices.len() == year_fractions.len(),
        "OHLC and year-fraction lengths differ"
    );
    for (index, fraction) in year_fractions.iter().enumerate() {
        require!(
            fraction.is_finite() && *fraction > 0.0,
            "invalid year fraction at index {index}"
        );
    }
    ohlc_points(prices, |index| year_fractions[index])
}

/// Estimates four QuantLib point volatilities with a common year fraction.
/// All bars, including the first, have a valid estimate.
///
/// # Errors
/// Returns an error for a nonpositive or nonfinite fraction, nonpositive or
/// nonfinite OHLC prices, or a nonfinite annualized estimate.
pub fn ohlc_point_volatility_constant_fraction(
    prices: &[IntervalPrice],
    year_fraction: Real,
) -> QlResult<OhlcPointEstimates> {
    require!(
        year_fraction.is_finite() && year_fraction > 0.0,
        "year fraction must be positive and finite"
    );
    ohlc_points(prices, |_| year_fraction)
}

fn ohlc_points(
    prices: &[IntervalPrice],
    year_fraction: impl Fn(usize) -> Real,
) -> QlResult<OhlcPointEstimates> {
    let len = prices.len();
    let mut result = OhlcPointEstimates {
        simple_sigma: ChartSeries::zeroed(len, 0)?,
        parkinson_sigma: ChartSeries::zeroed(len, 0)?,
        garman_klass_sigma4: ChartSeries::zeroed(len, 0)?,
        garman_klass_sigma5: ChartSeries::zeroed(len, 0)?,
    };
    for (index, price) in prices.iter().copied().enumerate() {
        let [simple, parkinson, sigma4, sigma5] = ohlc_point_terms(price, index)?;
        let divisor = year_fraction(index).sqrt();
        for (point, series) in [
            (simple, &mut result.simple_sigma),
            (parkinson, &mut result.parkinson_sigma),
            (sigma4, &mut result.garman_klass_sigma4),
            (sigma5, &mut result.garman_klass_sigma5),
        ] {
            let volatility = point.abs().sqrt() / divisor;
            require!(
                volatility.is_finite(),
                "nonfinite OHLC point volatility at index {index}"
            );
            series.values[index] = volatility;
        }
    }
    Ok(result)
}

fn ohlc_point_terms(price: IntervalPrice, index: usize) -> QlResult<[Real; 4]> {
    let (open, high, low, close) = (price.open(), price.high(), price.low(), price.close());
    require!(
        [open, high, low, close]
            .iter()
            .all(|value| value.is_finite() && *value > 0.0),
        "invalid OHLC price at index {index}"
    );
    let u = log_ratio(high, open);
    let d = log_ratio(low, open);
    let c = log_ratio(close, open);
    let range = u - d;
    Ok([
        c * c,
        range * range / (4.0 * std::f64::consts::LN_2),
        0.511 * range * range - 0.019 * (c * (u + d) - 2.0 * u * d) - 0.383 * c * c,
        0.5 * range * range - (2.0 * std::f64::consts::LN_2 - 1.0) * c * c,
    ])
}

fn log_ratio(numerator: Real, denominator: Real) -> Real {
    let ratio = numerator / denominator;
    if ratio.is_finite() && ratio > 0.0 {
        ratio.ln()
    } else {
        numerator.ln() - denominator.ln()
    }
}

/// Estimates annualized local volatility from consecutive positive closes.
/// `year_fractions[i]` belongs to the interval ending at `i`; index zero is unused.
///
/// # Errors
/// Returns an error for mismatched lengths, invalid closes or used year fractions.
pub fn simple_local_volatility(close: &[Real], year_fractions: &[Real]) -> QlResult<ChartSeries> {
    require!(
        close.len() == year_fractions.len(),
        "close and year-fraction lengths differ"
    );
    for (index, year_fraction) in year_fractions.iter().enumerate().skip(1) {
        require!(
            year_fraction.is_finite() && *year_fraction > 0.0,
            "invalid year fraction at index {index}"
        );
    }
    local_volatility(close, |index| year_fractions[index])
}

/// Estimates annualized local volatility with one fraction for every interval.
///
/// # Errors
/// Returns an error for invalid closes or a nonpositive or nonfinite fraction.
pub fn simple_local_volatility_constant_fraction(
    close: &[Real],
    year_fraction: Real,
) -> QlResult<ChartSeries> {
    require!(
        year_fraction.is_finite() && year_fraction > 0.0,
        "year fraction must be positive and finite"
    );
    local_volatility(close, |_| year_fraction)
}

fn local_volatility(
    close: &[Real],
    year_fraction: impl Fn(usize) -> Real,
) -> QlResult<ChartSeries> {
    for (index, value) in close.iter().enumerate() {
        require!(
            value.is_finite() && *value > 0.0,
            "invalid close at index {index}"
        );
    }
    let mut result = ChartSeries::zeroed(close.len(), 1)?;
    for index in 1..close.len() {
        let ratio = close[index] / close[index - 1];
        let log_return = if ratio.is_finite() && ratio > 0.0 {
            ratio.ln()
        } else {
            close[index].ln() - close[index - 1].ln()
        };
        let volatility = log_return.abs() / year_fraction(index).sqrt();
        require!(
            volatility.is_finite(),
            "nonfinite local volatility at index {index}"
        );
        result.values[index] = volatility;
    }
    Ok(result)
}

/// Applies QuantLib's constant estimator to each preceding window of valid volatility.
/// The current input value is excluded from its estimate.
///
/// # Errors
/// Returns an error for a zero window, invalid valid-range metadata, or a
/// nonfinite value in the valid input suffix.
pub fn constant_volatility(input: &ChartSeries, window: usize) -> QlResult<ChartSeries> {
    require!(window > 0, "volatility window must be positive");
    let len = input.values.len();
    require!(input.first_valid <= len, "invalid first-valid index");
    for (index, value) in input.values.iter().enumerate().skip(input.first_valid) {
        require!(value.is_finite(), "invalid volatility at index {index}");
    }
    let first_valid = input.first_valid.saturating_add(window).min(len);
    let mut result = ChartSeries::zeroed(len, first_valid)?;
    let count = window as Real;
    for index in first_valid..len {
        let preceding = &input.values[index - window..index];
        let scale = preceding
            .iter()
            .fold(0.0_f64, |max, value| max.max(value.abs()));
        if scale == 0.0 {
            continue;
        }
        let mut mean = 0.0;
        let mut squared_deviations = 0.0;
        for (offset, value) in preceding.iter().enumerate() {
            let normalized = value / scale;
            let delta = normalized - mean;
            mean += delta / (offset + 1) as Real;
            squared_deviations += delta * (normalized - mean);
        }
        let variance = (squared_deviations / count).max(0.0);
        let normalized = (variance + mean * mean / (count + 1.0)).sqrt();
        let volatility = scale * normalized;
        require!(
            volatility.is_finite(),
            "nonfinite constant volatility at index {index}"
        );
        result.values[index] = volatility;
    }
    Ok(result)
}

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

    fn bar(open: Real, high: Real, low: Real, close: Real) -> IntervalPrice {
        IntervalPrice::new(open, high, low, close).unwrap()
    }

    #[test]
    fn ohlc_quantlib_fixture() {
        let result =
            ohlc_point_volatility_constant_fraction(&[bar(100.0, 110.0, 90.0, 105.0)], 1.0 / 252.0)
                .unwrap();
        for (series, expected) in [
            (&result.simple_sigma, 0.7745198449099887),
            (&result.parkinson_sigma, 1.9131168640323526),
            (&result.garman_klass_sigma4, 2.204975405342331),
            (&result.garman_klass_sigma5, 2.2004838300550182),
        ] {
            assert_eq!(series.first_valid, 0);
            assert_eq!(series.values.len(), 1);
            assert!((series.values[0] - expected).abs() < 1e-12);
        }
    }

    #[test]
    fn ohlc_scalar_indexed_parity_and_input_immutability() {
        let prices = [
            bar(100.0, 110.0, 90.0, 105.0),
            bar(105.0, 106.0, 95.0, 96.0),
        ];
        let original = prices;
        let fractions = [1.0 / 252.0; 2];
        let indexed = ohlc_point_volatility(&prices, &fractions).unwrap();
        let scalar = ohlc_point_volatility_constant_fraction(&prices, 1.0 / 252.0).unwrap();
        assert_eq!(indexed, scalar);
        assert_eq!(prices, original);
        assert_eq!(fractions, [1.0 / 252.0; 2]);
        assert!(indexed.garman_klass_sigma4.values[1] > 0.0);
    }

    #[test]
    fn ohlc_validates_all_bars_and_fractions() {
        let valid = bar(1.0, 2.0, 0.5, 1.5);
        assert!(ohlc_point_volatility(&[valid], &[]).is_err());
        assert!(ohlc_point_volatility(&[], &[1.0]).is_err());
        for invalid in [0.0, -1.0, Real::NAN, Real::INFINITY] {
            assert!(ohlc_point_volatility(&[valid], &[invalid]).is_err());
            assert!(ohlc_point_volatility_constant_fraction(&[], invalid).is_err());
        }
        for invalid in [
            bar(0.0, 1.0, 0.0, 0.5),
            bar(-1.0, -0.5, -2.0, -1.5),
            bar(1.0, 1.0, -1.0, 0.5),
        ] {
            assert!(ohlc_point_volatility(&[valid, invalid], &[1.0, 1.0]).is_err());
            assert!(ohlc_point_volatility_constant_fraction(&[invalid], 1.0).is_err());
        }
    }

    #[test]
    fn ohlc_empty_and_short_series_are_valid_from_zero() {
        let empty = ohlc_point_volatility(&[], &[]).unwrap();
        for series in [
            &empty.simple_sigma,
            &empty.parkinson_sigma,
            &empty.garman_klass_sigma4,
            &empty.garman_klass_sigma5,
        ] {
            assert_eq!(series.first_valid, 0);
            assert!(series.values.is_empty());
        }
        assert_eq!(
            empty,
            ohlc_point_volatility_constant_fraction(&[], 1.0).unwrap()
        );
        let flat =
            ohlc_point_volatility_constant_fraction(&[bar(1.0, 1.0, 1.0, 1.0)], 1.0).unwrap();
        for series in [
            flat.simple_sigma,
            flat.parkinson_sigma,
            flat.garman_klass_sigma4,
            flat.garman_klass_sigma5,
        ] {
            assert_eq!(series.first_valid, 0);
            assert_eq!(series.values, [0.0]);
        }
    }

    #[test]
    fn ohlc_extreme_finite_ratios_and_fractions() {
        let extreme = bar(Real::MIN_POSITIVE, Real::MAX, Real::MIN_POSITIVE, Real::MAX);
        let result = ohlc_point_volatility_constant_fraction(&[extreme], 1.0).unwrap();
        for series in [
            result.simple_sigma,
            result.parkinson_sigma,
            result.garman_klass_sigma4,
            result.garman_klass_sigma5,
        ] {
            assert!(series.values[0].is_finite());
            assert!(series.values[0] > 0.0);
        }
        let tiny_fraction =
            ohlc_point_volatility_constant_fraction(&[extreme], Real::MIN_POSITIVE).unwrap();
        assert!(tiny_fraction.simple_sigma.values[0].is_finite());
    }

    #[test]
    fn overnight_quantlib_fixture() {
        let prices = [
            bar(100.0, 100.0, 100.0, 100.0),
            bar(110.0, 120.0, 105.0, 115.0),
        ];
        let result = ohlc_overnight_volatility(&prices, &[Real::NAN, 1.0 / 252.0], 0.25).unwrap();
        for (series, expected) in [
            (&result.garman_klass_sigma1, 2.2159224836472786),
            (&result.garman_klass_sigma3, 1.8303355611439194),
            (&result.garman_klass_sigma6, 1.6795672145926133),
        ] {
            assert_eq!(series.first_valid, 1);
            assert_eq!(series.values.len(), 2);
            assert_eq!(series.values[0], 0.0);
            assert!((series.values[1] - expected).abs() < 1e-12);
        }
    }

    #[test]
    fn overnight_scalar_indexed_parity_and_immutability() {
        let prices = [
            bar(100.0, 100.0, 100.0, 100.0),
            bar(110.0, 120.0, 105.0, 115.0),
            bar(112.0, 118.0, 108.0, 110.0),
        ];
        let original = prices;
        let fractions = [0.0, 1.0 / 252.0, 1.0 / 252.0];
        let indexed = ohlc_overnight_volatility(&prices, &fractions, 0.25).unwrap();
        let scalar =
            ohlc_overnight_volatility_constant_fraction(&prices, 1.0 / 252.0, 0.25).unwrap();
        assert_eq!(indexed, scalar);
        assert_eq!(prices, original);
        assert_eq!(fractions, [0.0, 1.0 / 252.0, 1.0 / 252.0]);
        assert!(indexed.garman_klass_sigma1.values[2] > 0.0);
        let differing =
            ohlc_overnight_volatility(&prices, &[0.0, 1.0 / 252.0, 1.0 / 365.0], 0.25).unwrap();
        assert!(differing.garman_klass_sigma3.values[2] > indexed.garman_klass_sigma3.values[2]);
    }

    #[test]
    fn overnight_validates_prices_and_fractions() {
        let valid = bar(1.0, 2.0, 0.5, 1.5);
        assert!(ohlc_overnight_volatility(&[valid], &[], 0.25).is_err());
        for invalid in [0.0, 1.0, -0.5, Real::NAN, Real::INFINITY] {
            assert!(ohlc_overnight_volatility(&[], &[], invalid).is_err());
            assert!(ohlc_overnight_volatility_constant_fraction(&[], 1.0, invalid).is_err());
        }
        for invalid in [0.0, -1.0, Real::NAN, Real::INFINITY] {
            assert!(ohlc_overnight_volatility(&[valid, valid], &[0.0, invalid], 0.25).is_err());
            assert!(ohlc_overnight_volatility_constant_fraction(&[], invalid, 0.25).is_err());
        }
        for invalid in [bar(0.0, 1.0, 0.0, 0.5), bar(-1.0, -0.5, -2.0, -1.5)] {
            assert!(ohlc_overnight_volatility(&[invalid], &[Real::NAN], 0.25).is_err());
            assert!(ohlc_overnight_volatility(&[valid, invalid], &[0.0, 1.0], 0.25).is_err());
        }
        assert!(overnight_volatility(0.0, -1.0, 0.5, 0.25, 1.0, 1).is_err());
    }

    #[test]
    fn overnight_short_series_have_zero_warmup() {
        let empty = ohlc_overnight_volatility(&[], &[], 0.25).unwrap();
        let single =
            ohlc_overnight_volatility(&[bar(1.0, 1.0, 1.0, 1.0)], &[Real::NAN], 0.25).unwrap();
        for series in [
            &empty.garman_klass_sigma1,
            &empty.garman_klass_sigma3,
            &empty.garman_klass_sigma6,
        ] {
            assert_eq!(series.first_valid, 0);
            assert!(series.values.is_empty());
        }
        for series in [
            &single.garman_klass_sigma1,
            &single.garman_klass_sigma3,
            &single.garman_klass_sigma6,
        ] {
            assert_eq!(series.first_valid, 1);
            assert_eq!(series.values, [0.0]);
        }
    }

    #[test]
    fn overnight_extreme_finite_inputs_avoid_intermediate_overflow() {
        let prices = [
            bar(
                Real::MIN_POSITIVE,
                Real::MIN_POSITIVE,
                Real::MIN_POSITIVE,
                Real::MIN_POSITIVE,
            ),
            bar(Real::MAX, Real::MAX, Real::MIN_POSITIVE, Real::MAX),
        ];
        let result =
            ohlc_overnight_volatility_constant_fraction(&prices, 1.0, Real::MIN_POSITIVE).unwrap();
        for series in [
            result.garman_klass_sigma1,
            result.garman_klass_sigma3,
            result.garman_klass_sigma6,
        ] {
            assert!(series.values[1].is_finite());
            assert!(series.values[1] > 1e150);
        }
        assert!(
            ohlc_overnight_volatility_constant_fraction(
                &prices,
                Real::MIN_POSITIVE,
                Real::MIN_POSITIVE
            )
            .is_err()
        );
    }

    fn close_fixture() -> [Real; 3] {
        [100.0, 110.0, 99.0]
    }

    #[test]
    fn quantlib_fixture_and_composition() {
        let close = close_fixture();
        let indexed = simple_local_volatility(&close, &[0.0, 1.0 / 252.0, 1.0 / 252.0]).unwrap();
        let scalar = simple_local_volatility_constant_fraction(&close, 1.0 / 252.0).unwrap();
        assert_eq!(indexed, scalar);
        assert_eq!(indexed.first_valid, 1);
        assert_eq!(indexed.values[0], 0.0);
        assert!((indexed.values[1] - 1.5130021990505673).abs() < 1e-12);
        assert!((indexed.values[2] - 1.6725463346168112).abs() < 1e-12);
        let constant = constant_volatility(&indexed, 1).unwrap();
        assert_eq!(constant.first_valid, 2);
        assert_eq!(constant.values[0..2], [0.0, 0.0]);
        assert!((constant.values[2] - 1.0698541148988145).abs() < 1e-12);
    }

    #[test]
    fn local_validates_inputs_even_without_an_interval() {
        assert!(simple_local_volatility(&[100.0], &[]).is_err());
        for close in [0.0, -1.0, Real::NAN, Real::INFINITY] {
            assert!(simple_local_volatility_constant_fraction(&[close], 1.0).is_err());
        }
        for fraction in [0.0, -1.0, Real::NAN, Real::INFINITY] {
            assert!(simple_local_volatility_constant_fraction(&[], fraction).is_err());
            assert!(simple_local_volatility(&[100.0, 101.0], &[0.0, fraction]).is_err());
        }
        assert_eq!(simple_local_volatility(&[], &[]).unwrap().first_valid, 0);
        assert_eq!(
            simple_local_volatility(&[100.0], &[Real::NAN])
                .unwrap()
                .values,
            [0.0]
        );
    }

    #[test]
    fn short_series_are_aligned_and_zeroed() {
        let local = simple_local_volatility_constant_fraction(&[100.0], 1.0).unwrap();
        assert_eq!(local.first_valid, 1);
        assert_eq!(local.values, [0.0]);
        let constant = constant_volatility(&local, 2).unwrap();
        assert_eq!(constant.first_valid, 1);
        assert_eq!(constant.values, [0.0]);
        let empty = constant_volatility(
            &ChartSeries {
                values: vec![],
                first_valid: 0,
            },
            1,
        )
        .unwrap();
        assert_eq!(empty.first_valid, 0);
        assert!(empty.values.is_empty());
    }

    #[test]
    fn constant_validates_only_the_valid_suffix() {
        let input = ChartSeries {
            values: vec![Real::NAN, -1.0, 2.0, 4.0, 9.0],
            first_valid: 2,
        };
        let result = constant_volatility(&input, 2).unwrap();
        assert_eq!(result.first_valid, 4);
        assert!(result.values[..4].iter().all(|value| *value == 0.0));
        assert!((result.values[4] - 2.0).abs() < 1e-12);
        assert!(constant_volatility(&input, 0).is_err());
        assert!(
            constant_volatility(
                &ChartSeries {
                    values: vec![1.0],
                    first_valid: 2
                },
                1
            )
            .is_err()
        );
        for invalid in [Real::NAN, Real::INFINITY, Real::NEG_INFINITY] {
            assert!(
                constant_volatility(
                    &ChartSeries {
                        values: vec![invalid],
                        first_valid: 0
                    },
                    2
                )
                .is_err()
            );
        }
    }

    #[test]
    fn constant_accepts_signed_values_like_quantlib() {
        let input = ChartSeries {
            values: vec![-1.0, 2.0, 9.0],
            first_valid: 0,
        };
        let result = constant_volatility(&input, 2).unwrap();
        assert_eq!(result.first_valid, 2);
        assert!((result.values[2] - (7.0_f64 / 3.0).sqrt()).abs() < 1e-12);
        let extreme = ChartSeries {
            values: vec![-Real::MAX, Real::MAX, 0.0],
            first_valid: 0,
        };
        assert_eq!(
            constant_volatility(&extreme, 2).unwrap().values[2],
            Real::MAX
        );
    }

    #[test]
    fn finite_extremes_avoid_intermediate_overflow() {
        let local =
            simple_local_volatility_constant_fraction(&[Real::MIN_POSITIVE, Real::MAX], 1.0)
                .unwrap();
        assert!(local.values[1].is_finite());
        assert!(local.values[1] > 1400.0);
        let reverse =
            simple_local_volatility_constant_fraction(&[Real::MAX, Real::MIN_POSITIVE], 1.0)
                .unwrap();
        assert!((local.values[1] - reverse.values[1]).abs() < 1e-12);
        let input = ChartSeries {
            values: vec![Real::MAX, Real::MAX, 0.0],
            first_valid: 0,
        };
        let result = constant_volatility(&input, 2).unwrap();
        assert!(result.values[2].is_finite());
        assert!((result.values[2] / Real::MAX - 1.0 / 3.0_f64.sqrt()).abs() < 1e-12);
    }
}