datasynth-generators 2.2.0

50+ data generators covering GL, P2P, O2C, S2C, HR, manufacturing, audit, tax, treasury, and ESG
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
//! FX rate generation service using Ornstein-Uhlenbeck process.
//!
//! Generates realistic exchange rates with mean-reversion and
//! occasional fat-tail moves.

use chrono::{Datelike, NaiveDate};
use datasynth_core::utils::seeded_rng;
use rand::Rng;
use rand_chacha::ChaCha8Rng;
use rand_distr::{Distribution, Normal};
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::collections::HashMap;
use tracing::{debug, info};

use datasynth_core::models::{base_rates_usd, FxRate, FxRateTable, RateType};

/// Configuration for FX rate generation.
#[derive(Debug, Clone)]
pub struct FxRateServiceConfig {
    /// Base currency for all rates.
    pub base_currency: String,
    /// Mean reversion speed (theta) - higher = faster reversion.
    pub mean_reversion_speed: f64,
    /// Long-term mean level (typically 0 for log returns).
    pub long_term_mean: f64,
    /// Daily volatility (sigma) - typical FX volatility is 0.5-1% daily.
    pub daily_volatility: f64,
    /// Probability of fat-tail event (2x volatility).
    pub fat_tail_probability: f64,
    /// Fat-tail multiplier.
    pub fat_tail_multiplier: f64,
    /// Currencies to generate rates for.
    pub currencies: Vec<String>,
    /// Whether to generate weekend rates (or skip weekends).
    pub include_weekends: bool,
}

impl Default for FxRateServiceConfig {
    fn default() -> Self {
        Self {
            base_currency: "USD".to_string(),
            mean_reversion_speed: 0.05,
            long_term_mean: 0.0,
            daily_volatility: 0.006, // ~0.6% daily volatility
            fat_tail_probability: 0.05,
            fat_tail_multiplier: 2.5,
            currencies: vec![
                "EUR".to_string(),
                "GBP".to_string(),
                "JPY".to_string(),
                "CHF".to_string(),
                "CAD".to_string(),
                "AUD".to_string(),
                "CNY".to_string(),
            ],
            include_weekends: false,
        }
    }
}

/// Service for generating FX rates.
pub struct FxRateService {
    config: FxRateServiceConfig,
    rng: ChaCha8Rng,
    /// Current rates for each currency (log of rate for O-U process).
    current_log_rates: HashMap<String, f64>,
    /// Base rates (initial starting points).
    base_rates: HashMap<String, Decimal>,
}

impl FxRateService {
    /// Creates a new FX rate service.
    pub fn new(config: FxRateServiceConfig, rng: ChaCha8Rng) -> Self {
        let base_rates = base_rates_usd();
        let mut current_log_rates = HashMap::new();

        // Initialize log rates from base rates
        for currency in &config.currencies {
            if let Some(rate) = base_rates.get(currency) {
                let rate_f64: f64 = rate.to_f64().unwrap_or(1.0);
                current_log_rates.insert(currency.clone(), rate_f64.ln());
            }
        }

        Self {
            config,
            rng,
            current_log_rates,
            base_rates,
        }
    }

    /// Creates a new FX rate service from a seed, constructing the RNG internally.
    pub fn with_seed(config: FxRateServiceConfig, seed: u64) -> Self {
        Self::new(config, seeded_rng(seed, 0))
    }

