finquant 0.0.60

Experimental Rust Quant Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::error::Result;
use crate::patterns::observer::{Observable, Observer};
use crate::time::calendars::Calendar;
use crate::time::period::Period;
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::cell::RefCell;
use std::rc::{Rc, Weak};

/// A single FX forward market quote, keyed by tenor.
///
/// ## Bloomberg quote conventions — ON / TN / SN
///
/// Bloomberg displays three kinds of pre-spot and at-spot tenors on its FX
/// Forward screen:
///
/// | Tenor | Bloomberg name  | Near leg | Far leg             |
/// |-------|-----------------|----------|---------------------|
/// | `ON`  | Overnight       | T        | T+1                 |
/// | `TN`  | Tom-Next        | T+1      | T+2 (spot, T+2 pairs) |
/// | `SPOT`| Spot            | —        | T+2                 |
/// | `SN`  | Spot-Next       | T+2      | T+3                 |
///
/// Bloomberg's **"Pts"** column shows the *swap forward points* for each
/// individual overnight period (not cumulative from spot). The **"Fwds"**
/// column shows the *outright forward rate* at the far-leg date.
///
/// ## What `value` represents in `FXForwardHelper`
///
/// `value` is always stored as **outright forward points from spot** (same
/// unit as the 1W, 1M, … quotes). Positive = above spot; negative = below.
///
/// | Tenor | Typical `value` sign      | Interpretation                       |
/// |-------|---------------------------|--------------------------------------|
/// | `ON`  | negative (USD high rates) | outright pts at T+1 relative to spot |
/// | `TN`  | ~0 (equals spot far leg)  | same settlement as `SPOT`            |
/// | `SPOT`| 0.0                       | reference point                       |
/// | `SN`  | positive                  | outright pts at T+3 relative to spot |
///
/// ## Single outright forward vs 2-leg FX swap
///
/// * **Single outright forward**: one cash exchange at the settlement date.
///   Price by calling `FXForwardHelper::get_forward(settlement_date, cal)`.
/// * **2-leg FX swap** (e.g. ON, TN, SN): simultaneous buy at the near leg
///   and sell at the far leg (or vice-versa). Obtain both dates via
///   `Period::near_date` (near leg) and `Period::settlement_date` (far leg),
///   then call `get_forward` for each leg separately.
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct FXForwardQuote {
    pub tenor: Period,
    pub value: f64,
}

#[derive(Serialize, Debug)]
pub struct FXForwardHelper {
    pub valuation_date: NaiveDate,
    pub spot_ref: f64,
    spot_lag: i64,
    pub quotes: Vec<FXForwardQuote>,
    #[serde(skip_serializing)]
    observers: RefCell<Vec<Weak<RefCell<dyn Observer>>>>,
}

impl FXForwardHelper {
    /// Construct a helper for a standard T+2 currency pair.
    pub fn new(valuation_date: NaiveDate, spot_ref: f64, quotes: Vec<FXForwardQuote>) -> Self {
        Self::with_spot_lag(valuation_date, spot_ref, 2, quotes)
    }

    /// Construct a helper with an explicit spot lag.
    ///
    /// Prefer building via `FXUnderlying::forward_helper` so the lag is derived
    /// automatically from the pair's convention rather than supplied ad-hoc.
    pub(crate) fn with_spot_lag(
        valuation_date: NaiveDate,
        spot_ref: f64,
        spot_lag: i64,
        quotes: Vec<FXForwardQuote>,
    ) -> Self {
        Self {
            valuation_date,
            spot_ref,
            spot_lag,
            quotes,
            observers: RefCell::new(Vec::new()),
        }
    }

    pub fn get_forward(
        &self,
        target_date: NaiveDate,
        calendar: &dyn Calendar,
    ) -> Result<Option<f64>> {
        // Out-of-range if the target is on/before valuation
        if self.valuation_date >= target_date {
            return Ok(None);
        }

        // Compute settlement dates up-front, propagating any calendar errors
        let mut dated: Vec<(NaiveDate, f64)> = self
            .quotes
            .iter()
            .map(|q| {
                Ok((
                    q.tenor.settlement_date_with_lag(
                        self.valuation_date,
                        calendar,
                        self.spot_lag,
                    )?,
                    q.value,
                ))
            })
            .collect::<Result<Vec<_>>>()?;

        // Need at least two points to interpolate
        if dated.len() < 2 {
            return Ok(None);
        }

        // Sort by settlement date once
        dated.sort_unstable_by_key(|(d, _)| *d);

        // Exact match or find bracketing dates
        match dated.binary_search_by_key(&target_date, |(d, _)| *d) {
            Ok(idx) => Ok(Some(dated[idx].1)),
            Err(idx) => {
                // If the target is outside the known range, return None
                if idx == 0 || idx == dated.len() {
                    return Ok(None);
                }

                let (start_date, start_val) = dated[idx - 1];
                let (end_date, end_val) = dated[idx];

                let total_day_count = (end_date - start_date).num_days() as f64;
                if total_day_count.abs() < f64::EPSILON {
                    // Degenerate case: identical settlement dates; use start value
                    return Ok(Some(start_val));
                }

                let target_day_count = (target_date - start_date).num_days() as f64;
                let weight = target_day_count / total_day_count;
                let interpolated = start_val + (end_val - start_val) * weight;
                Ok(Some(interpolated))
            }
        }
    }
}

