libitofin 0.6.1

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Monte Carlo European-option engine.
//!
//! Port of `ql/pricingengines/vanilla/mceuropeanengine.hpp`: the concrete
//! Monte Carlo engine for European vanilla options. It embeds the [`#451`]
//! [`McVanillaEngineBase`], builds a [`EuropeanPathPricer`] from the option's
//! payoff and the process discount factor (`mceuropeanengine.hpp:132-153`), and
//! delegates the simulation to [`McVanillaEngineBase::run`]. The
//! [`MakeMcEuropeanEngine`] builder ports the C++ `MakeMCEuropeanEngine`
//! factory (`mceuropeanengine.hpp:70`).
//!
//! Divergences from `mceuropeanengine.hpp`, all deliberate:
//! - **concrete Black-Scholes process**: C++ holds a generic
//!   `StochasticProcess` and `dynamic_pointer_cast`s to
//!   `GeneralizedBlackScholesProcess` in `pathPricer()`
//!   (`mceuropeanengine.hpp:142-145`, "Black-Scholes process required"). The
//!   engine here holds a `Shared<GeneralizedBlackScholesProcess>` concretely, so
//!   that downcast is a compile-time fact and cannot fail at run time. The base
//!   still sees the process erased to `dyn StochasticProcess1D`.
//! - **payoff downcast stays a run-time guard**: the option's payoff is an
//!   erased `StrikedTypePayoff`, so the C++ "non-plain payoff given" downcast
//!   (`mceuropeanengine.hpp:137-140`) survives as a run-time `Err` in
//!   [`calculate`](MCEuropeanEngine::calculate), mirroring
//!   [`AnalyticEuropeanEngine`](crate::pricingengines::vanilla::AnalyticEuropeanEngine).
//!
//! Deferred, rejected visibly rather than silently ignored:
//! - **antithetic variate**: the C++ builder's `withAntitheticVariate`
//!   (`mceuropeanengine.hpp:81`) is kept as
//!   [`with_antithetic_variate`](MakeMcEuropeanEngine::with_antithetic_variate),
//!   but requesting it makes [`build`](MakeMcEuropeanEngine::build) return `Err`
//!   (the underlying [`McSimulation`](crate::methods::montecarlo) defers it).
//!   This is an Err-at-build, one step earlier than the base's Err-at-run
//!   precedent; the failure is visible either way (#262 class).
//! - **Brownian bridge / control variate**: the C++ builder's
//!   `withBrownianBridge` (`mceuropeanengine.hpp:76`) and the control-variate
//!   machinery are omitted from the builder entirely; the base is always driven
//!   with both flags `false`.
//!
//! Oracle note (divergence catalogue): the MC-vs-analytic test in this module
//! INTENTIONALLY STRENGTHENS QuantLib's own `0.01 * underlying` relative band
//! (`test-suite/europeanoption.cpp:1278`) into the tighter `|mc - analytic| <
//! 3 * error_estimate()` convergence pin, which ties the tolerance to the
//! computed standard error instead of a loose absolute band.

use std::any::Any;

use crate::errors::QlResult;
use crate::exercise::ExerciseType;
use crate::instruments::{PlainVanillaPayoff, StrikedTypePayoff, TypePayoff};
use crate::math::randomnumbers::rngtraits::McRngTraits;
use crate::methods::montecarlo::{Path, PathPricer};
use crate::option::OptionType;
use crate::patterns::observable::{AsObservable, Observable};
use crate::payoff::Payoff;
use crate::pricingengine::{Arguments, PricingEngine, Results};
use crate::pricingengines::vanilla::McVanillaEngineBase;
use crate::processes::GeneralizedBlackScholesProcess;
use crate::shared::Shared;
use crate::stochasticprocess::StochasticProcess1D;
use crate::types::{DiscountFactor, Real, Size};
use crate::{fail, require};