    /// Generates daily FX rates for a date range.
    pub fn generate_daily_rates(
        &mut self,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> FxRateTable {
        info!(
            "Generating FX rates for {} currencies ({} to {})",
            self.config.currencies.len(),
            start_date,
            end_date
        );
        let mut table = FxRateTable::new(&self.config.base_currency);
        let mut current_date = start_date;

        while current_date <= end_date {
            // Skip weekends if configured
            if !self.config.include_weekends {
                let weekday = current_date.weekday();
                if weekday == chrono::Weekday::Sat || weekday == chrono::Weekday::Sun {
                    current_date = current_date.succ_opt().unwrap_or(current_date);
                    continue;
                }
            }

            // Generate rates for each currency
            for currency in self.config.currencies.clone() {
                if currency == self.config.base_currency {
                    continue;
                }

                let rate = self.generate_next_rate(&currency, current_date);
                table.add_rate(rate);
            }

            current_date = current_date.succ_opt().unwrap_or(current_date);
        }

        table
    }

    /// Generates period rates (closing and average) for a fiscal period.
    pub fn generate_period_rates(
        &mut self,
        year: i32,
        month: u32,
        daily_table: &FxRateTable,
    ) -> Vec<FxRate> {
        let mut rates = Vec::new();

        let period_start =
            NaiveDate::from_ymd_opt(year, month, 1).expect("valid year/month for period start");
        let period_end = if month == 12 {
            NaiveDate::from_ymd_opt(year + 1, 1, 1)
                .expect("valid next year start")
                .pred_opt()
                .expect("valid predecessor date")
        } else {
            NaiveDate::from_ymd_opt(year, month + 1, 1)
                .expect("valid next month start")
                .pred_opt()
                .expect("valid predecessor date")
        };

        for currency in &self.config.currencies {
            if *currency == self.config.base_currency {
                continue;
            }

            // Closing rate = last spot rate of the period
            if let Some(closing) =
                daily_table.get_spot_rate(currency, &self.config.base_currency, period_end)
            {
                rates.push(FxRate::new(
                    currency,
                    &self.config.base_currency,
                    RateType::Closing,
                    period_end,
                    closing.rate,
                    "GENERATED",
                ));
            }

            // Average rate = simple average of all spot rates in the period
            let spot_rates: Vec<&FxRate> = daily_table
                .get_all_rates(currency, &self.config.base_currency)
                .into_iter()
                .filter(|r| {
                    r.rate_type == RateType::Spot
                        && r.effective_date >= period_start
                        && r.effective_date <= period_end
                })
                .collect();

            if !spot_rates.is_empty() {
                let sum: Decimal = spot_rates.iter().map(|r| r.rate).sum();
                let avg = sum / Decimal::from(spot_rates.len());

                rates.push(FxRate::new(
                    currency,
                    &self.config.base_currency,
                    RateType::Average,
                    period_end,
                    avg.round_dp(6),
                    "GENERATED",
                ));
            }
        }

        rates
    }

    /// Generates the next rate using Ornstein-Uhlenbeck process.
    ///
    /// The O-U process: dX = θ(μ - X)dt + σdW
    /// Where:
    /// - θ = mean reversion speed
    /// - μ = long-term mean
    /// - σ = volatility
    /// - dW = Wiener process increment
    fn generate_next_rate(&mut self, currency: &str, date: NaiveDate) -> FxRate {
        let current_log = *self.current_log_rates.get(currency).unwrap_or(&0.0);

        // Get base rate for mean reversion target
        let base_rate: f64 = self
            .base_rates
            .get(currency)
            .map(|d| (*d).try_into().unwrap_or(1.0))
            .unwrap_or(1.0);
        let base_log = base_rate.ln();

        // Ornstein-Uhlenbeck step
        let theta = self.config.mean_reversion_speed;
        let mu = base_log + self.config.long_term_mean;

        // Check for fat-tail event
        let volatility = if self.rng.random::<f64>() < self.config.fat_tail_probability {
            self.config.daily_volatility * self.config.fat_tail_multiplier
        } else {
            self.config.daily_volatility
        };

        // Generate normal random shock
        let normal = Normal::new(0.0, 1.0).expect("valid standard normal parameters");
        let dw: f64 = normal.sample(&mut self.rng);

        // O-U update: X(t+1) = X(t) + θ(μ - X(t)) + σ * dW
        let drift = theta * (mu - current_log);
        let diffusion = volatility * dw;
        let new_log = current_log + drift + diffusion;

        // Update state
        self.current_log_rates.insert(currency.to_string(), new_log);

        // Convert log rate back to actual rate
        let new_rate = new_log.exp();
        let rate_decimal = Decimal::try_from(new_rate).unwrap_or(dec!(1)).round_dp(6);

        // Log at period boundaries (first day of each month) to avoid excessive output
        if date.day() == 1 {
            debug!(
                "Rate {}/{} for {}: {}",
                currency, self.config.base_currency, date, rate_decimal
            );
        }

        FxRate::new(
            currency,
            &self.config.base_currency,
            RateType::Spot,
            date,
            rate_decimal,
            "O-U PROCESS",
        )
    }

    /// Resets the rate service to initial base rates.
    pub fn reset(&mut self) {
        self.current_log_rates.clear();
        for currency in &self.config.currencies {
            if let Some(rate) = self.base_rates.get(currency) {
                let rate_f64: f64 = (*rate).try_into().unwrap_or(1.0);
                self.current_log_rates
                    .insert(currency.clone(), rate_f64.ln());
            }
        }
    }

    /// Gets the current rate for a currency.
    pub fn current_rate(&self, currency: &str) -> Option<Decimal> {
        self.current_log_rates.get(currency).map(|log_rate| {
            let rate = log_rate.exp();
            Decimal::try_from(rate).unwrap_or(dec!(1)).round_dp(6)
        })
    }
}

/// Generates a complete set of FX rates for a simulation period.
pub struct FxRateGenerator {
    service: FxRateService,
}

impl FxRateGenerator {
    /// Creates a new FX rate generator.
    pub fn new(config: FxRateServiceConfig, rng: ChaCha8Rng) -> Self {
        Self {
            service: FxRateService::new(config, rng),
        }
    }

    /// Creates a new FX rate generator from a seed, constructing the RNG internally.
    pub fn with_seed(config: FxRateServiceConfig, seed: u64) -> Self {
        Self::new(config, seeded_rng(seed, 0))
    }

