Skip to main content

nautilus_model/data/
greeks.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Option *Greeks* data structures (delta, gamma, theta, vega, rho) used throughout the platform.
17
18use std::{
19    any::Any,
20    fmt::Display,
21    ops::{Add, Deref, Mul},
22    sync::Arc,
23};
24
25use implied_vol::{DefaultSpecialFn, ImpliedBlackVolatility, SpecialFn};
26use nautilus_core::{
27    UnixNanos,
28    correctness::{CorrectnessResult, check_equal_usize, check_predicate_true},
29    datetime::unix_nanos_to_iso8601,
30    math::{quadratic_interpolation, too_close_for_interpolation},
31};
32use serde::{Deserialize, Serialize};
33
34use crate::{
35    data::{
36        CustomDataTrait, HasTsInit,
37        black_scholes::{
38            REFINEMENT_VOL_MAX, REFINEMENT_VOL_MIN, compute_greeks, compute_iv_and_greeks,
39        },
40    },
41    identifiers::InstrumentId,
42};
43
44const FRAC_SQRT_2_PI: f64 = f64::from_bits(0x3fd9_8845_33d4_3651);
45/// used to convert theta to per-calendar-day change when building `BlackScholesGreeksResult`.
46const THETA_DAILY_FACTOR: f64 = 1.0 / 365.0;
47/// Scale for vega to express as absolute percent change when building `BlackScholesGreeksResult`.
48const VEGA_PERCENT_FACTOR: f64 = 0.01;
49const RHO_PERCENT_FACTOR: f64 = 0.01;
50const PRICE_RELATIVE_TOLERANCE: f64 = 1e-4;
51
52/// An unsupported or invalid local option valuation.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
54pub enum OptionValuationError {
55    #[error("Invalid option valuation input: {0}")]
56    InvalidInput(&'static str),
57    #[error("No finite positive implied volatility for the option price")]
58    ImpliedVolatilityUnavailable,
59    #[error("Nonfinite or inconsistent option valuation result")]
60    InvalidResult,
61    #[error("Option {0} has expired")]
62    Expired(InstrumentId),
63    #[error("Local valuation of option spread {0} is unsupported")]
64    UnsupportedSpread(InstrumentId),
65}
66
67/// Core option Greek sensitivity values (the 5 standard sensitivities).
68/// Designed as a composable building block embedded in all Greeks-carrying types.
69#[repr(C)]
70#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
71#[cfg_attr(
72    feature = "python",
73    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
74)]
75#[cfg_attr(
76    feature = "python",
77    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
78)]
79pub struct OptionGreekValues {
80    pub delta: f64,
81    pub gamma: f64,
82    pub vega: f64,
83    pub theta: f64,
84    pub rho: f64,
85}
86
87impl Add for OptionGreekValues {
88    type Output = Self;
89
90    fn add(self, rhs: Self) -> Self {
91        Self {
92            delta: self.delta + rhs.delta,
93            gamma: self.gamma + rhs.gamma,
94            vega: self.vega + rhs.vega,
95            theta: self.theta + rhs.theta,
96            rho: self.rho + rhs.rho,
97        }
98    }
99}
100
101impl Mul<f64> for OptionGreekValues {
102    type Output = Self;
103
104    fn mul(self, scalar: f64) -> Self {
105        Self {
106            delta: self.delta * scalar,
107            gamma: self.gamma * scalar,
108            vega: self.vega * scalar,
109            theta: self.theta * scalar,
110            rho: self.rho * scalar,
111        }
112    }
113}
114
115impl Mul<OptionGreekValues> for f64 {
116    type Output = OptionGreekValues;
117
118    fn mul(self, greeks: OptionGreekValues) -> OptionGreekValues {
119        greeks * self
120    }
121}
122
123impl Display for OptionGreekValues {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        write!(
126            f,
127            "OptionGreekValues(delta={:.4}, gamma={:.4}, vega={:.4}, theta={:.4}, rho={:.4})",
128            self.delta, self.gamma, self.vega, self.theta, self.rho
129        )
130    }
131}
132
133/// Trait for types carrying Greek sensitivity values.
134pub trait HasGreeks {
135    fn greeks(&self) -> OptionGreekValues;
136}
137
138#[inline(always)]
139fn norm_pdf(x: f64) -> f64 {
140    FRAC_SQRT_2_PI * (-0.5 * x * x).exp()
141}
142
143/// Result structure for Black-Scholes Greeks calculations.
144///
145/// This is a separate f64 struct (not a type alias) for Python compatibility.
146/// Rho is per percentage point and holds carry fixed in the unchecked functions.
147/// Checked functions take the carry rate sensitivity explicitly.
148#[repr(C)]
149#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
150#[cfg_attr(
151    feature = "python",
152    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
153)]
154#[cfg_attr(
155    feature = "python",
156    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
157)]
158pub struct BlackScholesGreeksResult {
159    pub price: f64,
160    pub vol: f64,
161    pub delta: f64,
162    pub gamma: f64,
163    pub vega: f64,
164    pub theta: f64,
165    pub itm_prob: f64,
166    pub rho: f64,
167}
168
169// Standardized Generalized Black-Scholes Greeks implementation
170// dS_t = S_t * (b * dt + vol * dW_t) (stock)
171// dC_t = r * C_t * dt (cash numeraire)
172#[must_use]
173pub fn black_scholes_greeks_exact(
174    s: f64,
175    r: f64,
176    b: f64,
177    vol: f64,
178    is_call: bool,
179    k: f64,
180    t: f64,
181) -> BlackScholesGreeksResult {
182    let phi = if is_call { 1.0 } else { -1.0 };
183    let sqrt_t = t.sqrt();
184    let scaled_vol = vol * sqrt_t;
185
186    // d1 and d2 calculations
187    let d1 = ((s / k).ln() + (b + 0.5 * vol.powi(2)) * t) / scaled_vol;
188    let d2 = d1 - scaled_vol;
189
190    // Probabilities and PDF
191    let cdf_phi_d1 = DefaultSpecialFn::norm_cdf(phi * d1);
192    let cdf_phi_d2 = DefaultSpecialFn::norm_cdf(phi * d2);
193    let pdf_d1 = norm_pdf(d1);
194
195    // Discounting factors
196    let df_b = ((b - r) * t).exp();
197    let df_r = (-r * t).exp();
198
199    // Price and common Greeks
200    let price = phi * (s * df_b * cdf_phi_d1 - k * df_r * cdf_phi_d2);
201    let delta = phi * df_b * cdf_phi_d1;
202    let gamma = (df_b * pdf_d1) / (s * scaled_vol);
203    let vega = s * df_b * sqrt_t * pdf_d1 * VEGA_PERCENT_FACTOR;
204
205    // Decay due to volatility, Drift/Cost of Carry component, Interest rate component on strike
206    let theta_v = -(s * df_b * pdf_d1 * vol) / (2.0 * sqrt_t);
207    let theta_b = -phi * (b - r) * s * df_b * cdf_phi_d1;
208    let theta_r = -phi * r * k * df_r * cdf_phi_d2;
209    let theta = (theta_v + theta_b + theta_r) * THETA_DAILY_FACTOR;
210
211    BlackScholesGreeksResult {
212        price,
213        vol,
214        delta,
215        gamma,
216        vega,
217        theta,
218        itm_prob: cdf_phi_d2,
219        rho: -t * price * RHO_PERCENT_FACTOR,
220    }
221}
222
223#[must_use]
224pub fn imply_vol(s: f64, r: f64, b: f64, is_call: bool, k: f64, t: f64, price: f64) -> f64 {
225    let forward = s * (b * t).exp();
226    let forward_price = price * (r * t).exp();
227
228    ImpliedBlackVolatility::builder()
229        .option_price(forward_price)
230        .forward(forward)
231        .strike(k)
232        .expiry(t)
233        .is_call(is_call)
234        .build()
235        .and_then(|iv| iv.calculate::<DefaultSpecialFn>())
236        .unwrap_or(0.0)
237}
238
239/// Computes Black-Scholes greeks using the fast `compute_greeks` implementation.
240/// This function uses `compute_greeks` from `black_scholes.rs` which is optimized for performance.
241#[must_use]
242pub fn black_scholes_greeks(
243    s: f64,
244    r: f64,
245    b: f64,
246    vol: f64,
247    is_call: bool,
248    k: f64,
249    t: f64,
250) -> BlackScholesGreeksResult {
251    // Use f32 for performance, then cast to f64 when applying multiplier
252    let greeks = compute_greeks::<f32>(
253        s as f32, k as f32, t as f32, r as f32, b as f32, vol as f32, is_call,
254    );
255
256    BlackScholesGreeksResult {
257        price: f64::from(greeks.price),
258        vol,
259        delta: f64::from(greeks.delta),
260        gamma: f64::from(greeks.gamma),
261        vega: f64::from(greeks.vega) * VEGA_PERCENT_FACTOR,
262        theta: f64::from(greeks.theta) * THETA_DAILY_FACTOR,
263        itm_prob: f64::from(greeks.itm_prob),
264        rho: -t * f64::from(greeks.price) * RHO_PERCENT_FACTOR,
265    }
266}
267
268/// Computes implied volatility and greeks using the fast implementations.
269/// This function uses `compute_greeks` after implying volatility.
270#[must_use]
271pub fn imply_vol_and_greeks(
272    s: f64,
273    r: f64,
274    b: f64,
275    is_call: bool,
276    k: f64,
277    t: f64,
278    price: f64,
279) -> BlackScholesGreeksResult {
280    let vol = imply_vol(s, r, b, is_call, k, t, price);
281    // Handle case when imply_vol fails and returns 0.0 or very small value
282    // Using a very small vol (1e-8) instead of 0.0 prevents division by zero in greeks calculations
283    // This ensures greeks remain finite even when imply_vol fails
284    let safe_vol = if vol < 1e-8 { 1e-8 } else { vol };
285    black_scholes_greeks(s, r, b, safe_vol, is_call, k, t)
286}
287
288/// Refines implied volatility using an initial guess and computes greeks.
289/// This function uses `compute_iv_and_greeks` which performs a Halley iteration
290/// to refine the volatility estimate from an initial guess.
291#[expect(clippy::too_many_arguments)]
292#[must_use]
293pub fn refine_vol_and_greeks(
294    s: f64,
295    r: f64,
296    b: f64,
297    is_call: bool,
298    k: f64,
299    t: f64,
300    target_price: f64,
301    initial_vol: f64,
302) -> BlackScholesGreeksResult {
303    // Use f32 for performance, then cast to f64 when applying multiplier
304    let greeks = compute_iv_and_greeks::<f32>(
305        target_price as f32,
306        s as f32,
307        k as f32,
308        t as f32,
309        r as f32,
310        b as f32,
311        is_call,
312        initial_vol as f32,
313    );
314
315    BlackScholesGreeksResult {
316        price: f64::from(greeks.price),
317        vol: f64::from(greeks.vol),
318        delta: f64::from(greeks.delta),
319        gamma: f64::from(greeks.gamma),
320        vega: f64::from(greeks.vega) * VEGA_PERCENT_FACTOR,
321        theta: f64::from(greeks.theta) * THETA_DAILY_FACTOR,
322        itm_prob: f64::from(greeks.itm_prob),
323        rho: -t * f64::from(greeks.price) * RHO_PERCENT_FACTOR,
324    }
325}
326
327/// Computes validated Greeks with an explicit sensitivity of carry to the interest rate.
328///
329/// `db_dr` is zero for fixed carry and one for carry defined as `r - q`, even when `r == q`.
330/// Rho measures the price change for a one percentage point rate move.
331/// The exact implementation is used when the fast result is nonfinite or inconsistent.
332///
333/// # Errors
334///
335/// Returns an error if:
336/// - Model inputs are invalid.
337/// - Valuation results are nonfinite or inconsistent.
338#[expect(clippy::too_many_arguments)]
339pub fn black_scholes_greeks_checked(
340    s: f64,
341    r: f64,
342    b: f64,
343    vol: f64,
344    is_call: bool,
345    k: f64,
346    t: f64,
347    db_dr: f64,
348) -> Result<BlackScholesGreeksResult, OptionValuationError> {
349    check_option_inputs(s, r, b, vol, k, t)?;
350    let result = black_scholes_greeks(s, r, b, vol, is_call, k, t);
351    match apply_rate_sensitivity(result, s, r, is_call, k, t, db_dr) {
352        Err(OptionValuationError::InvalidResult) => {
353            let result = black_scholes_greeks_exact(s, r, b, vol, is_call, k, t);
354            apply_rate_sensitivity(result, s, r, is_call, k, t, db_dr)
355        }
356        result => result,
357    }
358}
359
360/// Solves implied volatility and computes validated Greeks with explicit carry rate sensitivity.
361///
362/// A refinement seed is used only when it produces an interior volatility and reprices the
363/// premium within 0.01 percent, otherwise the full implied-volatility solver is used.
364/// The exact implementation is used when the fast kernel cannot reprice the solved premium
365/// within that tolerance. Carry rate sensitivity and rho units follow [`black_scholes_greeks_checked`].
366///
367/// # Errors
368///
369/// Returns an error if:
370/// - Model inputs or the premium are invalid.
371/// - The premium has no finite positive implied volatility.
372/// - Results are nonfinite, inconsistent, or fail the 0.01 percent repricing tolerance.
373#[expect(clippy::too_many_arguments)]
374pub fn imply_vol_and_greeks_checked(
375    s: f64,
376    r: f64,
377    b: f64,
378    is_call: bool,
379    k: f64,
380    t: f64,
381    price: f64,
382    db_dr: f64,
383    initial_vol: Option<f64>,
384) -> Result<BlackScholesGreeksResult, OptionValuationError> {
385    check_option_inputs(s, r, b, 1.0, k, t)?;
386
387    if !price.is_finite() || price <= 0.0 {
388        return Err(OptionValuationError::InvalidInput("option price"));
389    }
390
391    let forward = s * (b * t).exp();
392    let forward_price = price * (r * t).exp();
393
394    let intrinsic = if is_call {
395        (forward - k).max(0.0)
396    } else {
397        (k - forward).max(0.0)
398    };
399
400    let upper = if is_call { forward } else { k };
401    if !forward.is_finite()
402        || !forward_price.is_finite()
403        || forward_price <= intrinsic
404        || forward_price >= upper
405    {
406        return Err(OptionValuationError::ImpliedVolatilityUnavailable);
407    }
408
409    let price_tolerance = price * PRICE_RELATIVE_TOLERANCE;
410
411    if let Some(seed) = initial_vol {
412        check_option_inputs(s, r, b, seed, k, t)?;
413        let result = refine_vol_and_greeks(s, r, b, is_call, k, t, price, seed);
414        if result.vol > REFINEMENT_VOL_MIN
415            && result.vol < REFINEMENT_VOL_MAX
416            && (result.price - price).abs() <= price_tolerance
417        {
418            return apply_rate_sensitivity(result, s, r, is_call, k, t, db_dr);
419        }
420    }
421
422    let vol = imply_vol_checked(s, r, b, is_call, k, t, price)?;
423    let mut result = black_scholes_greeks_checked(s, r, b, vol, is_call, k, t, db_dr)?;
424    if (result.price - price).abs() > price_tolerance {
425        result = apply_rate_sensitivity(
426            black_scholes_greeks_exact(s, r, b, vol, is_call, k, t),
427            s,
428            r,
429            is_call,
430            k,
431            t,
432            db_dr,
433        )?;
434    }
435
436    if (result.price - price).abs() > price_tolerance {
437        return Err(OptionValuationError::InvalidResult);
438    }
439
440    Ok(result)
441}
442
443/// Solves implied volatility without fast-kernel repricing.
444///
445/// # Errors
446///
447/// Returns an error if:
448/// - Model inputs are invalid.
449/// - The premium has no finite positive implied volatility.
450pub(crate) fn imply_vol_checked(
451    s: f64,
452    r: f64,
453    b: f64,
454    is_call: bool,
455    k: f64,
456    t: f64,
457    price: f64,
458) -> Result<f64, OptionValuationError> {
459    let vol = imply_vol(s, r, b, is_call, k, t, price);
460    if !vol.is_finite() || vol <= 0.0 {
461        return Err(OptionValuationError::ImpliedVolatilityUnavailable);
462    }
463
464    Ok(vol)
465}
466
467/// Checks model inputs against the fast pricing kernel's numeric domain.
468///
469/// # Errors
470///
471/// Returns an error if:
472/// - Rates are not finite in the pricing kernel's precision.
473/// - Spot, strike, time, or volatility are not finite and positive in that precision.
474pub fn check_option_inputs(
475    s: f64,
476    r: f64,
477    b: f64,
478    vol: f64,
479    k: f64,
480    t: f64,
481) -> Result<(), OptionValuationError> {
482    for (name, value) in [
483        ("underlying price", s),
484        ("strike", k),
485        ("time to expiry", t),
486        ("volatility", vol),
487    ] {
488        let kernel_value = value as f32;
489        if !value.is_finite() || value <= 0.0 || !kernel_value.is_finite() || kernel_value <= 0.0 {
490            return Err(OptionValuationError::InvalidInput(name));
491        }
492    }
493
494    for (name, value) in [("interest rate", r), ("cost of carry", b)] {
495        if !(value as f32).is_finite() {
496            return Err(OptionValuationError::InvalidInput(name));
497        }
498    }
499
500    Ok(())
501}
502
503fn apply_rate_sensitivity(
504    mut result: BlackScholesGreeksResult,
505    s: f64,
506    r: f64,
507    is_call: bool,
508    k: f64,
509    t: f64,
510    db_dr: f64,
511) -> Result<BlackScholesGreeksResult, OptionValuationError> {
512    if !db_dr.is_finite() {
513        return Err(OptionValuationError::InvalidInput("carry rate sensitivity"));
514    }
515
516    if db_dr != 0.0 {
517        let phi = if is_call { 1.0 } else { -1.0 };
518        // The strike term avoids subtracting spot delta and price for deep ITM options
519        result.rho = t
520            * ((db_dr - 1.0) * s * result.delta + phi * k * (-r * t).exp() * result.itm_prob)
521            * RHO_PERCENT_FACTOR;
522    }
523
524    check_valuation_result(result)
525}
526
527fn check_valuation_result(
528    result: BlackScholesGreeksResult,
529) -> Result<BlackScholesGreeksResult, OptionValuationError> {
530    if [
531        result.price,
532        result.vol,
533        result.delta,
534        result.gamma,
535        result.vega,
536        result.theta,
537        result.rho,
538        result.itm_prob,
539    ]
540    .iter()
541    .any(|value| !value.is_finite())
542        || result.price < 0.0
543        || result.gamma < 0.0
544        || result.vega < 0.0
545        || !(0.0..=1.0).contains(&result.itm_prob)
546    {
547        return Err(OptionValuationError::InvalidResult);
548    }
549
550    Ok(result)
551}
552
553#[repr(C)]
554#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
555#[cfg_attr(
556    feature = "python",
557    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
558)]
559#[cfg_attr(
560    feature = "python",
561    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
562)]
563pub struct GreeksData {
564    pub instrument_id: InstrumentId,
565    pub is_call: bool,
566    pub strike: f64,
567    pub expiry: i32,
568    pub expiry_in_days: i32,
569    pub expiry_in_years: f64,
570    pub multiplier: f64,
571    pub quantity: f64,
572    pub underlying_price: f64,
573    pub interest_rate: f64,
574    pub cost_of_carry: f64,
575    pub vol: f64,
576    pub pnl: f64,
577    pub price: f64,
578    /// Core Greek sensitivity values (delta, gamma, vega, theta, rho).
579    pub greeks: OptionGreekValues,
580    // in the money probability, P(phi * S_T > phi * K), phi = 1 if is_call else -1
581    pub itm_prob: f64,
582    pub ts_event: UnixNanos,
583    pub ts_init: UnixNanos,
584}
585
586impl GreeksData {
587    #[expect(clippy::too_many_arguments)]
588    #[must_use]
589    pub fn new(
590        instrument_id: InstrumentId,
591        is_call: bool,
592        strike: f64,
593        expiry: i32,
594        expiry_in_days: i32,
595        expiry_in_years: f64,
596        multiplier: f64,
597        quantity: f64,
598        underlying_price: f64,
599        interest_rate: f64,
600        cost_of_carry: f64,
601        vol: f64,
602        pnl: f64,
603        price: f64,
604        greeks: OptionGreekValues,
605        itm_prob: f64,
606        ts_event: UnixNanos,
607        ts_init: UnixNanos,
608    ) -> Self {
609        Self {
610            instrument_id,
611            is_call,
612            strike,
613            expiry,
614            expiry_in_days,
615            expiry_in_years,
616            multiplier,
617            quantity,
618            underlying_price,
619            interest_rate,
620            cost_of_carry,
621            vol,
622            pnl,
623            price,
624            greeks,
625            itm_prob,
626            ts_event,
627            ts_init,
628        }
629    }
630
631    #[must_use]
632    pub fn from_delta(
633        instrument_id: InstrumentId,
634        delta: f64,
635        multiplier: f64,
636        ts_event: UnixNanos,
637    ) -> Self {
638        Self {
639            instrument_id,
640            is_call: true,
641            strike: 0.0,
642            expiry: 0,
643            expiry_in_days: 0,
644            expiry_in_years: 0.0,
645            multiplier,
646            quantity: 1.0,
647            underlying_price: 0.0,
648            interest_rate: 0.0,
649            cost_of_carry: 0.0,
650            vol: 0.0,
651            pnl: 0.0,
652            price: 0.0,
653            greeks: OptionGreekValues {
654                delta,
655                ..Default::default()
656            },
657            itm_prob: 0.0,
658            ts_event,
659            ts_init: ts_event,
660        }
661    }
662
663    /// Returns portfolio values with `pnl`, `price`, and all Greeks scaled by the contract multiplier.
664    ///
665    /// Preserves both timestamps and leaves position quantity scaling to the caller.
666    #[must_use]
667    pub fn to_portfolio_greeks(&self) -> PortfolioGreeks {
668        PortfolioGreeks {
669            pnl: self.pnl * self.multiplier,
670            price: self.price * self.multiplier,
671            greeks: self.greeks * self.multiplier,
672            ts_event: self.ts_event,
673            ts_init: self.ts_init,
674        }
675    }
676}
677
678impl Deref for GreeksData {
679    type Target = OptionGreekValues;
680    fn deref(&self) -> &Self::Target {
681        &self.greeks
682    }
683}
684
685impl HasGreeks for GreeksData {
686    fn greeks(&self) -> OptionGreekValues {
687        self.greeks
688    }
689}
690
691impl Default for GreeksData {
692    fn default() -> Self {
693        Self {
694            instrument_id: InstrumentId::from("ES.GLBX"),
695            is_call: true,
696            strike: 0.0,
697            expiry: 0,
698            expiry_in_days: 0,
699            expiry_in_years: 0.0,
700            multiplier: 0.0,
701            quantity: 0.0,
702            underlying_price: 0.0,
703            interest_rate: 0.0,
704            cost_of_carry: 0.0,
705            vol: 0.0,
706            pnl: 0.0,
707            price: 0.0,
708            greeks: OptionGreekValues::default(),
709            itm_prob: 0.0,
710            ts_event: UnixNanos::default(),
711            ts_init: UnixNanos::default(),
712        }
713    }
714}
715
716impl Display for GreeksData {
717    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718        write!(
719            f,
720            "GreeksData(instrument_id={}, expiry={}, itm_prob={:.2}%, vol={:.2}%, pnl={:.2}, price={:.2}, delta={:.2}, gamma={:.2}, vega={:.2}, theta={:.2}, quantity={}, ts_event={}, ts_init={})",
721            self.instrument_id,
722            self.expiry,
723            self.itm_prob * 100.0,
724            self.vol * 100.0,
725            self.pnl,
726            self.price,
727            self.greeks.delta,
728            self.greeks.gamma,
729            self.greeks.vega,
730            self.greeks.theta,
731            self.quantity,
732            unix_nanos_to_iso8601(self.ts_event),
733            unix_nanos_to_iso8601(self.ts_init)
734        )
735    }
736}
737
738/// Scales values by quantity without applying the contract multiplier.
739impl Mul<&GreeksData> for f64 {
740    type Output = GreeksData;
741
742    fn mul(self, g: &GreeksData) -> GreeksData {
743        GreeksData {
744            instrument_id: g.instrument_id,
745            is_call: g.is_call,
746            strike: g.strike,
747            expiry: g.expiry,
748            expiry_in_days: g.expiry_in_days,
749            expiry_in_years: g.expiry_in_years,
750            multiplier: g.multiplier,
751            quantity: g.quantity,
752            underlying_price: g.underlying_price,
753            interest_rate: g.interest_rate,
754            cost_of_carry: g.cost_of_carry,
755            vol: g.vol,
756            pnl: self * g.pnl,
757            price: self * g.price,
758            greeks: g.greeks * self,
759            itm_prob: g.itm_prob,
760            ts_event: g.ts_event,
761            ts_init: g.ts_init,
762        }
763    }
764}
765
766impl HasTsInit for GreeksData {
767    fn ts_init(&self) -> UnixNanos {
768        self.ts_init
769    }
770}
771
772#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
773#[cfg_attr(
774    feature = "python",
775    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
776)]
777#[cfg_attr(
778    feature = "python",
779    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
780)]
781pub struct PortfolioGreeks {
782    pub pnl: f64,
783    pub price: f64,
784    pub greeks: OptionGreekValues,
785    pub ts_event: UnixNanos,
786    pub ts_init: UnixNanos,
787}
788
789impl PortfolioGreeks {
790    #[expect(clippy::too_many_arguments)]
791    #[must_use]
792    pub fn new(
793        pnl: f64,
794        price: f64,
795        delta: f64,
796        gamma: f64,
797        vega: f64,
798        theta: f64,
799        ts_event: UnixNanos,
800        ts_init: UnixNanos,
801    ) -> Self {
802        Self {
803            pnl,
804            price,
805            greeks: OptionGreekValues {
806                delta,
807                gamma,
808                vega,
809                theta,
810                rho: 0.0,
811            },
812            ts_event,
813            ts_init,
814        }
815    }
816}
817
818impl Deref for PortfolioGreeks {
819    type Target = OptionGreekValues;
820    fn deref(&self) -> &Self::Target {
821        &self.greeks
822    }
823}
824
825impl Default for PortfolioGreeks {
826    fn default() -> Self {
827        Self {
828            pnl: 0.0,
829            price: 0.0,
830            greeks: OptionGreekValues::default(),
831            ts_event: UnixNanos::default(),
832            ts_init: UnixNanos::default(),
833        }
834    }
835}
836
837impl Display for PortfolioGreeks {
838    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
839        write!(
840            f,
841            "PortfolioGreeks(pnl={:.2}, price={:.2}, delta={:.2}, gamma={:.2}, vega={:.2}, theta={:.2}, ts_event={}, ts_init={})",
842            self.pnl,
843            self.price,
844            self.greeks.delta,
845            self.greeks.gamma,
846            self.greeks.vega,
847            self.greeks.theta,
848            unix_nanos_to_iso8601(self.ts_event),
849            unix_nanos_to_iso8601(self.ts_init)
850        )
851    }
852}
853
854impl Add for PortfolioGreeks {
855    type Output = Self;
856
857    fn add(self, other: Self) -> Self {
858        Self {
859            pnl: self.pnl + other.pnl,
860            price: self.price + other.price,
861            greeks: self.greeks + other.greeks,
862            ts_event: self.ts_event,
863            ts_init: self.ts_init,
864        }
865    }
866}
867
868impl From<GreeksData> for PortfolioGreeks {
869    fn from(g: GreeksData) -> Self {
870        g.to_portfolio_greeks()
871    }
872}
873
874impl Mul<&PortfolioGreeks> for f64 {
875    type Output = PortfolioGreeks;
876
877    fn mul(self, g: &PortfolioGreeks) -> PortfolioGreeks {
878        PortfolioGreeks {
879            pnl: self * g.pnl,
880            price: self * g.price,
881            greeks: g.greeks * self,
882            ts_event: g.ts_event,
883            ts_init: g.ts_init,
884        }
885    }
886}
887
888impl HasTsInit for PortfolioGreeks {
889    fn ts_init(&self) -> UnixNanos {
890        self.ts_init
891    }
892}
893
894impl HasGreeks for PortfolioGreeks {
895    fn greeks(&self) -> OptionGreekValues {
896        self.greeks
897    }
898}
899
900impl HasGreeks for BlackScholesGreeksResult {
901    fn greeks(&self) -> OptionGreekValues {
902        OptionGreekValues {
903            delta: self.delta,
904            gamma: self.gamma,
905            vega: self.vega,
906            theta: self.theta,
907            rho: self.rho,
908        }
909    }
910}
911
912#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
913#[cfg_attr(
914    feature = "python",
915    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
916)]
917#[cfg_attr(
918    feature = "python",
919    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
920)]
921pub struct YieldCurve {
922    pub curve_name: String,
923    pub tenors: Vec<f64>,
924    pub interest_rates: Vec<f64>,
925    pub ts_event: UnixNanos,
926    pub ts_init: UnixNanos,
927}
928
929impl YieldCurve {
930    #[must_use]
931    pub fn new(
932        curve_name: String,
933        tenors: Vec<f64>,
934        interest_rates: Vec<f64>,
935        ts_event: UnixNanos,
936        ts_init: UnixNanos,
937    ) -> Self {
938        Self {
939            curve_name,
940            tenors,
941            interest_rates,
942            ts_event,
943            ts_init,
944        }
945    }
946
947    // Interpolate the yield curve for a given expiry time
948    #[must_use]
949    pub fn get_rate(&self, expiry_in_years: f64) -> f64 {
950        if self.interest_rates.len() == 1 {
951            return self.interest_rates[0];
952        }
953
954        quadratic_interpolation(expiry_in_years, &self.tenors, &self.interest_rates)
955    }
956
957    /// Validates that [`Self::get_rate`] can evaluate this curve.
958    ///
959    /// # Errors
960    ///
961    /// Returns an error if `tenors` and `interest_rates` differ in length, hold two points or
962    /// none, or hold a non-finite value, or if `tenors` does not strictly increase with each
963    /// step wide enough to interpolate.
964    pub fn validate(&self) -> CorrectnessResult<()> {
965        check_equal_usize(
966            self.tenors.len(),
967            self.interest_rates.len(),
968            "tenors",
969            "interest_rates",
970        )?;
971
972        // Interpolation needs at least three points; a single rate is a flat curve
973        check_predicate_true(
974            self.interest_rates.len() == 1 || self.interest_rates.len() >= 3,
975            "`interest_rates` must hold one rate or at least three points",
976        )?;
977        check_predicate_true(
978            self.tenors
979                .iter()
980                .chain(&self.interest_rates)
981                .all(|value| value.is_finite()),
982            "`tenors` and `interest_rates` must be finite",
983        )?;
984        check_predicate_true(
985            self.tenors
986                .windows(2)
987                .all(|pair| pair[0] < pair[1] && !too_close_for_interpolation(pair[0], pair[1])),
988            "`tenors` must be strictly increasing, with each step wide enough to interpolate",
989        )
990    }
991}
992
993impl Display for YieldCurve {
994    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
995        write!(
996            f,
997            "YieldCurve(curve_name={}, ts_event={}, ts_init={})",
998            self.curve_name,
999            unix_nanos_to_iso8601(self.ts_event),
1000            unix_nanos_to_iso8601(self.ts_init)
1001        )
1002    }
1003}
1004
1005impl HasTsInit for YieldCurve {
1006    fn ts_init(&self) -> UnixNanos {
1007        self.ts_init
1008    }
1009}
1010
1011macro_rules! impl_greeks_custom_data {
1012    ($($type:ident),+ $(,)?) => {
1013        $(
1014            impl CustomDataTrait for $type {
1015                fn type_name(&self) -> &'static str {
1016                    Self::type_name_static()
1017                }
1018
1019                fn as_any(&self) -> &dyn Any {
1020                    self
1021                }
1022
1023                fn ts_event(&self) -> UnixNanos {
1024                    self.ts_event
1025                }
1026
1027                fn to_json(&self) -> anyhow::Result<String> {
1028                    Ok(serde_json::to_string(self)?)
1029                }
1030
1031                fn clone_arc(&self) -> Arc<dyn CustomDataTrait> {
1032                    Arc::new(self.clone())
1033                }
1034
1035                fn eq_arc(&self, other: &dyn CustomDataTrait) -> bool {
1036                    other.as_any().downcast_ref::<Self>() == Some(self)
1037                }
1038
1039                #[cfg(feature = "python")]
1040                fn to_pyobject(&self, py: pyo3::Python<'_>) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
1041                    crate::data::custom::clone_pyclass_to_pyobject(self, py)
1042                }
1043
1044                fn type_name_static() -> &'static str {
1045                    stringify!($type)
1046                }
1047
1048                fn from_json(value: serde_json::Value) -> anyhow::Result<Arc<dyn CustomDataTrait>> {
1049                    let parsed: Self = serde_json::from_value(value)?;
1050                    Ok(Arc::new(parsed))
1051                }
1052            }
1053        )+
1054    };
1055}
1056impl_greeks_custom_data!(GreeksData, PortfolioGreeks, YieldCurve);
1057
1058impl Default for YieldCurve {
1059    fn default() -> Self {
1060        Self {
1061            curve_name: "USD".to_string(),
1062            tenors: vec![0.5, 1.0, 1.5, 2.0, 2.5],
1063            interest_rates: vec![0.04, 0.04, 0.04, 0.04, 0.04],
1064            ts_event: UnixNanos::default(),
1065            ts_init: UnixNanos::default(),
1066        }
1067    }
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072    use rstest::rstest;
1073
1074    use super::*;
1075    use crate::{
1076        data::{CustomData, ensure_custom_data_json_registered},
1077        identifiers::InstrumentId,
1078    };
1079
1080    const JSON_ROUND_TRIP_VALUE: f64 = 51.248_178_375_505_404;
1081
1082    fn create_test_greeks_data() -> GreeksData {
1083        GreeksData::new(
1084            InstrumentId::from("SPY240315C00500000.OPRA"),
1085            true,
1086            500.0,
1087            20_240_315,
1088            91, // expiry_in_days (approximately 3 months)
1089            0.25,
1090            100.0,
1091            1.0,
1092            520.0,
1093            0.05,
1094            0.05,
1095            0.2,
1096            250.0,
1097            25.5,
1098            OptionGreekValues {
1099                delta: 0.65,
1100                gamma: 0.003,
1101                vega: 15.2,
1102                theta: -0.08,
1103                rho: 0.0,
1104            },
1105            0.75,
1106            UnixNanos::from(1_500_000_000),
1107            UnixNanos::from(1_000_000_000),
1108        )
1109    }
1110
1111    fn create_test_portfolio_greeks() -> PortfolioGreeks {
1112        PortfolioGreeks::new(
1113            1500.0,
1114            125.5,
1115            2.15,
1116            0.008,
1117            42.7,
1118            -2.3,
1119            UnixNanos::from(1_500_000_000),
1120            UnixNanos::from(1_000_000_000),
1121        )
1122    }
1123
1124    fn create_test_yield_curve() -> YieldCurve {
1125        YieldCurve::new(
1126            "USD".to_string(),
1127            vec![0.25, 0.5, 1.0, 2.0, 5.0],
1128            vec![0.025, 0.03, 0.035, 0.04, 0.045],
1129            UnixNanos::from(1_500_000_000),
1130            UnixNanos::from(1_000_000_000),
1131        )
1132    }
1133
1134    #[rstest]
1135    fn test_black_scholes_greeks_result_creation() {
1136        let result = BlackScholesGreeksResult {
1137            price: 25.5,
1138            vol: 0.2,
1139            delta: 0.65,
1140            gamma: 0.003,
1141            vega: 15.2,
1142            theta: -0.08,
1143            itm_prob: 0.55,
1144            rho: 1.75,
1145        };
1146
1147        assert_eq!(result.price, 25.5);
1148        assert_eq!(result.delta, 0.65);
1149        assert_eq!(result.gamma, 0.003);
1150        assert_eq!(result.vega, 15.2);
1151        assert_eq!(result.theta, -0.08);
1152        assert_eq!(result.itm_prob, 0.55);
1153    }
1154
1155    #[rstest]
1156    fn test_black_scholes_greeks_result_clone_and_copy() {
1157        let result1 = BlackScholesGreeksResult {
1158            price: 25.5,
1159            vol: 0.2,
1160            delta: 0.65,
1161            gamma: 0.003,
1162            vega: 15.2,
1163            theta: -0.08,
1164            itm_prob: 0.55,
1165            rho: 1.75,
1166        };
1167        let result2 = result1;
1168        let result3 = result1;
1169
1170        assert_eq!(result1, result2);
1171        assert_eq!(result1, result3);
1172    }
1173
1174    #[rstest]
1175    fn test_black_scholes_greeks_result_debug() {
1176        let result = BlackScholesGreeksResult {
1177            price: 25.5,
1178            vol: 0.2,
1179            delta: 0.65,
1180            gamma: 0.003,
1181            vega: 15.2,
1182            theta: -0.08,
1183            itm_prob: 0.55,
1184            rho: 1.75,
1185        };
1186        let debug_str = format!("{result:?}");
1187
1188        assert!(debug_str.contains("BlackScholesGreeksResult"));
1189        assert!(debug_str.contains("25.5"));
1190        assert!(debug_str.contains("0.65"));
1191    }
1192
1193    #[rstest]
1194    fn test_imply_vol_and_greeks_result_creation() {
1195        let result = BlackScholesGreeksResult {
1196            price: 25.5,
1197            vol: 0.2,
1198            delta: 0.65,
1199            gamma: 0.003,
1200            vega: 15.2,
1201            theta: -0.08,
1202            itm_prob: 0.55,
1203            rho: 1.75,
1204        };
1205
1206        assert_eq!(result.vol, 0.2);
1207        assert_eq!(result.price, 25.5);
1208        assert_eq!(result.delta, 0.65);
1209        assert_eq!(result.gamma, 0.003);
1210        assert_eq!(result.vega, 15.2);
1211        assert_eq!(result.theta, -0.08);
1212    }
1213
1214    #[rstest]
1215    fn test_black_scholes_greeks_basic_call() {
1216        let s = 100.0;
1217        let r = 0.05;
1218        let b = 0.05;
1219        let vol = 0.2;
1220        let is_call = true;
1221        let k = 100.0;
1222        let t = 1.0;
1223
1224        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1225
1226        assert!(greeks.price > 0.0);
1227        assert!(greeks.delta > 0.0 && greeks.delta < 1.0);
1228        assert!(greeks.gamma > 0.0);
1229        assert!(greeks.vega > 0.0);
1230        assert!(greeks.theta < 0.0); // Time decay for long option
1231    }
1232
1233    #[rstest]
1234    fn test_black_scholes_greeks_basic_put() {
1235        let s = 100.0;
1236        let r = 0.05;
1237        let b = 0.05;
1238        let vol = 0.2;
1239        let is_call = false;
1240        let k = 100.0;
1241        let t = 1.0;
1242
1243        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1244
1245        assert!(
1246            greeks.price > 0.0,
1247            "Put option price should be positive, was: {}",
1248            greeks.price
1249        );
1250        assert!(greeks.delta < 0.0 && greeks.delta > -1.0);
1251        assert!(greeks.gamma > 0.0);
1252        assert!(greeks.vega > 0.0);
1253        assert!(greeks.theta < 0.0); // Time decay for long option
1254    }
1255
1256    #[rstest]
1257    fn test_black_scholes_greeks_deep_itm_call() {
1258        let s = 150.0;
1259        let r = 0.05;
1260        let b = 0.05;
1261        let vol = 0.2;
1262        let is_call = true;
1263        let k = 100.0;
1264        let t = 1.0;
1265
1266        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1267
1268        assert!(greeks.delta > 0.9); // Deep ITM call has delta close to 1
1269        assert!(greeks.gamma > 0.0 && greeks.gamma < 0.01); // Low gamma for deep ITM
1270    }
1271
1272    #[rstest]
1273    fn test_black_scholes_greeks_deep_otm_call() {
1274        let s = 50.0;
1275        let r = 0.05;
1276        let b = 0.05;
1277        let vol = 0.2;
1278        let is_call = true;
1279        let k = 100.0;
1280        let t = 1.0;
1281
1282        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1283
1284        assert!(greeks.delta < 0.1); // Deep OTM call has delta close to 0
1285        assert!(greeks.gamma > 0.0 && greeks.gamma < 0.01); // Low gamma for deep OTM
1286    }
1287
1288    #[rstest]
1289    fn test_black_scholes_greeks_zero_time() {
1290        let s = 100.0;
1291        let r = 0.05;
1292        let b = 0.05;
1293        let vol = 0.2;
1294        let is_call = true;
1295        let k = 100.0;
1296        let t = 0.0001; // Near zero time
1297
1298        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1299
1300        assert!(greeks.price >= 0.0);
1301        assert!(greeks.theta.is_finite());
1302    }
1303
1304    #[rstest]
1305    fn test_imply_vol_basic() {
1306        let s = 100.0;
1307        let r = 0.05;
1308        let b = 0.05;
1309        let vol = 0.2;
1310        let is_call = true;
1311        let k = 100.0;
1312        let t = 1.0;
1313
1314        let theoretical_price = black_scholes_greeks(s, r, b, vol, is_call, k, t).price;
1315        let implied_vol = imply_vol(s, r, b, is_call, k, t, theoretical_price);
1316
1317        // Tolerance relaxed due to numerical precision differences between fast_norm_query and exact methods
1318        let tolerance = 1e-4;
1319        assert!(
1320            (implied_vol - vol).abs() < tolerance,
1321            "Implied vol difference exceeds tolerance: {implied_vol} vs {vol}"
1322        );
1323    }
1324
1325    // Note: Implied volatility tests across different strikes can be sensitive to numerical precision
1326    // The basic implied vol test already covers the core functionality
1327
1328    // Note: Comprehensive implied vol consistency test is challenging due to numerical precision
1329    // The existing accuracy tests already cover this functionality adequately
1330
1331    #[rstest]
1332    fn test_greeks_data_new() {
1333        let greeks = create_test_greeks_data();
1334
1335        assert_eq!(greeks.ts_init, UnixNanos::from(1_000_000_000));
1336        assert_eq!(greeks.ts_event, UnixNanos::from(1_500_000_000));
1337        assert_eq!(
1338            greeks.instrument_id,
1339            InstrumentId::from("SPY240315C00500000.OPRA")
1340        );
1341        assert!(greeks.is_call);
1342        assert_eq!(greeks.strike, 500.0);
1343        assert_eq!(greeks.expiry, 20_240_315);
1344        assert_eq!(greeks.expiry_in_years, 0.25);
1345        assert_eq!(greeks.multiplier, 100.0);
1346        assert_eq!(greeks.quantity, 1.0);
1347        assert_eq!(greeks.underlying_price, 520.0);
1348        assert_eq!(greeks.interest_rate, 0.05);
1349        assert_eq!(greeks.cost_of_carry, 0.05);
1350        assert_eq!(greeks.vol, 0.2);
1351        assert_eq!(greeks.pnl, 250.0);
1352        assert_eq!(greeks.price, 25.5);
1353        assert_eq!(greeks.delta, 0.65);
1354        assert_eq!(greeks.gamma, 0.003);
1355        assert_eq!(greeks.vega, 15.2);
1356        assert_eq!(greeks.theta, -0.08);
1357        assert_eq!(greeks.itm_prob, 0.75);
1358    }
1359
1360    #[rstest]
1361    fn test_greeks_data_from_delta() {
1362        let delta = 0.5;
1363        let multiplier = 100.0;
1364        let ts_event = UnixNanos::from(2_000_000_000);
1365        let instrument_id = InstrumentId::from("AAPL240315C00180000.OPRA");
1366
1367        let greeks = GreeksData::from_delta(instrument_id, delta, multiplier, ts_event);
1368
1369        assert_eq!(greeks.ts_init, ts_event);
1370        assert_eq!(greeks.ts_event, ts_event);
1371        assert_eq!(greeks.instrument_id, instrument_id);
1372        assert!(greeks.is_call);
1373        assert_eq!(greeks.delta, delta);
1374        assert_eq!(greeks.multiplier, multiplier);
1375        assert_eq!(greeks.quantity, 1.0);
1376
1377        // Check that all other fields are zeroed
1378        assert_eq!(greeks.strike, 0.0);
1379        assert_eq!(greeks.expiry, 0);
1380        assert_eq!(greeks.price, 0.0);
1381        assert_eq!(greeks.gamma, 0.0);
1382        assert_eq!(greeks.vega, 0.0);
1383        assert_eq!(greeks.theta, 0.0);
1384    }
1385
1386    #[rstest]
1387    fn test_greeks_data_default() {
1388        let greeks = GreeksData::default();
1389
1390        assert_eq!(greeks.ts_init, UnixNanos::default());
1391        assert_eq!(greeks.ts_event, UnixNanos::default());
1392        assert_eq!(greeks.instrument_id, InstrumentId::from("ES.GLBX"));
1393        assert!(greeks.is_call);
1394        assert_eq!(greeks.strike, 0.0);
1395        assert_eq!(greeks.expiry, 0);
1396        assert_eq!(greeks.multiplier, 0.0);
1397        assert_eq!(greeks.quantity, 0.0);
1398        assert_eq!(greeks.delta, 0.0);
1399        assert_eq!(greeks.gamma, 0.0);
1400        assert_eq!(greeks.vega, 0.0);
1401        assert_eq!(greeks.theta, 0.0);
1402    }
1403
1404    #[rstest]
1405    fn test_greeks_data_display() {
1406        let greeks = create_test_greeks_data();
1407        let display_str = format!("{greeks}");
1408
1409        assert_eq!(
1410            display_str,
1411            "GreeksData(instrument_id=SPY240315C00500000.OPRA, expiry=20240315, itm_prob=75.00%, vol=20.00%, pnl=250.00, price=25.50, delta=0.65, gamma=0.00, vega=15.20, theta=-0.08, quantity=1, ts_event=1970-01-01T00:00:01.500000000Z, ts_init=1970-01-01T00:00:01.000000000Z)"
1412        );
1413    }
1414
1415    #[rstest]
1416    fn test_greeks_data_multiplication() {
1417        let greeks = create_test_greeks_data();
1418        let quantity = 5.0;
1419        let scaled_greeks = quantity * &greeks;
1420
1421        assert_eq!(scaled_greeks.ts_init, greeks.ts_init);
1422        assert_eq!(scaled_greeks.ts_event, greeks.ts_event);
1423        assert_eq!(scaled_greeks.instrument_id, greeks.instrument_id);
1424        assert_eq!(scaled_greeks.is_call, greeks.is_call);
1425        assert_eq!(scaled_greeks.strike, greeks.strike);
1426        assert_eq!(scaled_greeks.expiry, greeks.expiry);
1427        assert_eq!(scaled_greeks.multiplier, greeks.multiplier);
1428        assert_eq!(scaled_greeks.quantity, greeks.quantity);
1429        assert_eq!(scaled_greeks.vol, greeks.vol);
1430        assert_eq!(scaled_greeks.itm_prob, greeks.itm_prob);
1431
1432        // Check scaled values
1433        assert_eq!(scaled_greeks.pnl, quantity * greeks.pnl);
1434        assert_eq!(scaled_greeks.price, quantity * greeks.price);
1435        assert_eq!(scaled_greeks.delta, quantity * greeks.delta);
1436        assert_eq!(scaled_greeks.gamma, quantity * greeks.gamma);
1437        assert_eq!(scaled_greeks.vega, quantity * greeks.vega);
1438        assert_eq!(scaled_greeks.theta, quantity * greeks.theta);
1439    }
1440
1441    #[rstest]
1442    fn test_greeks_data_has_ts_init() {
1443        let greeks = create_test_greeks_data();
1444        assert_eq!(greeks.ts_init(), UnixNanos::from(1_000_000_000));
1445    }
1446
1447    #[rstest]
1448    fn test_greeks_data_clone() {
1449        let greeks1 = create_test_greeks_data();
1450        let greeks2 = greeks1.clone();
1451
1452        assert_eq!(greeks1.ts_init, greeks2.ts_init);
1453        assert_eq!(greeks1.instrument_id, greeks2.instrument_id);
1454        assert_eq!(greeks1.delta, greeks2.delta);
1455        assert_eq!(greeks1.gamma, greeks2.gamma);
1456    }
1457
1458    #[rstest]
1459    fn test_portfolio_greeks_new() {
1460        let portfolio_greeks = create_test_portfolio_greeks();
1461
1462        assert_eq!(portfolio_greeks.ts_init, UnixNanos::from(1_000_000_000));
1463        assert_eq!(portfolio_greeks.ts_event, UnixNanos::from(1_500_000_000));
1464        assert_eq!(portfolio_greeks.pnl, 1500.0);
1465        assert_eq!(portfolio_greeks.price, 125.5);
1466        assert_eq!(portfolio_greeks.delta, 2.15);
1467        assert_eq!(portfolio_greeks.gamma, 0.008);
1468        assert_eq!(portfolio_greeks.vega, 42.7);
1469        assert_eq!(portfolio_greeks.theta, -2.3);
1470    }
1471
1472    #[rstest]
1473    fn test_portfolio_greeks_default() {
1474        let portfolio_greeks = PortfolioGreeks::default();
1475
1476        assert_eq!(portfolio_greeks.ts_init, UnixNanos::default());
1477        assert_eq!(portfolio_greeks.ts_event, UnixNanos::default());
1478        assert_eq!(portfolio_greeks.pnl, 0.0);
1479        assert_eq!(portfolio_greeks.price, 0.0);
1480        assert_eq!(portfolio_greeks.delta, 0.0);
1481        assert_eq!(portfolio_greeks.gamma, 0.0);
1482        assert_eq!(portfolio_greeks.vega, 0.0);
1483        assert_eq!(portfolio_greeks.theta, 0.0);
1484    }
1485
1486    #[rstest]
1487    fn test_portfolio_greeks_display() {
1488        let portfolio_greeks = create_test_portfolio_greeks();
1489        let display_str = format!("{portfolio_greeks}");
1490
1491        assert_eq!(
1492            display_str,
1493            "PortfolioGreeks(pnl=1500.00, price=125.50, delta=2.15, gamma=0.01, vega=42.70, theta=-2.30, ts_event=1970-01-01T00:00:01.500000000Z, ts_init=1970-01-01T00:00:01.000000000Z)"
1494        );
1495    }
1496
1497    #[rstest]
1498    fn test_portfolio_greeks_addition() {
1499        let mut greeks1 = PortfolioGreeks::new(
1500            100.0,
1501            50.0,
1502            1.0,
1503            0.005,
1504            20.0,
1505            -1.0,
1506            UnixNanos::from(1_500_000_000),
1507            UnixNanos::from(1_000_000_000),
1508        );
1509
1510        let mut greeks2 = PortfolioGreeks::new(
1511            200.0,
1512            75.0,
1513            1.5,
1514            0.003,
1515            25.0,
1516            -1.5,
1517            UnixNanos::from(2_500_000_000),
1518            UnixNanos::from(2_000_000_000),
1519        );
1520
1521        greeks1.greeks.rho = 12.0;
1522        greeks2.greeks.rho = 17.0;
1523
1524        let result = greeks1 + greeks2;
1525
1526        assert_eq!(result.ts_init, UnixNanos::from(1_000_000_000)); // Uses first ts_init
1527        assert_eq!(result.ts_event, UnixNanos::from(1_500_000_000)); // Uses first ts_event
1528        assert_eq!(result.pnl, 300.0);
1529        assert_eq!(result.price, 125.0);
1530        assert_eq!(result.delta, 2.5);
1531        assert_eq!(result.gamma, 0.008);
1532        assert_eq!(result.vega, 45.0);
1533        assert_eq!(result.theta, -2.5);
1534        assert_eq!(result.rho, 29.0);
1535    }
1536
1537    #[rstest]
1538    #[case(1.0, [20.0, 30.0, 40.0, 50.0, 60.0, -70.0, 80.0])]
1539    #[case(2.0, [40.0, 60.0, 80.0, 100.0, 120.0, -140.0, 160.0])]
1540    #[case(-3.0, [-60.0, -90.0, -120.0, -150.0, -180.0, 210.0, -240.0])]
1541    #[case(0.0, [0.0; 7])]
1542    fn test_greeks_data_portfolio_scaling(#[case] quantity: f64, #[case] expected: [f64; 7]) {
1543        let greeks = GreeksData {
1544            pnl: 2.0,
1545            price: 3.0,
1546            multiplier: 10.0,
1547            quantity: 9.0,
1548            greeks: OptionGreekValues {
1549                delta: 4.0,
1550                gamma: 5.0,
1551                vega: 6.0,
1552                theta: -7.0,
1553                rho: 8.0,
1554            },
1555            ..create_test_greeks_data()
1556        };
1557
1558        let portfolio = quantity * &greeks.to_portfolio_greeks();
1559
1560        assert_eq!(portfolio.ts_init, UnixNanos::from(1_000_000_000));
1561        assert_eq!(portfolio.ts_event, UnixNanos::from(1_500_000_000));
1562        assert_eq!(
1563            [
1564                portfolio.pnl,
1565                portfolio.price,
1566                portfolio.delta,
1567                portfolio.gamma,
1568                portfolio.vega,
1569                portfolio.theta,
1570                portfolio.rho
1571            ],
1572            expected,
1573        );
1574        assert_eq!(greeks.pnl, 2.0);
1575        assert_eq!(greeks.price, 3.0);
1576        assert_eq!(greeks.multiplier, 10.0);
1577        assert_eq!(greeks.quantity, 9.0);
1578        assert_eq!(
1579            greeks.greeks,
1580            OptionGreekValues {
1581                delta: 4.0,
1582                gamma: 5.0,
1583                vega: 6.0,
1584                theta: -7.0,
1585                rho: 8.0,
1586            }
1587        );
1588    }
1589
1590    #[rstest]
1591    fn test_portfolio_greeks_from_greeks_data() {
1592        let greeks_data = create_test_greeks_data();
1593        let portfolio_greeks: PortfolioGreeks = greeks_data.clone().into();
1594
1595        assert_eq!(portfolio_greeks.ts_init, greeks_data.ts_init);
1596        assert_eq!(portfolio_greeks.ts_event, greeks_data.ts_event);
1597        assert_eq!(portfolio_greeks.pnl, 25_000.0);
1598        assert_eq!(portfolio_greeks.price, 2_550.0);
1599        assert_eq!(portfolio_greeks.delta, 65.0);
1600        assert_eq!(portfolio_greeks.gamma, 0.3);
1601        assert_eq!(portfolio_greeks.vega, 1_520.0);
1602        assert_eq!(portfolio_greeks.theta, -8.0);
1603        assert_eq!(portfolio_greeks.rho, 0.0);
1604    }
1605
1606    #[rstest]
1607    fn test_portfolio_greeks_has_ts_init() {
1608        let portfolio_greeks = create_test_portfolio_greeks();
1609        assert_eq!(portfolio_greeks.ts_init(), UnixNanos::from(1_000_000_000));
1610    }
1611
1612    #[rstest]
1613    fn test_yield_curve_new() {
1614        let curve = create_test_yield_curve();
1615
1616        assert_eq!(curve.ts_init, UnixNanos::from(1_000_000_000));
1617        assert_eq!(curve.ts_event, UnixNanos::from(1_500_000_000));
1618        assert_eq!(curve.curve_name, "USD");
1619        assert_eq!(curve.tenors, vec![0.25, 0.5, 1.0, 2.0, 5.0]);
1620        assert_eq!(curve.interest_rates, vec![0.025, 0.03, 0.035, 0.04, 0.045]);
1621    }
1622
1623    #[rstest]
1624    fn test_yield_curve_default() {
1625        let curve = YieldCurve::default();
1626
1627        assert_eq!(curve.ts_init, UnixNanos::default());
1628        assert_eq!(curve.ts_event, UnixNanos::default());
1629        assert_eq!(curve.curve_name, "USD");
1630        assert_eq!(curve.tenors, vec![0.5, 1.0, 1.5, 2.0, 2.5]);
1631        assert_eq!(curve.interest_rates, vec![0.04, 0.04, 0.04, 0.04, 0.04]);
1632    }
1633
1634    #[rstest]
1635    fn test_yield_curve_get_rate_single_point() {
1636        let curve = YieldCurve::new(
1637            "USD".to_string(),
1638            vec![1.0],
1639            vec![0.05],
1640            UnixNanos::default(),
1641            UnixNanos::default(),
1642        );
1643
1644        assert_eq!(curve.get_rate(0.5), 0.05);
1645        assert_eq!(curve.get_rate(1.0), 0.05);
1646        assert_eq!(curve.get_rate(2.0), 0.05);
1647    }
1648
1649    #[rstest]
1650    fn test_yield_curve_get_rate_interpolation() {
1651        let curve = create_test_yield_curve();
1652
1653        // Test exact matches
1654        assert_eq!(curve.get_rate(0.25), 0.025);
1655        assert_eq!(curve.get_rate(1.0), 0.035);
1656        assert_eq!(curve.get_rate(5.0), 0.045);
1657
1658        // Test interpolation (results will depend on quadratic_interpolation implementation)
1659        let rate_0_75 = curve.get_rate(0.75);
1660        assert!(rate_0_75 > 0.025 && rate_0_75 < 0.045);
1661    }
1662
1663    #[rstest]
1664    fn test_yield_curve_display() {
1665        let curve = create_test_yield_curve();
1666        let display_str = format!("{curve}");
1667
1668        assert_eq!(
1669            display_str,
1670            "YieldCurve(curve_name=USD, ts_event=1970-01-01T00:00:01.500000000Z, ts_init=1970-01-01T00:00:01.000000000Z)"
1671        );
1672    }
1673
1674    #[rstest]
1675    fn test_yield_curve_has_ts_init() {
1676        let curve = create_test_yield_curve();
1677        assert_eq!(curve.ts_init(), UnixNanos::from(1_000_000_000));
1678    }
1679
1680    #[rstest]
1681    fn test_yield_curve_clone() {
1682        let curve1 = create_test_yield_curve();
1683        let curve2 = curve1.clone();
1684
1685        assert_eq!(curve1.curve_name, curve2.curve_name);
1686        assert_eq!(curve1.tenors, curve2.tenors);
1687        assert_eq!(curve1.interest_rates, curve2.interest_rates);
1688    }
1689
1690    #[rstest]
1691    #[case(vec![0.0], vec![0.04])]
1692    #[case(vec![0.25, 1.0, 5.0], vec![0.043, 0.041, 0.038])]
1693    fn test_yield_curve_validate_accepts_evaluable_curves(
1694        #[case] tenors: Vec<f64>,
1695        #[case] interest_rates: Vec<f64>,
1696    ) {
1697        let curve = YieldCurve::new(
1698            "USD".to_string(),
1699            tenors,
1700            interest_rates,
1701            UnixNanos::default(),
1702            UnixNanos::default(),
1703        );
1704
1705        assert!(curve.validate().is_ok());
1706    }
1707
1708    #[rstest]
1709    #[case(vec![0.5, 1.0, 2.0], vec![0.04, 0.05], "'tenors' usize of 3 was not equal")]
1710    #[case(vec![0.5, 1.0], vec![0.04, 0.05], "one rate or at least three points")]
1711    #[case(vec![], vec![], "one rate or at least three points")]
1712    #[case(vec![0.25, 1.0, 5.0], vec![0.04, f64::NAN, 0.05], "must be finite")]
1713    #[case(vec![0.25, f64::INFINITY, 5.0], vec![0.04, 0.05, 0.06], "must be finite")]
1714    #[case(vec![0.05, 0.05, 1.0], vec![0.04, 0.05, 0.06], "strictly increasing")]
1715    #[case(vec![1.0, 0.5, 2.0], vec![0.04, 0.05, 0.06], "strictly increasing")]
1716    #[case(vec![1.0, 1.0 + f64::EPSILON, 2.0], vec![0.04, 0.05, 0.06], "wide enough")]
1717    fn test_yield_curve_validate_rejects_curves_get_rate_cannot_evaluate(
1718        #[case] tenors: Vec<f64>,
1719        #[case] interest_rates: Vec<f64>,
1720        #[case] message: &str,
1721    ) {
1722        let curve = YieldCurve::new(
1723            "USD".to_string(),
1724            tenors,
1725            interest_rates,
1726            UnixNanos::default(),
1727            UnixNanos::default(),
1728        );
1729
1730        let error = curve.validate().unwrap_err();
1731
1732        assert!(
1733            error.to_string().contains(message),
1734            "error was {error}, expected to contain {message}"
1735        );
1736    }
1737
1738    #[rstest]
1739    fn test_yield_curve_custom_data_json_round_trip() {
1740        let curve = create_test_yield_curve();
1741        let mut other = curve.clone();
1742        other.interest_rates[0] = 0.02;
1743
1744        let json = curve.to_json().unwrap();
1745        let restored = YieldCurve::from_json(serde_json::from_str(&json).unwrap()).unwrap();
1746
1747        assert_eq!(curve.type_name(), "YieldCurve");
1748        assert_eq!(YieldCurve::type_name_static(), "YieldCurve");
1749        assert_eq!(
1750            CustomDataTrait::ts_event(&curve),
1751            UnixNanos::from(1_500_000_000)
1752        );
1753        assert!(restored.eq_arc(&curve));
1754        assert!(!restored.eq_arc(&other));
1755        assert_eq!(restored.as_any().downcast_ref::<YieldCurve>(), Some(&curve));
1756    }
1757
1758    #[rstest]
1759    #[case::instrument(Arc::new(create_test_greeks_data()))]
1760    #[case::portfolio(Arc::new(create_test_portfolio_greeks()))]
1761    #[case::yield_curve(Arc::new(create_test_yield_curve()))]
1762    #[case::instrument_precision(Arc::new(GreeksData {
1763        price: JSON_ROUND_TRIP_VALUE,
1764        ..create_test_greeks_data()
1765    }))]
1766    #[case::portfolio_precision(Arc::new(PortfolioGreeks {
1767        pnl: JSON_ROUND_TRIP_VALUE,
1768        ..create_test_portfolio_greeks()
1769    }))]
1770    #[case::yield_curve_precision(Arc::new(YieldCurve {
1771        interest_rates: vec![JSON_ROUND_TRIP_VALUE],
1772        tenors: vec![1.0],
1773        ..create_test_yield_curve()
1774    }))]
1775    fn test_greeks_custom_data_envelope_round_trip(#[case] data: Arc<dyn CustomDataTrait>) {
1776        ensure_custom_data_json_registered::<GreeksData>().unwrap();
1777        ensure_custom_data_json_registered::<PortfolioGreeks>().unwrap();
1778        ensure_custom_data_json_registered::<YieldCurve>().unwrap();
1779        let original = CustomData::from_arc(data);
1780        let encoded = serde_json::to_vec(&original).unwrap();
1781        let restored = CustomData::from_json_bytes(&encoded).unwrap();
1782
1783        assert_eq!(restored, original);
1784        assert_eq!(restored.data.ts_event(), original.data.ts_event());
1785        assert_eq!(restored.ts_init(), original.ts_init());
1786        assert!(restored.data.clone_arc().eq_arc(original.data.as_ref()));
1787        assert!(!restored.data.eq_arc(&YieldCurve::default()));
1788    }
1789
1790    #[rstest]
1791    fn test_black_scholes_greeks_extreme_values() {
1792        let s = 1000.0;
1793        let r = 0.1;
1794        let b = 0.1;
1795        let vol = 0.5;
1796        let is_call = true;
1797        let k = 10.0; // Very deep ITM
1798        let t = 0.1;
1799
1800        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1801
1802        assert!(greeks.price.is_finite());
1803        assert!(greeks.delta.is_finite());
1804        assert!(greeks.gamma.is_finite());
1805        assert!(greeks.vega.is_finite());
1806        assert!(greeks.theta.is_finite());
1807        assert!(greeks.price > 0.0);
1808        assert!(greeks.delta > 0.99); // Very deep ITM call
1809    }
1810
1811    #[rstest]
1812    fn test_black_scholes_greeks_high_volatility() {
1813        let s = 100.0;
1814        let r = 0.05;
1815        let b = 0.05;
1816        let vol = 2.0; // 200% volatility
1817        let is_call = true;
1818        let k = 100.0;
1819        let t = 1.0;
1820
1821        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1822
1823        assert!(greeks.price.is_finite());
1824        assert!(greeks.delta.is_finite());
1825        assert!(greeks.gamma.is_finite());
1826        assert!(greeks.vega.is_finite());
1827        assert!(greeks.theta.is_finite());
1828        assert!(greeks.price > 0.0);
1829    }
1830
1831    #[rstest]
1832    fn test_greeks_data_put_option() {
1833        let greeks = GreeksData::new(
1834            InstrumentId::from("SPY240315P00480000.OPRA"),
1835            false, // Put option
1836            480.0,
1837            20_240_315,
1838            91, // expiry_in_days (approximately 3 months)
1839            0.25,
1840            100.0,
1841            1.0,
1842            500.0,
1843            0.05,
1844            0.05,
1845            0.25,
1846            -150.0, // Negative PnL
1847            8.5,
1848            OptionGreekValues {
1849                delta: -0.35,
1850                gamma: 0.002,
1851                vega: 12.8,
1852                theta: -0.06,
1853                rho: 0.0,
1854            },
1855            0.25,
1856            UnixNanos::from(1_500_000_000),
1857            UnixNanos::from(1_000_000_000),
1858        );
1859
1860        assert!(!greeks.is_call);
1861        assert!(greeks.delta < 0.0);
1862        assert_eq!(greeks.pnl, -150.0);
1863    }
1864
1865    #[rstest]
1866    #[case(true, 10.450_583_572_185_565, -0.017_572_678_209_419_72)]
1867    #[case(false, 5.573_526_022_256_971, -0.004_542_138_147_766_099)]
1868    fn test_theta_per_calendar_day(
1869        #[case] is_call: bool,
1870        #[case] price: f64,
1871        #[case] expected: f64,
1872    ) {
1873        let exact = black_scholes_greeks_exact(100.0, 0.05, 0.05, 0.2, is_call, 100.0, 1.0);
1874        let fast = black_scholes_greeks(100.0, 0.05, 0.05, 0.2, is_call, 100.0, 1.0);
1875        let implied = imply_vol_and_greeks(100.0, 0.05, 0.05, is_call, 100.0, 1.0, price);
1876        let refined = refine_vol_and_greeks(100.0, 0.05, 0.05, is_call, 100.0, 1.0, price, 0.2);
1877
1878        assert!((exact.theta - expected).abs() < 1e-12);
1879
1880        for result in [fast, implied, refined] {
1881            assert!(
1882                (result.theta - expected).abs() < 5e-8,
1883                "Expected daily theta {expected}, was {}",
1884                result.theta
1885            );
1886        }
1887    }
1888
1889    // Original accuracy tests (keeping these as they are comprehensive)
1890    #[rstest]
1891    fn test_greeks_accuracy_call() {
1892        let s = 100.0;
1893        let k = 100.1;
1894        let t = 1.0;
1895        let r = 0.01;
1896        let b = 0.005;
1897        let vol = 0.2;
1898        let is_call = true;
1899        let eps = 1e-3;
1900
1901        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1902
1903        // Use exact method for finite difference calculations for better precision
1904        let price0 = |s: f64| black_scholes_greeks_exact(s, r, b, vol, is_call, k, t).price;
1905
1906        let delta_bnr = (price0(s + eps) - price0(s - eps)) / (2.0 * eps);
1907        let gamma_bnr = (price0(s + eps) + price0(s - eps) - 2.0 * price0(s)) / (eps * eps);
1908        let vega_bnr = (black_scholes_greeks_exact(s, r, b, vol + eps, is_call, k, t).price
1909            - black_scholes_greeks_exact(s, r, b, vol - eps, is_call, k, t).price)
1910            / (2.0 * eps)
1911            / 100.0;
1912        let theta_bnr = (black_scholes_greeks_exact(s, r, b, vol, is_call, k, t - eps).price
1913            - black_scholes_greeks_exact(s, r, b, vol, is_call, k, t + eps).price)
1914            / (2.0 * eps)
1915            / 365.0;
1916
1917        // Tolerance relaxed due to differences between fast f32 implementation and exact finite difference approximations
1918        // Also accounts for differences in how b (cost of carry) is handled between implementations
1919        let tolerance = 5e-3;
1920        assert!(
1921            (greeks.delta - delta_bnr).abs() < tolerance,
1922            "Delta difference exceeds tolerance: {} vs {}",
1923            greeks.delta,
1924            delta_bnr
1925        );
1926        // Gamma tolerance is more relaxed due to second-order finite differences being less accurate and f32 precision
1927        let gamma_tolerance = 0.1;
1928        assert!(
1929            (greeks.gamma - gamma_bnr).abs() < gamma_tolerance,
1930            "Gamma difference exceeds tolerance: {} vs {}",
1931            greeks.gamma,
1932            gamma_bnr
1933        );
1934        // Both greeks.vega and vega_bnr are per 1% vol (absolute percent change).
1935        assert!(
1936            (greeks.vega - vega_bnr).abs() < tolerance,
1937            "Vega difference exceeds tolerance: {} vs {}",
1938            greeks.vega,
1939            vega_bnr
1940        );
1941        assert!(
1942            (greeks.theta - theta_bnr).abs() < tolerance,
1943            "Theta difference exceeds tolerance: {} vs {}",
1944            greeks.theta,
1945            theta_bnr
1946        );
1947    }
1948
1949    #[rstest]
1950    fn test_greeks_accuracy_put() {
1951        let s = 100.0;
1952        let k = 100.1;
1953        let t = 1.0;
1954        let r = 0.01;
1955        let b = 0.005;
1956        let vol = 0.2;
1957        let is_call = false;
1958        let eps = 1e-3;
1959
1960        let greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
1961
1962        // Use exact method for finite difference calculations for better precision
1963        let price0 = |s: f64| black_scholes_greeks_exact(s, r, b, vol, is_call, k, t).price;
1964
1965        let delta_bnr = (price0(s + eps) - price0(s - eps)) / (2.0 * eps);
1966        let gamma_bnr = (price0(s + eps) + price0(s - eps) - 2.0 * price0(s)) / (eps * eps);
1967        let vega_bnr = (black_scholes_greeks_exact(s, r, b, vol + eps, is_call, k, t).price
1968            - black_scholes_greeks_exact(s, r, b, vol - eps, is_call, k, t).price)
1969            / (2.0 * eps)
1970            / 100.0;
1971        let theta_bnr = (black_scholes_greeks_exact(s, r, b, vol, is_call, k, t - eps).price
1972            - black_scholes_greeks_exact(s, r, b, vol, is_call, k, t + eps).price)
1973            / (2.0 * eps)
1974            / 365.0;
1975
1976        // Tolerance relaxed due to differences between fast f32 implementation and exact finite difference approximations
1977        // Also accounts for differences in how b (cost of carry) is handled between implementations
1978        let tolerance = 5e-3;
1979        assert!(
1980            (greeks.delta - delta_bnr).abs() < tolerance,
1981            "Delta difference exceeds tolerance: {} vs {}",
1982            greeks.delta,
1983            delta_bnr
1984        );
1985        // Gamma tolerance is more relaxed due to second-order finite differences being less accurate and f32 precision
1986        let gamma_tolerance = 0.1;
1987        assert!(
1988            (greeks.gamma - gamma_bnr).abs() < gamma_tolerance,
1989            "Gamma difference exceeds tolerance: {} vs {}",
1990            greeks.gamma,
1991            gamma_bnr
1992        );
1993        // Both greeks.vega and vega_bnr are per 1% vol (absolute percent change).
1994        assert!(
1995            (greeks.vega - vega_bnr).abs() < tolerance,
1996            "Vega difference exceeds tolerance: {} vs {}",
1997            greeks.vega,
1998            vega_bnr
1999        );
2000        assert!(
2001            (greeks.theta - theta_bnr).abs() < tolerance,
2002            "Theta difference exceeds tolerance: {} vs {}",
2003            greeks.theta,
2004            theta_bnr
2005        );
2006    }
2007
2008    #[rstest]
2009    fn test_imply_vol_and_greeks_accuracy_call() {
2010        let s = 100.0;
2011        let k = 100.1;
2012        let t = 1.0;
2013        let r = 0.01;
2014        let b = 0.005;
2015        let vol = 0.2;
2016        let is_call = true;
2017
2018        let base_greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
2019        let price = base_greeks.price;
2020
2021        let implied_result = imply_vol_and_greeks(s, r, b, is_call, k, t, price);
2022
2023        // Tolerance relaxed due to numerical precision differences
2024        let tolerance = 2e-4;
2025        assert!(
2026            (implied_result.vol - vol).abs() < tolerance,
2027            "Vol difference exceeds tolerance: {} vs {}",
2028            implied_result.vol,
2029            vol
2030        );
2031        assert!(
2032            (implied_result.price - base_greeks.price).abs() < tolerance,
2033            "Price difference exceeds tolerance: {} vs {}",
2034            implied_result.price,
2035            base_greeks.price
2036        );
2037        assert!(
2038            (implied_result.delta - base_greeks.delta).abs() < tolerance,
2039            "Delta difference exceeds tolerance: {} vs {}",
2040            implied_result.delta,
2041            base_greeks.delta
2042        );
2043        assert!(
2044            (implied_result.gamma - base_greeks.gamma).abs() < tolerance,
2045            "Gamma difference exceeds tolerance: {} vs {}",
2046            implied_result.gamma,
2047            base_greeks.gamma
2048        );
2049        assert!(
2050            (implied_result.vega - base_greeks.vega).abs() < tolerance,
2051            "Vega difference exceeds tolerance: {} vs {}",
2052            implied_result.vega,
2053            base_greeks.vega
2054        );
2055        assert!(
2056            (implied_result.theta - base_greeks.theta).abs() < tolerance,
2057            "Theta difference exceeds tolerance: {} vs {}",
2058            implied_result.theta,
2059            base_greeks.theta
2060        );
2061    }
2062
2063    #[rstest]
2064    fn test_black_scholes_greeks_target_price_refinement() {
2065        let s = 100.0;
2066        let r = 0.05;
2067        let b = 0.05;
2068        let initial_vol = 0.2;
2069        let is_call = true;
2070        let k = 100.0;
2071        let t = 1.0;
2072
2073        // Calculate the price with the initial vol
2074        let initial_greeks = black_scholes_greeks(s, r, b, initial_vol, is_call, k, t);
2075        let target_price = initial_greeks.price;
2076
2077        // Now use a slightly different vol and refine it using target_price
2078        let refined_vol = initial_vol * 1.1; // 10% higher vol
2079        let refined_greeks =
2080            refine_vol_and_greeks(s, r, b, is_call, k, t, target_price, refined_vol);
2081
2082        // The refined vol should be closer to the initial vol, and the price should match the target
2083        // Tolerance matches the function's convergence tolerance (price_epsilon * 2.0)
2084        let price_tolerance = (s * 5e-5).max(1e-4) * 2.0;
2085        assert!(
2086            (refined_greeks.price - target_price).abs() < price_tolerance,
2087            "Refined price should match target: {} vs {}",
2088            refined_greeks.price,
2089            target_price
2090        );
2091
2092        // The refined vol should be between the initial and refined vol (converged towards initial)
2093        assert!(
2094            refined_vol > refined_greeks.vol && refined_greeks.vol > initial_vol * 0.9,
2095            "Refined vol should converge towards initial: {} (initial: {}, refined: {})",
2096            refined_greeks.vol,
2097            initial_vol,
2098            refined_vol
2099        );
2100    }
2101
2102    #[rstest]
2103    fn test_black_scholes_greeks_target_price_refinement_put() {
2104        let s = 100.0;
2105        let r = 0.05;
2106        let b = 0.05;
2107        let initial_vol = 0.25;
2108        let is_call = false;
2109        let k = 105.0;
2110        let t = 0.5;
2111
2112        // Calculate the price with the initial vol
2113        let initial_greeks = black_scholes_greeks(s, r, b, initial_vol, is_call, k, t);
2114        let target_price = initial_greeks.price;
2115
2116        // Now use a different vol and refine it using target_price
2117        let refined_vol = initial_vol * 0.8; // 20% lower vol
2118        let refined_greeks =
2119            refine_vol_and_greeks(s, r, b, is_call, k, t, target_price, refined_vol);
2120
2121        // The refined price should match the target
2122        // Tolerance matches the function's convergence tolerance (price_epsilon * 2.0)
2123        let price_tolerance = (s * 5e-5).max(1e-4) * 2.0;
2124        assert!(
2125            (refined_greeks.price - target_price).abs() < price_tolerance,
2126            "Refined price should match target: {} vs {}",
2127            refined_greeks.price,
2128            target_price
2129        );
2130
2131        // The refined vol should converge towards the initial vol
2132        assert!(
2133            refined_vol < refined_greeks.vol && refined_greeks.vol < initial_vol * 1.1,
2134            "Refined vol should converge towards initial: {} (initial: {}, refined: {})",
2135            refined_greeks.vol,
2136            initial_vol,
2137            refined_vol
2138        );
2139    }
2140
2141    #[rstest]
2142    fn test_imply_vol_and_greeks_accuracy_put() {
2143        let s = 100.0;
2144        let k = 100.1;
2145        let t = 1.0;
2146        let r = 0.01;
2147        let b = 0.005;
2148        let vol = 0.2;
2149        let is_call = false;
2150
2151        let base_greeks = black_scholes_greeks(s, r, b, vol, is_call, k, t);
2152        let price = base_greeks.price;
2153
2154        let implied_result = imply_vol_and_greeks(s, r, b, is_call, k, t, price);
2155
2156        // Tolerance relaxed due to numerical precision differences
2157        let tolerance = 2e-4;
2158        assert!(
2159            (implied_result.vol - vol).abs() < tolerance,
2160            "Vol difference exceeds tolerance: {} vs {}",
2161            implied_result.vol,
2162            vol
2163        );
2164        assert!(
2165            (implied_result.price - base_greeks.price).abs() < tolerance,
2166            "Price difference exceeds tolerance: {} vs {}",
2167            implied_result.price,
2168            base_greeks.price
2169        );
2170        assert!(
2171            (implied_result.delta - base_greeks.delta).abs() < tolerance,
2172            "Delta difference exceeds tolerance: {} vs {}",
2173            implied_result.delta,
2174            base_greeks.delta
2175        );
2176        assert!(
2177            (implied_result.gamma - base_greeks.gamma).abs() < tolerance,
2178            "Gamma difference exceeds tolerance: {} vs {}",
2179            implied_result.gamma,
2180            base_greeks.gamma
2181        );
2182        assert!(
2183            (implied_result.vega - base_greeks.vega).abs() < tolerance,
2184            "Vega difference exceeds tolerance: {} vs {}",
2185            implied_result.vega,
2186            base_greeks.vega
2187        );
2188        assert!(
2189            (implied_result.theta - base_greeks.theta).abs() < tolerance,
2190            "Theta difference exceeds tolerance: {} vs {}",
2191            implied_result.theta,
2192            base_greeks.theta
2193        );
2194    }
2195
2196    // Parameterized tests comparing black_scholes_greeks against black_scholes_greeks_exact
2197    // Testing three moneyness levels (OTM, ATM, ITM) and both call and put options
2198    #[rstest]
2199    fn test_black_scholes_greeks_vs_exact(
2200        #[values(90.0, 100.0, 110.0)] spot: f64,
2201        #[values(true, false)] is_call: bool,
2202        #[values(0.15, 0.25, 0.5)] vol: f64,
2203        #[values(0.01, 0.25, 2.0)] t: f64,
2204    ) {
2205        let r = 0.05;
2206        let b = 0.05;
2207        let k = 100.0;
2208
2209        let greeks_fast = black_scholes_greeks(spot, r, b, vol, is_call, k, t);
2210        let greeks_exact = black_scholes_greeks_exact(spot, r, b, vol, is_call, k, t);
2211
2212        // Verify ~7 significant decimals precision using relative error checks
2213        // For 7 significant decimals: relative error < 5e-6 (accounts for f32 intermediate calculations)
2214        // Use max(|exact|, 1e-10) to avoid division by zero for very small values
2215        // Very short expiry (0.01) can have slightly larger relative errors due to numerical precision
2216        let rel_tolerance = if t < 0.1 {
2217            1e-4 // More lenient for very short expiry (~5 significant decimals)
2218        } else {
2219            8e-6 // Standard tolerance for normal/long expiry (~6.1 significant decimals)
2220        };
2221        let abs_tolerance = 1e-10; // Minimum absolute tolerance for near-zero values
2222
2223        // Check relative error with seven significant decimal places
2224        let check_7_sig_figs = |fast: f64, exact: f64, name: &str| {
2225            let abs_diff = (fast - exact).abs();
2226            // For very small values (near zero), use absolute tolerance instead of relative
2227            // This handles cases with very short expiry where values can be very close to zero
2228            // Use a threshold of 1e-4 for "very small" values
2229            let small_value_threshold = 1e-4;
2230            let max_allowed = if exact.abs() < small_value_threshold {
2231                // Both values are very small, use absolute tolerance (more lenient for very small values)
2232                if t < 0.1 {
2233                    1e-5 // Very lenient for very short expiry with small values
2234                } else {
2235                    1e-6 // Standard absolute tolerance for small values
2236                }
2237            } else {
2238                // Use relative tolerance
2239                exact.abs().max(abs_tolerance) * rel_tolerance
2240            };
2241            let rel_diff = if exact.abs() > abs_tolerance {
2242                abs_diff / exact.abs()
2243            } else {
2244                0.0 // Both near zero, difference is acceptable
2245            };
2246
2247            assert!(
2248                abs_diff < max_allowed,
2249                "{name} mismatch for spot={spot}, is_call={is_call}, vol={vol}, t={t}: fast={fast:.10}, exact={exact:.10}, abs_diff={abs_diff:.2e}, rel_diff={rel_diff:.2e}, max_allowed={max_allowed:.2e}"
2250            );
2251        };
2252
2253        check_7_sig_figs(greeks_fast.price, greeks_exact.price, "Price");
2254        check_7_sig_figs(greeks_fast.delta, greeks_exact.delta, "Delta");
2255        check_7_sig_figs(greeks_fast.gamma, greeks_exact.gamma, "Gamma");
2256        check_7_sig_figs(greeks_fast.vega, greeks_exact.vega, "Vega");
2257        check_7_sig_figs(greeks_fast.theta, greeks_exact.theta, "Theta");
2258    }
2259
2260    // Parameterized tests comparing refine_vol_and_greeks against imply_vol_and_greeks
2261    // Testing that both methods recover the target volatility and produce similar greeks
2262    #[rstest]
2263    fn test_refine_vol_and_greeks_vs_imply_vol_and_greeks(
2264        #[values(90.0, 100.0, 110.0)] spot: f64,
2265        #[values(true, false)] is_call: bool,
2266        #[values(0.15, 0.25, 0.5)] target_vol: f64,
2267        #[values(0.01, 0.25, 2.0)] t: f64,
2268    ) {
2269        let r = 0.05;
2270        let b = 0.05;
2271        let k = 100.0;
2272
2273        // Compute the theoretical price using the target volatility
2274        let base_greeks = black_scholes_greeks(spot, r, b, target_vol, is_call, k, t);
2275        let target_price = base_greeks.price;
2276
2277        // Initial guess is 0.01 below the target vol
2278        let initial_guess = target_vol - 0.01;
2279
2280        // Recover volatility using refine_vol_and_greeks
2281        let refined_result =
2282            refine_vol_and_greeks(spot, r, b, is_call, k, t, target_price, initial_guess);
2283
2284        // Recover volatility using imply_vol_and_greeks
2285        let implied_result = imply_vol_and_greeks(spot, r, b, is_call, k, t, target_price);
2286
2287        // Detect deep ITM/OTM options (more than 5% away from ATM)
2288        // These are especially challenging for imply_vol with very short expiry
2289        let moneyness = (spot - k) / k;
2290        let is_deep_itm_otm = moneyness.abs() > 0.05;
2291        let is_deep_edge_case = t < 0.1 && is_deep_itm_otm;
2292
2293        // Verify both methods recover the target volatility
2294        // refine_vol_and_greeks uses a single Halley iteration, so convergence may be limited
2295        // Initial guess is 0.01 below target, which should provide reasonable convergence
2296        // Very short (0.01) or very long (2.0) expiry can make convergence more challenging
2297        // Deep ITM/OTM with very short expiry is especially problematic for imply_vol
2298        let vol_abs_tolerance = 1e-6;
2299        let vol_rel_tolerance = if is_deep_edge_case {
2300            // Deep ITM/OTM with very short expiry: imply_vol often fails, use very lenient tolerance
2301            2.0 // Very lenient to effectively skip when imply_vol fails for these edge cases
2302        } else if t < 0.1 {
2303            // Very short expiry: convergence is more challenging
2304            0.10 // Lenient for short expiry
2305        } else if t > 1.5 {
2306            // Very long expiry: convergence can be challenging
2307            if target_vol <= 0.15 {
2308                0.05 // Moderate tolerance for 0.15 vol with long expiry
2309            } else {
2310                0.01 // Moderate tolerance for higher vols with long expiry
2311            }
2312        } else {
2313            // Normal expiry (0.25-1.5): use standard tolerances
2314            if target_vol <= 0.15 {
2315                0.05 // Moderate tolerance for 0.15 vol
2316            } else {
2317                0.001 // Tighter tolerance for higher vols (0.1% relative error)
2318            }
2319        };
2320
2321        let refined_vol_error = (refined_result.vol - target_vol).abs();
2322        let implied_vol_error = (implied_result.vol - target_vol).abs();
2323        let refined_vol_rel_error = refined_vol_error / target_vol.max(vol_abs_tolerance);
2324        let implied_vol_rel_error = implied_vol_error / target_vol.max(vol_abs_tolerance);
2325
2326        assert!(
2327            refined_vol_rel_error < vol_rel_tolerance,
2328            "Refined vol mismatch for spot={}, is_call={}, target_vol={}, t={}: refined={:.10}, target={:.10}, abs_error={:.2e}, rel_error={:.2e}",
2329            spot,
2330            is_call,
2331            target_vol,
2332            t,
2333            refined_result.vol,
2334            target_vol,
2335            refined_vol_error,
2336            refined_vol_rel_error
2337        );
2338
2339        // For very short expiry, imply_vol may fail (return 0.0 or very wrong value), so use very lenient tolerance
2340        // Deep ITM/OTM with very short expiry is especially problematic
2341        let implied_vol_tolerance = if is_deep_edge_case {
2342            // Deep ITM/OTM with very short expiry: imply_vol often fails
2343            2.0 // Very lenient to effectively skip
2344        } else if implied_result.vol < 1e-6 {
2345            // imply_vol failed (returned 0.0), skip this check
2346            2.0 // Very lenient to effectively skip (allow 100%+ error)
2347        } else if t < 0.1 && (implied_result.vol - target_vol).abs() / target_vol.max(1e-6) > 0.5 {
2348            // For very short expiry, if implied vol is way off (>50% error), imply_vol likely failed
2349            2.0 // Very lenient to effectively skip
2350        } else {
2351            vol_rel_tolerance
2352        };
2353
2354        assert!(
2355            implied_vol_rel_error < implied_vol_tolerance,
2356            "Implied vol mismatch for spot={}, is_call={}, target_vol={}, t={}: implied={:.10}, target={:.10}, abs_error={:.2e}, rel_error={:.2e}",
2357            spot,
2358            is_call,
2359            target_vol,
2360            t,
2361            implied_result.vol,
2362            target_vol,
2363            implied_vol_error,
2364            implied_vol_rel_error
2365        );
2366
2367        // Verify greeks from both methods are close (6 decimals precision)
2368        // Note: Since refine_vol_and_greeks may not fully converge, the recovered vols may differ slightly,
2369        // which will cause the greeks to differ. Use adaptive tolerance based on vol recovery quality and expiry.
2370        let greeks_abs_tolerance = 1e-10;
2371
2372        // Detect deep ITM/OTM options (more than 5% away from ATM)
2373        let moneyness = (spot - k) / k;
2374        let is_deep_itm_otm = moneyness.abs() > 0.05;
2375        let is_deep_edge_case = t < 0.1 && is_deep_itm_otm;
2376
2377        // Use more lenient tolerance for low vols and extreme expiry where convergence is more challenging
2378        // All greeks are sensitive to vol differences at low vols and extreme expiry
2379        // Deep ITM/OTM with very short expiry is especially challenging for imply_vol
2380        let greeks_rel_tolerance = if is_deep_edge_case {
2381            // Deep ITM/OTM with very short expiry: imply_vol often fails, use very lenient tolerance
2382            1.0 // Very lenient to effectively skip when imply_vol fails for these edge cases
2383        } else if t < 0.1 {
2384            // Very short expiry: greeks are very sensitive
2385            if target_vol <= 0.15 {
2386                0.10 // Lenient for 0.15 vol with short expiry
2387            } else {
2388                0.05 // Lenient for higher vols with short expiry
2389            }
2390        } else if t > 1.5 {
2391            // Very long expiry: greeks can be sensitive
2392            if target_vol <= 0.15 {
2393                0.08 // More lenient for 0.15 vol with long expiry
2394            } else {
2395                0.01 // Moderate tolerance for higher vols with long expiry
2396            }
2397        } else {
2398            // Normal expiry (0.25-1.5): use standard tolerances
2399            if target_vol <= 0.15 {
2400                0.05 // Moderate tolerance for 0.15 vol
2401            } else {
2402                2e-3 // Tolerance for higher vols (~2.5 significant decimals)
2403            }
2404        };
2405
2406        // Check relative error with six decimal places
2407        // Gamma is more sensitive to vol differences, so use more lenient tolerance
2408        // If imply_vol failed (vol < 1e-6 or way off for short expiry), the greeks may be wrong, so skip comparison
2409        // Deep ITM/OTM with very short expiry is especially problematic
2410        let imply_vol_failed = implied_result.vol < 1e-6
2411            || (t < 0.1 && (implied_result.vol - target_vol).abs() / target_vol.max(1e-6) > 0.5)
2412            || is_deep_edge_case;
2413        let effective_greeks_tolerance = if imply_vol_failed || is_deep_edge_case {
2414            1.0 // Very lenient to effectively skip when imply_vol fails or for deep ITM/OTM edge cases
2415        } else {
2416            greeks_rel_tolerance
2417        };
2418
2419        let check_6_sig_figs = |refined: f64, implied: f64, name: &str, is_gamma: bool| {
2420            // Skip check if imply_vol failed and greeks contain NaN, invalid values, or very small values
2421            // Also skip for deep ITM/OTM with very short expiry where imply_vol is unreliable
2422            if (imply_vol_failed || is_deep_edge_case)
2423                && (!implied.is_finite() || implied.abs() < 1e-4 || refined.abs() < 1e-4)
2424            {
2425                return; // Skip this check when imply_vol fails or for deep ITM/OTM edge cases
2426            }
2427
2428            let abs_diff = (refined - implied).abs();
2429            // If both values are very small, use absolute tolerance instead of relative
2430            // For deep ITM/OTM with short expiry, use more lenient absolute tolerance
2431            let small_value_threshold = if is_deep_edge_case { 1e-3 } else { 1e-6 };
2432            let rel_diff =
2433                if implied.abs() < small_value_threshold && refined.abs() < small_value_threshold {
2434                    0.0 // Both near zero, difference is acceptable
2435                } else {
2436                    abs_diff / implied.abs().max(greeks_abs_tolerance)
2437                };
2438            // Gamma is more sensitive, use higher multiplier for it, especially for low vols and extreme expiry
2439            let gamma_multiplier = if (0.1..=1.5).contains(&t) {
2440                // Normal expiry
2441                if target_vol <= 0.15 { 5.0 } else { 3.0 }
2442            } else {
2443                // Extreme expiry: gamma is very sensitive
2444                if target_vol <= 0.15 { 10.0 } else { 5.0 }
2445            };
2446            let tolerance = if is_gamma {
2447                effective_greeks_tolerance * gamma_multiplier
2448            } else {
2449                effective_greeks_tolerance
2450            };
2451            // For deep ITM/OTM with very short expiry and very small values, use absolute tolerance
2452            let max_allowed = if is_deep_edge_case && implied.abs() < 1e-3 {
2453                2e-5 // Very lenient absolute tolerance for deep edge cases with small values
2454            } else {
2455                implied.abs().max(greeks_abs_tolerance) * tolerance
2456            };
2457
2458            assert!(
2459                abs_diff < max_allowed,
2460                "{name} mismatch between refine and imply for spot={spot}, is_call={is_call}, target_vol={target_vol}, t={t}: refined={refined:.10}, implied={implied:.10}, abs_diff={abs_diff:.2e}, rel_diff={rel_diff:.2e}, max_allowed={max_allowed:.2e}"
2461            );
2462        };
2463
2464        check_6_sig_figs(refined_result.price, implied_result.price, "Price", false);
2465        check_6_sig_figs(refined_result.delta, implied_result.delta, "Delta", false);
2466        check_6_sig_figs(refined_result.gamma, implied_result.gamma, "Gamma", true);
2467        check_6_sig_figs(refined_result.vega, implied_result.vega, "Vega", false);
2468        check_6_sig_figs(refined_result.theta, implied_result.theta, "Theta", false);
2469    }
2470
2471    #[rstest]
2472    #[case(true, 1.0, 0.437_729_301_518)]
2473    #[case(false, 1.0, -0.513_500_122_983)]
2474    #[case(true, 0.0, -0.075_770_821_464)]
2475    #[case(false, 0.0, -0.075_770_821_464)]
2476    fn test_checked_greeks_rho_at_zero_carry(
2477        #[case] is_call: bool,
2478        #[case] db_dr: f64,
2479        #[case] expected: f64,
2480    ) {
2481        let result =
2482            black_scholes_greeks_checked(100.0, 0.05, 0.0, 0.2, is_call, 100.0, 1.0, db_dr)
2483                .unwrap();
2484        assert!((result.rho - expected).abs() < 1e-6);
2485        assert_eq!(result.greeks().rho, result.rho);
2486        let raw = black_scholes_greeks(100.0, 0.05, 0.0, 0.2, is_call, 100.0, 1.0);
2487        assert_eq!(
2488            result,
2489            BlackScholesGreeksResult {
2490                rho: result.rho,
2491                ..raw
2492            }
2493        );
2494    }
2495
2496    #[rstest]
2497    #[case(0, 0.0, "underlying price")]
2498    #[case(0, -1.0, "underlying price")]
2499    #[case(0, f64::INFINITY, "underlying price")]
2500    #[case(0, f64::MIN_POSITIVE, "underlying price")]
2501    #[case(0, f64::MAX, "underlying price")]
2502    #[case(1, f64::NAN, "interest rate")]
2503    #[case(2, f64::INFINITY, "cost of carry")]
2504    #[case(3, 0.0, "volatility")]
2505    #[case(3, -0.2, "volatility")]
2506    #[case(3, f64::NAN, "volatility")]
2507    #[case(4, 0.0, "strike")]
2508    #[case(4, -100.0, "strike")]
2509    #[case(5, 0.0, "time to expiry")]
2510    #[case(5, -1.0, "time to expiry")]
2511    fn test_checked_greeks_reject_invalid_inputs(
2512        #[case] index: usize,
2513        #[case] value: f64,
2514        #[case] expected: &'static str,
2515    ) {
2516        let mut inputs = [100.0, 0.05, 0.03, 0.2, 110.0, 0.5];
2517        inputs[index] = value;
2518        let [s, r, b, vol, k, t] = inputs;
2519        assert_eq!(
2520            black_scholes_greeks_checked(s, r, b, vol, true, k, t, 1.0),
2521            Err(OptionValuationError::InvalidInput(expected))
2522        );
2523    }
2524
2525    #[rstest]
2526    #[case(true, 0.0)]
2527    #[case(true, 100.0)]
2528    #[case(true, 200.0)]
2529    #[case(false, 0.0)]
2530    #[case(false, 100.0)]
2531    #[case(false, 200.0)]
2532    fn test_checked_iv_rejects_zero_and_unattainable_premiums(
2533        #[case] is_call: bool,
2534        #[case] price: f64,
2535    ) {
2536        let expected = if price == 0.0 {
2537            OptionValuationError::InvalidInput("option price")
2538        } else {
2539            OptionValuationError::ImpliedVolatilityUnavailable
2540        };
2541
2542        assert_eq!(
2543            imply_vol_and_greeks_checked(100.0, 0.0, 0.0, is_call, 100.0, 1.0, price, 1.0, None),
2544            Err(expected)
2545        );
2546    }
2547
2548    #[rstest]
2549    #[case(1e-8)]
2550    #[case(0.21)]
2551    #[case(10.0)]
2552    fn test_checked_iv_refinement_falls_back_without_fabricated_volatility(#[case] seed: f64) {
2553        let raw = black_scholes_greeks(100.0, 0.05, 0.0, 0.2, true, 100.0, 1.0);
2554        let result = imply_vol_and_greeks_checked(
2555            100.0,
2556            0.05,
2557            0.0,
2558            true,
2559            100.0,
2560            1.0,
2561            raw.price,
2562            1.0,
2563            Some(seed),
2564        )
2565        .unwrap();
2566        assert!((result.vol - 0.2).abs() < 1e-5);
2567        assert!((result.price - raw.price).abs() < 1e-4);
2568        assert!((result.rho - 0.437_729_301_518).abs() < 1e-6);
2569    }
2570
2571    #[rstest]
2572    fn test_checked_greeks_rejects_nonfinite_kernel_results() {
2573        assert_eq!(
2574            black_scholes_greeks_checked(100.0, 0.05, 1000.0, 0.2, true, 100.0, 1.0, 1.0),
2575            Err(OptionValuationError::InvalidResult)
2576        );
2577    }
2578
2579    #[rstest]
2580    fn test_checked_iv_accepts_a_premium_the_fast_kernel_cannot_reprice() {
2581        let result =
2582            imply_vol_and_greeks_checked(100.0, 0.05, 0.05, true, 200.0, 1.0, 1e-10, 0.0, None)
2583                .unwrap();
2584        assert!((result.price - 1e-10).abs() < 1e-14);
2585        assert_eq!(
2586            result,
2587            black_scholes_greeks_exact(100.0, 0.05, 0.05, result.vol, true, 200.0, 1.0)
2588        );
2589    }
2590
2591    #[rstest]
2592    #[case(f64::NAN)]
2593    #[case(f64::INFINITY)]
2594    fn test_checked_greeks_rejects_nonfinite_carry_sensitivity(#[case] db_dr: f64) {
2595        assert_eq!(
2596            black_scholes_greeks_checked(100.0, 0.05, 0.0, 0.2, true, 100.0, 1.0, db_dr),
2597            Err(OptionValuationError::InvalidInput("carry rate sensitivity"))
2598        );
2599    }
2600
2601    #[rstest]
2602    fn test_checked_iv_does_not_accept_a_clamped_deep_itm_refinement() {
2603        let result = imply_vol_and_greeks_checked(
2604            200.0,
2605            0.0,
2606            0.0,
2607            true,
2608            100.0,
2609            1.0,
2610            100.000_001,
2611            1.0,
2612            Some(1e-8),
2613        )
2614        .unwrap();
2615        assert!((result.vol - 0.138_406_809_897_693_3).abs() < 1e-12);
2616    }
2617
2618    #[rstest]
2619    #[case(true, 0.460_172_162_723)]
2620    #[case(false, -0.539_827_837_277)]
2621    fn test_checked_greeks_rho_at_zero_rates(#[case] is_call: bool, #[case] expected: f64) {
2622        let result =
2623            black_scholes_greeks_checked(100.0, 0.0, 0.0, 0.2, is_call, 100.0, 1.0, 1.0).unwrap();
2624        assert!((result.rho - expected).abs() < 1e-6);
2625    }
2626
2627    #[rstest]
2628    #[case(0.0)]
2629    #[case(0.4)]
2630    #[case(1.0)]
2631    fn test_checked_greeks_rho_matches_independent_rate_bumps(#[case] db_dr: f64) {
2632        let result =
2633            black_scholes_greeks_checked(110.0, 0.05, 0.03, 0.25, true, 105.0, 0.75, db_dr)
2634                .unwrap();
2635        let epsilon = 1e-5;
2636        let high = black_scholes_greeks_exact(
2637            110.0,
2638            0.05 + epsilon,
2639            0.03 + db_dr * epsilon,
2640            0.25,
2641            true,
2642            105.0,
2643            0.75,
2644        );
2645        let low = black_scholes_greeks_exact(
2646            110.0,
2647            0.05 - epsilon,
2648            0.03 - db_dr * epsilon,
2649            0.25,
2650            true,
2651            105.0,
2652            0.75,
2653        );
2654        let reference = (high.price - low.price) / (2.0 * epsilon) * 0.01;
2655        assert!((result.rho - reference).abs() < 1e-6);
2656    }
2657
2658    #[rstest]
2659    fn test_checked_greeks_rho_is_stable_for_deep_itm_calls() {
2660        let result =
2661            black_scholes_greeks_checked(1e20, 0.05, 0.0, 0.2, true, 100.0, 1.0, 1.0).unwrap();
2662        assert!((result.rho - 0.951_229_424_500_714).abs() < 1e-12);
2663    }
2664
2665    #[rstest]
2666    fn test_checked_implied_volatility_preserves_a_tiny_premium_solution() {
2667        let vol = imply_vol_checked(100.0, 0.05, 0.05, true, 200.0, 1.0, 1e-10).unwrap();
2668        assert!((vol - 0.099_420_823_233_839_27).abs() < 1e-12);
2669    }
2670
2671    #[rstest]
2672    fn test_checked_iv_does_not_accept_the_upper_refinement_clamp() {
2673        let result = imply_vol_and_greeks_checked(
2674            100.0,
2675            0.0,
2676            0.0,
2677            true,
2678            100.0,
2679            1.0,
2680            99.99998,
2681            1.0,
2682            Some(10.0),
2683        )
2684        .unwrap();
2685        assert!((result.vol - 10.398_675_164_168_564).abs() < 1e-12);
2686    }
2687
2688    #[rstest]
2689    #[case(100.0, 0.0)]
2690    #[case(100.0, 100.0)]
2691    #[case(100.0, 200.0)]
2692    #[case(0.0, 10.0)]
2693    fn test_checked_implied_volatility_rejects_invalid_or_unavailable_solutions(
2694        #[case] spot: f64,
2695        #[case] price: f64,
2696    ) {
2697        assert_eq!(
2698            imply_vol_checked(spot, 0.0, 0.0, true, 100.0, 1.0, price),
2699            Err(OptionValuationError::ImpliedVolatilityUnavailable)
2700        );
2701    }
2702
2703    #[rstest]
2704    fn test_checked_iv_accepts_valid_index_option_premium() {
2705        let strike = 5085.0;
2706        let time = 1.0 / 365.25;
2707        let vol = 0.141;
2708        let target = black_scholes_greeks_exact(5000.0, 0.0425, 0.0, vol, true, strike, time);
2709        let result = imply_vol_and_greeks_checked(
2710            5000.0,
2711            0.0425,
2712            0.0,
2713            true,
2714            strike,
2715            time,
2716            target.price,
2717            0.0,
2718            None,
2719        )
2720        .unwrap();
2721        assert!((result.vol - vol).abs() < 1e-10);
2722        assert_eq!(
2723            result,
2724            black_scholes_greeks_exact(5000.0, 0.0425, 0.0, result.vol, true, strike, time)
2725        );
2726    }
2727
2728    #[rstest]
2729    fn test_checked_greeks_accepts_valid_tail_after_spot_shock() {
2730        let result = black_scholes_greeks_checked(
2731            4593.0,
2732            0.0425,
2733            0.0,
2734            0.14,
2735            true,
2736            5100.0,
2737            7.0 / 365.25,
2738            0.0,
2739        )
2740        .unwrap();
2741        assert_eq!(
2742            result,
2743            black_scholes_greeks_exact(4593.0, 0.0425, 0.0, 0.14, true, 5100.0, 7.0 / 365.25)
2744        );
2745    }
2746
2747    #[rstest]
2748    fn test_checked_iv_rejects_a_premium_neither_kernel_can_reprice() {
2749        let vol = imply_vol_checked(100.0, 0.0, 0.0, true, 100.0, 1.0, 1e-12).unwrap();
2750        assert!((vol - 2.506_628_274_631_000_4e-14).abs() < 1e-27);
2751        assert_eq!(
2752            imply_vol_and_greeks_checked(100.0, 0.0, 0.0, true, 100.0, 1.0, 1e-12, 0.0, None),
2753            Err(OptionValuationError::InvalidResult)
2754        );
2755    }
2756}