/// Prices one realized [`Path`] as the discounted terminal payoff
/// (`mceuropeanengine.hpp:93,254-257`): `payoff(path.back()) * discount`.
pub struct EuropeanPathPricer {
    payoff: PlainVanillaPayoff,
    discount: DiscountFactor,
}

impl EuropeanPathPricer {
    /// Builds the pricer from the option type, strike, and terminal discount
    /// factor (`mceuropeanengine.hpp:246-252`).
    ///
    /// # Errors
    ///
    /// Errors if `strike` is negative (`mceuropeanengine.hpp:250`).
    #[allow(clippy::neg_cmp_op_on_partial_ord)]
    pub fn new(
        option_type: OptionType,
        strike: Real,
        discount: DiscountFactor,
    ) -> QlResult<EuropeanPathPricer> {
        require!(strike >= 0.0, "strike less than zero not allowed");
        Ok(EuropeanPathPricer {
            payoff: PlainVanillaPayoff::new(option_type, strike),
            discount,
        })
    }
}

impl PathPricer<Path> for EuropeanPathPricer {
    /// The discounted terminal payoff (`mceuropeanengine.hpp:254-257`). The C++
    /// `QL_REQUIRE(!path.empty())` guard is unnecessary: the base always builds
    /// a non-empty path from a grid with at least one step.
    fn price(&self, path: &Path) -> Real {
        self.payoff.value(path.back()) * self.discount
    }
}

/// Monte Carlo pricing engine for European vanilla options
/// (`mceuropeanengine.hpp:42`), generic over the RNG policy `RNG`.
pub struct MCEuropeanEngine<RNG> {
    base: McVanillaEngineBase<RNG>,
    process: Shared<GeneralizedBlackScholesProcess>,
}

impl<RNG: McRngTraits> MCEuropeanEngine<RNG> {
    /// Builds the engine (`mceuropeanengine.hpp:110-129`). Prefer
    /// [`MakeMcEuropeanEngine`] for the validated, ergonomic construction path.
    ///
    /// # Errors
    ///
    /// Propagates the [`McVanillaEngineBase::new`] time-step validation.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        process: Shared<GeneralizedBlackScholesProcess>,
        time_steps: Option<Size>,
        time_steps_per_year: Option<Size>,
        brownian_bridge: bool,
        antithetic_variate: bool,
        required_samples: Option<Size>,
        required_tolerance: Option<Real>,
        max_samples: Option<Size>,
        seed: u32,
    ) -> QlResult<MCEuropeanEngine<RNG>> {
        let base = McVanillaEngineBase::new(
            Shared::clone(&process) as Shared<dyn StochasticProcess1D>,
            time_steps,
            time_steps_per_year,
            brownian_bridge,
            antithetic_variate,
            false,
            required_samples,
            required_tolerance,
            max_samples,
            seed,
        )?;
        Ok(MCEuropeanEngine { base, process })
    }
}

impl<RNG: McRngTraits> AsObservable for MCEuropeanEngine<RNG> {
    fn observable(&self) -> &Observable {
        self.base.observable()
    }
}

impl<RNG: McRngTraits> PricingEngine for MCEuropeanEngine<RNG> {
    fn arguments_mut(&mut self) -> &mut dyn Arguments {
        self.base.arguments_mut()
    }

    fn results(&self) -> &dyn Results {
        self.base.results()
    }

    fn reset(&mut self) {
        self.base.reset();
    }

    /// Builds the [`EuropeanPathPricer`] (`mceuropeanengine.hpp:132-153`) and
    /// runs the simulation through the base.
    ///
    /// # Errors
    ///
    /// Errors on a missing/non-European exercise, a missing or non-plain payoff,
    /// or any propagated grid/discount/simulation failure.
    fn calculate(&mut self) -> QlResult<()> {
        let arguments = self.base.arguments();
        let Some(exercise) = &arguments.exercise else {
            fail!("no exercise given");
        };
        if exercise.exercise_type() != ExerciseType::European {
            fail!("not an European option");
        }
        let Some(payoff) = &arguments.payoff else {
            fail!("no payoff given");
        };
        let payoff: &dyn StrikedTypePayoff = &**payoff;
        let Some(payoff) = (payoff as &dyn Any).downcast_ref::<PlainVanillaPayoff>() else {
            fail!("non-plain payoff given");
        };
        let option_type = payoff.option_type();
        let strike = payoff.strike();

        let grid = self.base.time_grid()?;
        let Some(last_time) = grid.back() else {
            fail!("empty time grid");
        };
        let discount = self
            .process
            .risk_free_rate()
            .current_link()?
            .discount(last_time, false)?;

        let pricer = EuropeanPathPricer::new(option_type, strike, discount)?;
        self.base.run(pricer)
    }
}

