quantsupport 0.1.7

Rust quantitative finance library for derivatives pricing, yield-curve bootstrapping, AAD risk, Monte Carlo exposure, and XVA.
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
use std::collections::{BTreeMap, HashMap};

use crate::{
    core::marketdatahandling::{
        constructedelementrequest::ConstructedElementRequest,
        constructedelementstore::ConstructedElementStore,
        marketdata::{MarketData, MarketDataProvider, MarketDataRequest},
    },
    currencies::currency::Currency,
    indices::marketindex::MarketIndex,
    models::modelconfiguration::SimulationConfiguration,
    quotes::{
        fixingstore::FixingStore,
        fxstore::FxStore,
        quote::Level,
        quotestore::QuoteStore,
        scenario::Scenario,
    },
    rates::bootstrapping::{
        bootstrapdiscountpolicy::BootstrapDiscountPolicy,
        creditcurvebootstrapper::CreditCurveBootstrapper,
        creditcurveconfiguration::CreditCurveConfiguration,
        curveconfiguration::CurveConfiguration,
        multicurvebootstrapper::MultiCurveBootstrapper,
    },
    simulations::simulationbuilder::SimulationBuilder,
    time::date::Date,
    utils::errors::{QSError, Result},
    volatility::{
        volatilitycubebuilder::VolatilityCubeBuilder,
        volatilitycubeconfiguration::VolatilityCubeConfiguration,
        volatilitysurfacebuilder::VolatilitySurfaceBuilder,
        volatilitysurfaceconfiguration::VolatilitySurfaceConfiguration,
    },
};

/// Manages the context for instrument evaluation, including market data access, quote level preferences,
/// base currency settings, and a list of model parameter sets for multiple model types.
#[derive(Default)]
pub struct PricingContext {
    /// The quote store provides access to direct market data quotes and reference date information.
    quote_store: QuoteStore,
    /// Scenario shocks applied to the quote store before bootstrapping.
    scenarios: Vec<Scenario>,
    /// The quote store with scenario shocks applied (built on `initialize`).
    shocked_quote_store: Option<QuoteStore>,
    /// The fixing store provides access to historical fixing values for indices and other reference data.
    fixing_store: FixingStore,
    /// Exchange rate store for FX spot rates used in cross-currency discounting.
    fx_store: FxStore,
    /// Curve specifications for curve construction.    
    curve_configurations: Vec<CurveConfiguration>,
    /// Credit (survival) curve specifications.
    credit_curve_configurations: Vec<CreditCurveConfiguration>,
    /// Volatility surface specifications.
    volatility_surface_configurations: Vec<VolatilitySurfaceConfiguration>,
    /// Volatility cube specifications.
    volatility_cube_configurations: Vec<VolatilityCubeConfiguration>,
    /// Model-driven Monte Carlo simulation specifications.
    simulation_configurations: Vec<SimulationConfiguration>,
    /// Constructed market data elements, such as discount curves, volatility surfaces, among others.
    constructed_elements: ConstructedElementStore,
    /// The base currency for pricing and reporting results.
    base_currency: Currency,
    /// Base remuneration index
    base_index: MarketIndex,
}

impl PricingContext {
    /// Creates a new pricing data context.
    #[must_use]
    pub fn new() -> Self {
        Self {
            quote_store: QuoteStore::default(),
            scenarios: Vec::new(),
            shocked_quote_store: None,
            fixing_store: FixingStore::default(),
            fx_store: FxStore::default(),
            curve_configurations: Vec::new(),
            credit_curve_configurations: Vec::new(),
            volatility_surface_configurations: Vec::new(),
            volatility_cube_configurations: Vec::new(),
            simulation_configurations: Vec::new(),
            constructed_elements: ConstructedElementStore::default(),
            base_currency: Currency::USD, // Default base currency
            base_index: MarketIndex::SOFR,
        }
    }

    /// Returns the active market data store. When scenarios are set and the
    /// context is initialized, the scenario-shocked store is returned;
    /// otherwise the base store.
    #[must_use]
    pub fn quote_store(&self) -> &QuoteStore {
        self.shocked_quote_store.as_ref().unwrap_or(&self.quote_store)
    }