    /// Generates all rates (daily, closing, average) for a date range.
    pub fn generate_all_rates(
        &mut self,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> GeneratedFxRates {
        // Generate daily spot rates
        let daily_rates = self.service.generate_daily_rates(start_date, end_date);

        // Generate period rates for each month
        let mut period_rates = Vec::new();
        let mut current_year = start_date.year();
        let mut current_month = start_date.month();

        while (current_year < end_date.year())
            || (current_year == end_date.year() && current_month <= end_date.month())
        {
            let rates =
                self.service
                    .generate_period_rates(current_year, current_month, &daily_rates);
            period_rates.extend(rates);

            // Move to next month
            if current_month == 12 {
                current_month = 1;
                current_year += 1;
            } else {
                current_month += 1;
            }
        }

        GeneratedFxRates {
            daily_rates,
            period_rates,
            start_date,
            end_date,
        }
    }

    /// Gets a reference to the underlying service.
    pub fn service(&self) -> &FxRateService {
        &self.service
    }

    /// Gets a mutable reference to the underlying service.
    pub fn service_mut(&mut self) -> &mut FxRateService {
        &mut self.service
    }
}

/// Container for all generated FX rates.
#[derive(Debug, Clone)]
pub struct GeneratedFxRates {
    /// Daily spot rates.
    pub daily_rates: FxRateTable,
    /// Period closing and average rates.
    pub period_rates: Vec<FxRate>,
    /// Start date of generation.
    pub start_date: NaiveDate,
    /// End date of generation.
    pub end_date: NaiveDate,
}

impl GeneratedFxRates {
    /// Combines all rates into a single rate table.
    pub fn combined_rate_table(&self) -> FxRateTable {
        let mut table = self.daily_rates.clone();
        for rate in &self.period_rates {
            table.add_rate(rate.clone());
        }
        table
    }

    /// Gets closing rates for a specific period end date.
    pub fn closing_rates_for_date(&self, date: NaiveDate) -> Vec<&FxRate> {
        self.period_rates
            .iter()
            .filter(|r| r.rate_type == RateType::Closing && r.effective_date == date)
            .collect()
    }

    /// Gets average rates for a specific period end date.
    pub fn average_rates_for_date(&self, date: NaiveDate) -> Vec<&FxRate> {
        self.period_rates
            .iter()
            .filter(|r| r.rate_type == RateType::Average && r.effective_date == date)
            .collect()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use rand::SeedableRng;

    #[test]
    fn test_fx_rate_generation() {
        let rng = ChaCha8Rng::seed_from_u64(12345);
        let config = FxRateServiceConfig {
            currencies: vec!["EUR".to_string(), "GBP".to_string()],
            ..Default::default()
        };

        let mut service = FxRateService::new(config, rng);

        let rates = service.generate_daily_rates(
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 1, 31).unwrap(),
        );

        // Should have rates for each business day
        assert!(!rates.is_empty());
    }

    #[test]
    fn test_rate_mean_reversion() {
        let rng = ChaCha8Rng::seed_from_u64(12345);
        let config = FxRateServiceConfig {
            currencies: vec!["EUR".to_string()],
            mean_reversion_speed: 0.1, // Strong mean reversion
            daily_volatility: 0.001,   // Low volatility
            ..Default::default()
        };

        let mut service = FxRateService::new(config.clone(), rng);

        // Generate 100 days of rates
        let rates = service.generate_daily_rates(
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 4, 10).unwrap(),
        );

        // With strong mean reversion and low volatility, rates should stay near base
        let base_eur = base_rates_usd().get("EUR").cloned().unwrap_or(dec!(1.10));
        let all_eur_rates: Vec<Decimal> = rates
            .get_all_rates("EUR", "USD")
            .iter()
            .map(|r| r.rate)
            .collect();

        assert!(!all_eur_rates.is_empty());

        // Check that rates stay within reasonable bounds of base rate (±10%)
        for rate in &all_eur_rates {
            let deviation = (*rate - base_eur).abs() / base_eur;
            assert!(
                deviation < dec!(0.15),
                "Rate {} deviated too much from base {}",
                rate,
                base_eur
            );
        }
    }

    #[test]
    fn test_period_rates() {
        let rng = ChaCha8Rng::seed_from_u64(12345);
        let config = FxRateServiceConfig {
            currencies: vec!["EUR".to_string()],
            ..Default::default()
        };

        let mut generator = FxRateGenerator::new(config, rng);

        let generated = generator.generate_all_rates(
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 3, 31).unwrap(),
        );

        // Should have closing and average rates for each month
        let jan_closing =
            generated.closing_rates_for_date(NaiveDate::from_ymd_opt(2024, 1, 31).unwrap());
        assert!(!jan_closing.is_empty());

        let jan_average =
            generated.average_rates_for_date(NaiveDate::from_ymd_opt(2024, 1, 31).unwrap());
        assert!(!jan_average.is_empty());
    }
}