/// Factory for [`MCEuropeanEngine`] (`mceuropeanengine.hpp:70`), generic over the
/// RNG policy `RNG`.
///
/// Validation the C++ builder splits across its setters is deferred to
/// [`build`](MakeMcEuropeanEngine::build) so the setters stay infallible and
/// chainable.
pub struct MakeMcEuropeanEngine<RNG> {
    process: Shared<GeneralizedBlackScholesProcess>,
    steps: Option<Size>,
    steps_per_year: Option<Size>,
    samples: Option<Size>,
    max_samples: Option<Size>,
    tolerance: Option<Real>,
    antithetic: bool,
    seed: u32,
    _rng: std::marker::PhantomData<RNG>,
}

impl<RNG: McRngTraits> MakeMcEuropeanEngine<RNG> {
    /// Starts a builder on the given Black-Scholes process
    /// (`mceuropeanengine.hpp:157-160`).
    pub fn new(process: Shared<GeneralizedBlackScholesProcess>) -> MakeMcEuropeanEngine<RNG> {
        MakeMcEuropeanEngine {
            process,
            steps: None,
            steps_per_year: None,
            samples: None,
            max_samples: None,
            tolerance: None,
            antithetic: false,
            seed: 0,
            _rng: std::marker::PhantomData,
        }
    }

    /// Sets the fixed number of time steps (`mceuropeanengine.hpp:164`).
    #[must_use]
    pub fn with_steps(mut self, steps: Size) -> Self {
        self.steps = Some(steps);
        self
    }

    /// Sets the number of time steps per year (`mceuropeanengine.hpp:171`).
    #[must_use]
    pub fn with_steps_per_year(mut self, steps: Size) -> Self {
        self.steps_per_year = Some(steps);
        self
    }

    /// Sets the required number of samples (`mceuropeanengine.hpp:178`).
    #[must_use]
    pub fn with_samples(mut self, samples: Size) -> Self {
        self.samples = Some(samples);
        self
    }

    /// Sets the required absolute tolerance (`mceuropeanengine.hpp:187`).
    #[must_use]
    pub fn with_absolute_tolerance(mut self, tolerance: Real) -> Self {
        self.tolerance = Some(tolerance);
        self
    }

    /// Sets the maximum number of samples (`mceuropeanengine.hpp:199`).
    #[must_use]
    pub fn with_max_samples(mut self, samples: Size) -> Self {
        self.max_samples = Some(samples);
        self
    }

    /// Sets the RNG seed (`mceuropeanengine.hpp:206`).
    #[must_use]
    pub fn with_seed(mut self, seed: u32) -> Self {
        self.seed = seed;
        self
    }

    /// Requests the antithetic-variate variance reduction
    /// (`mceuropeanengine.hpp:220`). Deferred: setting `true` makes
    /// [`build`](MakeMcEuropeanEngine::build) return `Err`.
    #[must_use]
    pub fn with_antithetic_variate(mut self, antithetic: bool) -> Self {
        self.antithetic = antithetic;
        self
    }