    /// Returns the base (unshocked) quote store.
    #[must_use]
    pub const fn base_quote_store(&self) -> &QuoteStore {
        &self.quote_store
    }

    /// Returns the fixings store.
    #[must_use]
    pub const fn fixing_store(&self) -> &FixingStore {
        &self.fixing_store
    }

    /// Returns the exchange rate store.
    #[must_use]
    pub const fn fx_store(&self) -> &FxStore {
        &self.fx_store
    }

    /// Sets the quote store.
    #[must_use]
    pub fn with_quote_store(mut self, quote_store: QuoteStore) -> Self {
        self.quote_store = quote_store;
        self.shocked_quote_store = None;
        self
    }

    /// Sets the scenario shocks applied to the quote store on `initialize`.
    #[must_use]
    pub fn with_scenarios(mut self, scenarios: Vec<Scenario>) -> Self {
        self.scenarios = scenarios;
        self.shocked_quote_store = None;
        self
    }

    /// Returns the scenarios applied to the quote store on `initialize`.
    #[must_use]
    pub const fn scenarios(&self) -> &Vec<Scenario> {
        &self.scenarios
    }

    /// Sets the base currency of the context.
    #[must_use]
    pub const fn with_base_currency(mut self, base_currency: Currency) -> Self {
        self.base_currency = base_currency;
        self
    }

    /// Sets the base collateral remuneration index.
    #[must_use]
    pub fn with_base_index(mut self, base_index: MarketIndex) -> Self {
        self.base_index = base_index;
        self
    }

    /// Sets the fixing store.
    #[must_use]
    pub fn with_fixing_store(mut self, fixing_store: FixingStore) -> Self {
        self.fixing_store = fixing_store;
        self
    }

    /// Sets the FX store.
    #[must_use]
    pub fn with_fx_store(mut self, fx_store: FxStore) -> Self {
        self.fx_store = fx_store;
        self
    }

    /// Sets the constructed elements store, replacing any previously registered elements.
    #[must_use]
    pub fn with_constructed_elements(
        mut self,
        constructed_elements: ConstructedElementStore,
    ) -> Self {
        self.constructed_elements = constructed_elements;
        self
    }

    /// Sets the curve configurations for bootstrapping.
    #[must_use]
    pub fn with_curve_configurations(mut self, configs: Vec<CurveConfiguration>) -> Self {
        self.curve_configurations = configs;
        self
    }

    /// Sets the credit curve configurations for bootstrapping.
    #[must_use]
    pub fn with_credit_curve_configurations(
        mut self,
        configs: Vec<CreditCurveConfiguration>,
    ) -> Self {
        self.credit_curve_configurations = configs;
        self
    }

    /// Sets the volatility surface configurations.
    #[must_use]
    pub fn with_volatility_surface_configurations(
        mut self,
        configs: Vec<VolatilitySurfaceConfiguration>,
    ) -> Self {
        self.volatility_surface_configurations = configs;
        self
    }

    /// Sets the volatility cube configurations.
    #[must_use]
    pub fn with_volatility_cube_configurations(
        mut self,
        configs: Vec<VolatilityCubeConfiguration>,
    ) -> Self {
        self.volatility_cube_configurations = configs;
        self
    }

    /// Sets the model-driven simulation configurations.
    #[must_use]
    pub fn with_simulation_configurations(
        mut self,
        configs: Vec<SimulationConfiguration>,
    ) -> Self {
        self.simulation_configurations = configs;
        self
    }

    /// Returns the curve configurations used for bootstrapping.
    #[must_use]
    pub const fn curve_configurations(&self) -> &Vec<CurveConfiguration> {
        &self.curve_configurations
    }

    /// Returns the credit curve configurations used for bootstrapping.
    #[must_use]
    pub const fn credit_curve_configurations(&self) -> &Vec<CreditCurveConfiguration> {
        &self.credit_curve_configurations
    }