impl Observable for FXForwardHelper {
    fn attach(&mut self, observer: Rc<RefCell<dyn Observer>>) {
        self.observers.borrow_mut().push(Rc::downgrade(&observer));
    }

    fn notify_observers(&self) -> Result<()> {
        // First, prune any dead observers
        {
            let mut list = self.observers.borrow_mut();
            list.retain(|w| w.upgrade().is_some());
        }

        // Then notify the currently alive observers
        let observers = self
            .observers
            .borrow()
            .iter()
            .filter_map(|observer_weak| observer_weak.upgrade())
            .collect::<Vec<_>>();
        for observer_rc in observers {
            observer_rc.borrow_mut().update(self)?;
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::error::Result;
    use crate::markets::forex::quotes::forwardpoints::{FXForwardHelper, FXForwardQuote};
    use crate::tests::common::{sample_fx_forward_helper, setup};
    use crate::time::calendars::JointCalendar;
    use crate::time::calendars::Target;
    use crate::time::calendars::UnitedKingdom;
    use crate::time::calendars::UnitedStates;
    use crate::time::period::Period;
    use chrono::NaiveDate;
    use std::f64;

    #[test]
    fn test_settlement_date_target() -> Result<()> {
        let valuation_date = NaiveDate::from_ymd_opt(2023, 3, 29).unwrap();
        let calendar = Target;
        assert_eq!(
            Period::SPOT.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 3, 31).unwrap()
        );
        assert_eq!(
            Period::SN.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 4, 3).unwrap()
        );
        assert_eq!(
            Period::Weeks(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 4, 11).unwrap()
        );
        assert_eq!(
            Period::Weeks(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 4, 14).unwrap()
        );
        assert_eq!(
            Period::Weeks(3).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 4, 21).unwrap()
        );
        assert_eq!(
            Period::Months(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 4, 28).unwrap()
        );
        assert_eq!(
            Period::Months(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 5, 31).unwrap()
        );
        assert_eq!(
            Period::Months(3).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 6, 30).unwrap()
        );
        assert_eq!(
            Period::Months(4).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 7, 31).unwrap()
        );
        assert_eq!(
            Period::Months(5).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 8, 31).unwrap()
        );
        assert_eq!(
            Period::Months(6).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 9, 29).unwrap()
        );
        assert_eq!(
            Period::Months(9).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 12, 29).unwrap()
        );
        assert_eq!(
            Period::Years(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 3, 28).unwrap()
        );
        assert_eq!(
            Period::Months(15).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 6, 28).unwrap()
        );
        assert_eq!(
            Period::Months(18).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 9, 30).unwrap()
        );
        assert_eq!(
            Period::Years(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2025, 3, 31).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_settlement_date_gbpusd() -> Result<()> {
        let valuation_date = NaiveDate::from_ymd_opt(2023, 10, 16).unwrap();
        let calendar = JointCalendar::new(vec![
            Box::new(UnitedStates::default()),
            Box::new(UnitedKingdom::default()),
        ]);

        assert_eq!(
            Period::ON.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 10, 17).unwrap()
        );

        // TN far leg equals the spot date for standard T+2 pairs
        assert_eq!(
            Period::TN.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 10, 18).unwrap()
        );
        assert_eq!(
            Period::SPOT.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 10, 18).unwrap()
        );
        assert_eq!(
            Period::SN.settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 10, 19).unwrap()
        );
        assert_eq!(
            Period::Weeks(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 10, 25).unwrap()
        );
        assert_eq!(
            Period::Weeks(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 11, 1).unwrap()
        );
        assert_eq!(
            Period::Weeks(3).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 11, 8).unwrap()
        );
        assert_eq!(
            Period::Months(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 11, 20).unwrap()
        );
        assert_eq!(
            Period::Months(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2023, 12, 18).unwrap()
        );
        assert_eq!(
            Period::Months(3).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 1, 18).unwrap()
        );
        assert_eq!(
            Period::Months(4).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 2, 20).unwrap()
        );
        assert_eq!(
            Period::Months(5).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 3, 18).unwrap()
        );
        assert_eq!(
            Period::Months(6).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 4, 18).unwrap()
        );
        assert_eq!(
            Period::Months(9).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 7, 18).unwrap()
        );
        assert_eq!(
            Period::Years(1).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2024, 10, 18).unwrap()
        );
        assert_eq!(
            Period::Months(15).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2025, 1, 21).unwrap()
        );
        assert_eq!(
            Period::Months(18).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2025, 4, 22).unwrap()
        );
        assert_eq!(
            Period::Years(2).settlement_date(valuation_date, &calendar)?,
            NaiveDate::from_ymd_opt(2025, 10, 20).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_forward_points() -> Result<()> {
        setup();
        let fx_forward_helper = sample_fx_forward_helper();
        let calendar = JointCalendar::new(vec![
            Box::new(UnitedStates::default()),
            Box::new(UnitedKingdom::default()),
        ]);

        let first_target_date = NaiveDate::from_ymd_opt(2024, 2, 15).unwrap();
        let cal_output = f64::trunc(
            fx_forward_helper
                .get_forward(first_target_date, &calendar)?
                .unwrap()
                * 100.0,
        ) / 100.0;
        assert_eq!(cal_output, 9.64);

        let second_target_date = NaiveDate::from_ymd_opt(2034, 2, 15).unwrap();
        let cal_output = fx_forward_helper.get_forward(second_target_date, &calendar)?;
        assert_eq!(cal_output, None);

        Ok(())
    }

    #[test]
    fn test_forward_none_on_or_before_valuation() -> Result<()> {
        // Ensure get_forward returns None when target_date is on/before valuation_date
        setup();
        let fx_forward_helper = sample_fx_forward_helper();
        let calendar = JointCalendar::new(vec![
            Box::new(UnitedStates::default()),
            Box::new(UnitedKingdom::default()),
        ]);

        // On valuation date -> None
        let on_valuation = fx_forward_helper.valuation_date;
        assert_eq!(
            fx_forward_helper.get_forward(on_valuation, &calendar)?,
            None
        );

        // Before valuation date -> None (if a predecessor exists)
        if let Some(before_valuation) = fx_forward_helper.valuation_date.pred_opt() {
            assert_eq!(
                fx_forward_helper.get_forward(before_valuation, &calendar)?,
                None
            );
        }

        Ok(())
    }

    #[test]
    fn test_forward_exact_match_returns_quote_value() -> Result<()> {
        // If the target date equals a quote's settlement date, return that quote's value
        setup();
        let fx_forward_helper = sample_fx_forward_helper();
        let calendar = JointCalendar::new(vec![
            Box::new(UnitedStates::default()),
            Box::new(UnitedKingdom::default()),
        ]);

        // Use the first available quote for an exact match test
        let q = fx_forward_helper.quotes[0];
        let exact_date = q
            .tenor
            .settlement_date(fx_forward_helper.valuation_date, &calendar)?;
        let got = fx_forward_helper
            .get_forward(exact_date, &calendar)?
            .unwrap();
        assert_eq!(got, q.value);

        Ok(())
    }

    #[test]
    fn test_forward_out_of_range_before_first_settlement() -> Result<()> {
        // Build a minimal helper where the target is after valuation but before first settlement
        use chrono::Duration;

        let valuation_date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
        // Create two quotes: 1W and 2W
        let quotes = vec![
            FXForwardQuote {
                tenor: Period::Weeks(1),
                value: 10.0,
            },
            FXForwardQuote {
                tenor: Period::Weeks(2),
                value: 20.0,
            },
        ];
        let helper = FXForwardHelper::new(valuation_date, 1.0, quotes);
        let calendar = Target;

        // Choose a date strictly after valuation_date but before 1W settlement date
        let first_settle = Period::Weeks(1).settlement_date(valuation_date, &calendar)?;
        let target_date = valuation_date + Duration::days(1);
        assert!(target_date > valuation_date && target_date < first_settle);

        assert_eq!(helper.get_forward(target_date, &calendar)?, None);

        Ok(())
    }

    #[test]
    fn test_notify_observers_prune_and_notify() -> Result<()> {
        // Create one dead observer (dropped before notification) and one live observer.
        use crate::patterns::observer::{Observable, Observer};
        use std::cell::RefCell;
        use std::rc::Rc;

        #[derive(Debug)]
        struct TestObserver {
            updates: usize,
        }

        impl Observer for TestObserver {
            fn update(&mut self, _observable: &dyn Observable) -> Result<()> {
                self.updates += 1;
                Ok(())
            }
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
        }

        let valuation_date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
        let quotes = vec![
            FXForwardQuote {
                tenor: Period::Weeks(1),
                value: 10.0,
            },
            FXForwardQuote {
                tenor: Period::Weeks(2),
                value: 20.0,
            },
        ];
        let mut helper = FXForwardHelper::new(valuation_date, 1.0, quotes);

        // Attach a dead observer (drop the last strong reference)
        let dead = Rc::new(RefCell::new(TestObserver { updates: 0 }));
        helper.attach(dead.clone());
        drop(dead);

        // Attach a live observer
        let alive = Rc::new(RefCell::new(TestObserver { updates: 0 }));
        helper.attach(alive.clone());

        // Notify should prune the dead one and notify the live one once
        helper.notify_observers()?;
        assert_eq!(alive.borrow().updates, 1);

        Ok(())
    }
}