    /// Builds the configured [`MCEuropeanEngine`]
    /// (`mceuropeanengine.hpp:225-242`).
    ///
    /// # Errors
    ///
    /// Errors if neither or both of `steps`/`steps_per_year` are set
    /// (`mceuropeanengine.hpp:229-232`), if both `samples` and `tolerance` are
    /// set (`mceuropeanengine.hpp:179,188`), if a tolerance is set on an RNG
    /// policy without an error estimate (`mceuropeanengine.hpp:190`), or if the
    /// deferred antithetic variate is requested.
    pub fn build(self) -> QlResult<MCEuropeanEngine<RNG>> {
        require!(
            self.steps.is_some() || self.steps_per_year.is_some(),
            "number of steps not given"
        );
        require!(
            self.steps.is_none() || self.steps_per_year.is_none(),
            "number of steps overspecified"
        );
        require!(
            !(self.samples.is_some() && self.tolerance.is_some()),
            "number of samples already set"
        );
        if self.tolerance.is_some() {
            require!(
                RNG::ALLOWS_ERROR_ESTIMATE,
                "chosen random generator policy does not allow an error estimate"
            );
        }
        require!(!self.antithetic, "antithetic variate not yet supported");

        MCEuropeanEngine::new(
            self.process,
            self.steps,
            self.steps_per_year,
            false,
            false,
            self.samples,
            self.tolerance,
            self.max_samples,
            self.seed,
        )
    }
}

#[cfg(test)]
mod builder_tests {
    //! Guards on [`MakeMcEuropeanEngine::build`] validation
    //! (`mceuropeanengine.hpp:179,188,190,229-232`), including the visible
    //! antithetic-variate deferral (#262 class).

    use super::MakeMcEuropeanEngine;
    use crate::math::randomnumbers::rngtraits::PseudoRandom;
    use crate::pricingengines::vanilla::test_market::market;

    fn maker() -> MakeMcEuropeanEngine<PseudoRandom> {
        MakeMcEuropeanEngine::new(market().process)
    }

    #[test]
    fn missing_steps_is_rejected() {
        assert!(maker().with_samples(1_000).build().is_err());
    }

    #[test]
    fn overspecified_steps_is_rejected() {
        assert!(
            maker()
                .with_steps(1)
                .with_steps_per_year(50)
                .with_samples(1_000)
                .build()
                .is_err()
        );
    }

    #[test]
    fn samples_and_tolerance_together_are_rejected() {
        assert!(
            maker()
                .with_steps(1)
                .with_samples(1_000)
                .with_absolute_tolerance(0.02)
                .build()
                .is_err()
        );
    }

    #[test]
    fn antithetic_variate_is_rejected_as_deferred() {
        assert!(
            maker()
                .with_steps(1)
                .with_samples(1_000)
                .with_antithetic_variate(true)
                .build()
                .is_err()
        );
    }

    #[test]
    fn plain_pseudo_config_builds() {
        assert!(
            maker()
                .with_steps(1)
                .with_samples(1_000)
                .with_seed(42)
                .build()
                .is_ok()
        );
    }
}

#[cfg(test)]
mod oracle {
    //! MC-vs-analytic oracle, the Batch MC capstone.
    //!
    //! Provenance: `test-suite/europeanoption.cpp:1269` `testMcEngines` prices a
    //! European option with `MakeMCEuropeanEngine<PseudoRandom>().withSteps(1)
    //! .withSamples(40000).withSeed(42)` and checks it against
    //! `AnalyticEuropeanEngine` (`europeanoption.cpp:168-171`). QuantLib uses a
    //! loose `0.01 * underlying` relative band (`europeanoption.cpp:1278`); this
    //! oracle INTENTIONALLY STRENGTHENS that into the `|mc - analytic| <
    //! 3 * error_estimate()` convergence pin, tying the tolerance to the
    //! computed standard error. The OTM leg is kept MODERATE (K=110, near the
    //! money): the `3 * se` Gaussian band is skew-fragile for deep-OTM payoffs
    //! at a fixed seed, which is why QuantLib uses a relative band across
    //! moneyness.
    //!
    //! The `testQmcEngines` low-discrepancy variant (`europeanoption.cpp:1288`)
    //! is deferred with the Sobol RNG policy (tracked in #454).