    /// Returns the volatility surface configurations.
    #[must_use]
    pub const fn volatility_surface_configurations(&self) -> &Vec<VolatilitySurfaceConfiguration> {
        &self.volatility_surface_configurations
    }

    /// Returns the volatility cube configurations.
    #[must_use]
    pub const fn volatility_cube_configurations(&self) -> &Vec<VolatilityCubeConfiguration> {
        &self.volatility_cube_configurations
    }

    /// Returns the model-driven simulation configurations.
    #[must_use]
    pub const fn simulation_configurations(&self) -> &Vec<SimulationConfiguration> {
        &self.simulation_configurations
    }

    /// Returns the current reference date.
    #[must_use]
    pub const fn evaluation_date(&self) -> Date {
        self.quote_store.reference_date()
    }

    /// Returns the constructed elements store.
    #[must_use]
    pub const fn constructed_elements(&self) -> &ConstructedElementStore {
        &self.constructed_elements
    }

    /// Returns a mutable reference to the constructed elements store.
    pub const fn constructed_elements_mut(&mut self) -> &mut ConstructedElementStore {
        &mut self.constructed_elements
    }

    /// Returns the base currency.
    #[must_use]
    pub const fn base_currency(&self) -> Currency {
        self.base_currency
    }

    /// Returns the base index.
    #[must_use]
    pub const fn base_index(&self) -> &MarketIndex {
        &self.base_index
    }

    /// Placeholder for one-time initialisation (pre-loading caches, etc.).
    ///
    /// # Errors
    /// Returns an error if a scenario matches no quotes, or if bootstrapping
    /// or volatility surface construction fails.
    pub fn initialize(&mut self) -> Result<()> {
        // Apply scenario shocks to a copy of the base quote store. All
        // downstream construction (curves, vols, simulations) then uses the
        // shocked market.
        self.shocked_quote_store = if self.scenarios.is_empty() {
            None
        } else {
            let mut store = self.quote_store.clone();
            for scenario in &self.scenarios {
                scenario.apply(&mut store)?;
            }
            Some(store)
        };

        // Bootstrap discount curves.
        let policy = BootstrapDiscountPolicy::new(self.base_index.clone(), self.base_currency);
        let bootstrapper = MultiCurveBootstrapper::new(self.curve_configurations.clone(), policy)
            .with_fx_store(self.fx_store.clone());
        let curves = bootstrapper.bootstrap(self.quote_store(), Level::Mid)?;
        for (index, curve) in curves {
            self.constructed_elements
                .discount_curves_mut()
                .insert(index, curve);
        }

        // Bootstrap credit (survival) curves. Runs after the discount curves
        // since CDS pillar instruments are discounted with them.
        if !self.credit_curve_configurations.is_empty() {
            let credit_bootstrapper =
                CreditCurveBootstrapper::new(self.credit_curve_configurations.clone());
            let credit_curves = credit_bootstrapper.bootstrap(
                self.quote_store(),
                Level::Mid,
                self.constructed_elements.discount_curves(),
            )?;
            for (index, curve) in credit_curves {
                self.constructed_elements
                    .credit_curves_mut()
                    .insert(index, curve);
            }
        }

        // Build volatility surfaces.
        if !self.volatility_surface_configurations.is_empty() {
            let surface_builder =
                VolatilitySurfaceBuilder::new(self.volatility_surface_configurations.clone());
            let surfaces = surface_builder.build(self.quote_store(), Level::Mid)?;
            for (index, surface) in surfaces {
                self.constructed_elements
                    .volatility_surfaces_mut()
                    .insert(index, surface);
            }
        }

        // Build volatility cubes.
        if !self.volatility_cube_configurations.is_empty() {
            let cube_builder =
                VolatilityCubeBuilder::new(self.volatility_cube_configurations.clone());
            let cubes = cube_builder.build(self.quote_store(), Level::Mid)?;
            for (index, cube) in cubes {
                self.constructed_elements
                    .volatility_cubes_mut()
                    .insert(index, cube);
            }
        }

        // Build model-driven Monte Carlo simulations. Runs last so that
        // models can consume the constructed curves, surfaces, and cubes.
        if !self.simulation_configurations.is_empty() {
            let simulation_builder =
                SimulationBuilder::new(self.simulation_configurations.clone());
            let simulations = simulation_builder.build(
                &self.constructed_elements,
                self.quote_store(),
                &self.fixing_store,
                Level::Mid,
            )?;
            for (index, simulation) in simulations {
                self.constructed_elements
                    .simulations_mut()
                    .insert(index, simulation);
            }
        }

        Ok(())
    }
}