    use super::MakeMcEuropeanEngine;
    use crate::exercise::EuropeanExercise;
    use crate::instrument::Instrument;
    use crate::instruments::{EuropeanOption, PlainVanillaPayoff};
    use crate::math::randomnumbers::rngtraits::PseudoRandom;
    use crate::option::OptionType;
    use crate::pricingengine::PricingEngine;
    use crate::pricingengines::vanilla::test_market::{Market, market, time_to_days, today};
    use crate::shared::{Shared, SharedMut, shared, shared_mut};
    use crate::time::date::Date;
    use crate::types::Real;

    fn mc_option(market: &Market, strike: Real, expiry: Date, seed: u32) -> EuropeanOption {
        let payoff = shared(PlainVanillaPayoff::new(OptionType::Call, strike));
        let exercise = shared(EuropeanExercise::new(expiry));
        let mut option = EuropeanOption::new(payoff, exercise, Shared::clone(&market.settings));
        let engine = shared_mut(
            MakeMcEuropeanEngine::<PseudoRandom>::new(Shared::clone(&market.process))
                .with_steps(1)
                .with_samples(40_000)
                .with_seed(seed)
                .build()
                .unwrap(),
        );
        option
            .base_mut()
            .set_pricing_engine(engine as SharedMut<dyn PricingEngine>);
        option
    }

    #[test]
    fn mc_matches_analytic_across_moneyness() {
        let market = market();
        market.set(100.0, 0.02, 0.05, 0.20);
        let expiry = today() + time_to_days(1.0);

        for &strike in &[90.0, 100.0, 110.0] {
            let analytic = market
                .option(OptionType::Call, strike, expiry)
                .npv()
                .unwrap();
            let mut mc = mc_option(&market, strike, expiry, 42);
            let mc_npv = mc.npv().unwrap();
            let se = mc.error_estimate().unwrap();

            assert!(se > 0.0, "K={strike}: error estimate must be positive");
            let diff = (mc_npv - analytic).abs();
            assert!(
                diff < 3.0 * se,
                "K={strike}: |mc - analytic|={diff} not within 3*se={}",
                3.0 * se
            );
        }
    }

    #[test]
    fn same_seed_is_bitwise_deterministic() {
        let market = market();
        market.set(100.0, 0.02, 0.05, 0.20);
        let expiry = today() + time_to_days(1.0);

        let first = mc_option(&market, 100.0, expiry, 42).npv().unwrap();
        let second = mc_option(&market, 100.0, expiry, 42).npv().unwrap();
        assert_eq!(first, second, "seed 42 must reproduce the NPV bitwise");

        let other = mc_option(&market, 100.0, expiry, 43).npv().unwrap();
        assert_ne!(first, other, "a different seed must change the NPV");
    }

    #[test]
    fn tolerance_path_converges() {
        let market = market();
        market.set(100.0, 0.02, 0.05, 0.20);
        let expiry = today() + time_to_days(1.0);

        let payoff = shared(PlainVanillaPayoff::new(OptionType::Call, 100.0));
        let exercise = shared(EuropeanExercise::new(expiry));
        let mut option = EuropeanOption::new(payoff, exercise, Shared::clone(&market.settings));
        let engine = shared_mut(
            MakeMcEuropeanEngine::<PseudoRandom>::new(Shared::clone(&market.process))
                .with_steps(1)
                .with_absolute_tolerance(0.05)
                .with_seed(42)
                .build()
                .unwrap(),
        );
        option
            .base_mut()
            .set_pricing_engine(engine as SharedMut<dyn PricingEngine>);

        let mc_npv = option.npv().unwrap();
        let se = option.error_estimate().unwrap();
        let analytic = market
            .option(OptionType::Call, 100.0, expiry)
            .npv()
            .unwrap();

        assert!(se <= 0.05, "tolerance mode must drive se={se} below 0.05");
        assert!(
            (mc_npv - analytic).abs() < 3.0 * se,
            "tolerance run must land within 3*se of analytic"
        );
    }
}