impl MarketDataProvider for PricingContext {
    fn evaluation_date(&self) -> Date {
        self.quote_store.reference_date()
    }

    // this needs to be refactored
    #[allow(clippy::too_many_lines)]
    fn handle_request(&self, request: &MarketDataRequest) -> Result<MarketData> {
        // 1. Resolve constructed elements from the internal store.
        let mut constructed_elements = ConstructedElementStore::default();
        if let Some(element_requests) = request.constructed_elements_request() {
            for req in element_requests {
                match req {
                    ConstructedElementRequest::DiscountCurve { market_index } => {
                        let curve = self
                            .constructed_elements
                            .discount_curve(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Discount curve not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .discount_curves_mut()
                            .insert(market_index.clone(), curve.clone());
                    }
                    ConstructedElementRequest::DividendCurve { market_index } => {
                        let curve = self
                            .constructed_elements
                            .dividend_curve(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Dividend curve not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .dividend_curves_mut()
                            .insert(market_index.clone(), curve.clone());
                    }
                    ConstructedElementRequest::CreditCurve { market_index } => {
                        let curve = self
                            .constructed_elements
                            .credit_curve(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Credit curve not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .credit_curves_mut()
                            .insert(market_index.clone(), curve.clone());
                    }
                    ConstructedElementRequest::VolatilitySurface { market_index } => {
                        let surface = self
                            .constructed_elements
                            .volatility_surface(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Volatility surface not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .volatility_surfaces_mut()
                            .insert(market_index.clone(), surface.clone());
                    }
                    ConstructedElementRequest::VolatilityCube { market_index } => {
                        let cube = self
                            .constructed_elements
                            .volatility_cube(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Volatility cube not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .volatility_cubes_mut()
                            .insert(market_index.clone(), cube.clone());
                    }
                    // probably this will be moved out
                    ConstructedElementRequest::Simulation { market_index } => {
                        let sim = self
                            .constructed_elements
                            .simulations()
                            .get(market_index)
                            .ok_or_else(|| {
                                QSError::NotFoundErr(format!(
                                    "Simulation not found for index {market_index}"
                                ))
                            })?;
                        constructed_elements
                            .simulations_mut()
                            .insert(market_index.clone(), sim.clone());
                    }
                }
            }
        }

        // 2. Resolve fixings from the fixing store.
        let mut fixings: HashMap<MarketIndex, BTreeMap<Date, f64>> = HashMap::new();
        if let Some(fixing_requests) = request.fixings_request() {
            for fix_req in fixing_requests {
                let market_index = fix_req.market_index();
                let date = fix_req.date();
                let value = self.fixing_store.fixing(market_index, date)?;
                fixings
                    .entry(market_index.clone())
                    .or_default()
                    .insert(date, value);
            }
        }

        // 3. Resolve FX rates from the FX store.
        // this approach is not ideal, it could lead to sensitivities in unnatural parities
        let mut fx_store = FxStore::new();
        if let Some(fx_requests) = request.fx_request() {
            for fx_req in fx_requests {
                if let Some(quote_ccy) = fx_req.quote() {
                    let rate = self.fx_store.get_fx_rate(fx_req.base(), quote_ccy)?;
                    fx_store.add_fx_rate(fx_req.base(), quote_ccy, rate);
                }
            }
        }

        // 4. Assemble final MarketData.
        let md = MarketData::new(fixings, constructed_elements).with_fx_store(fx_store);

        Ok(md)
    }
}