Skip to main content

aprender_monte_carlo/models/
mod.rs

1//! Business and financial models for Monte Carlo simulation
2//!
3//! This module provides domain-specific models that wrap the core
4//! Monte Carlo functionality from `aprender::monte_carlo`.
5
6use aprender::monte_carlo::prelude::*;
7
8/// Bayesian Revenue Model for business forecasting
9///
10/// Models product revenue with uncertain growth using Bayesian priors.
11/// Combines historical data with domain expertise for robust forecasting.
12///
13/// # Example
14///
15/// ```rust,ignore
16/// use aprender_monte_carlo::models::BayesianRevenueModel;
17///
18/// let products = vec![
19///     ProductData { name: "Widget", base_revenue: 100_000.0, growth_rate: 0.10, volatility: 0.15 },
20///     ProductData { name: "Gadget", base_revenue: 50_000.0, growth_rate: 0.20, volatility: 0.25 },
21/// ];
22///
23/// let model = BayesianRevenueModel::new(products);
24/// let engine = MonteCarloEngine::reproducible(42).with_n_simulations(10_000);
25/// let result = engine.simulate(&model, &TimeHorizon::quarters(8));
26/// ```
27#[derive(Debug, Clone)]
28pub struct BayesianRevenueModel {
29    /// Product data
30    products: Vec<ProductData>,
31    /// Use correlated simulation
32    correlated: bool,
33}
34
35/// Individual product data
36#[derive(Debug, Clone)]
37pub struct ProductData {
38    /// Product name
39    pub name: String,
40    /// Base revenue (current period)
41    pub base_revenue: f64,
42    /// Expected growth rate per period
43    pub growth_rate: f64,
44    /// Volatility (standard deviation of growth)
45    pub volatility: f64,
46}
47
48impl BayesianRevenueModel {
49    /// Create a new Bayesian revenue model
50    #[must_use]
51    pub fn new(products: Vec<ProductData>) -> Self {
52        Self {
53            products,
54            correlated: false,
55        }
56    }
57
58    /// Enable correlated simulation (products move together)
59    #[must_use]
60    pub fn with_correlation(mut self) -> Self {
61        self.correlated = true;
62        self
63    }
64
65    /// Get total base revenue
66    #[must_use]
67    pub fn total_base_revenue(&self) -> f64 {
68        self.products.iter().map(|p| p.base_revenue).sum()
69    }
70
71    /// Get weighted average growth rate
72    #[must_use]
73    pub fn weighted_growth_rate(&self) -> f64 {
74        let total = self.total_base_revenue();
75        if total <= 0.0 {
76            return 0.0;
77        }
78        self.products
79            .iter()
80            .map(|p| p.growth_rate * p.base_revenue)
81            .sum::<f64>()
82            / total
83    }
84
85    /// Get weighted average volatility
86    #[must_use]
87    pub fn weighted_volatility(&self) -> f64 {
88        let total = self.total_base_revenue();
89        if total <= 0.0 {
90            return 0.0;
91        }
92        // Use sqrt of weighted variance for portfolio effect
93        let weighted_var: f64 = self
94            .products
95            .iter()
96            .map(|p| (p.volatility * p.base_revenue / total).powi(2))
97            .sum();
98        weighted_var.sqrt()
99    }
100}
101
102impl SimulationModel for BayesianRevenueModel {
103    fn name(&self) -> &'static str {
104        "BayesianRevenue"
105    }
106
107    fn generate_path(
108        &self,
109        rng: &mut MonteCarloRng,
110        time_horizon: &TimeHorizon,
111        path_id: usize,
112    ) -> SimulationPath {
113        let n = time_horizon.n_steps();
114        let dt = time_horizon.dt();
115
116        // Start with total base revenue
117        let initial = self.total_base_revenue();
118        let mu = self.weighted_growth_rate();
119        let sigma = self.weighted_volatility();
120
121        let mut values = Vec::with_capacity(n + 1);
122        let mut current = initial;
123        values.push(current);
124
125        // Common shock for correlation
126        let common_shock = if self.correlated {
127            rng.standard_normal()
128        } else {
129            0.0
130        };
131
132        for _ in 0..n {
133            // GBM-like growth with random shocks
134            let z = if self.correlated {
135                0.7 * common_shock + 0.3 * rng.standard_normal() // 70% correlated
136            } else {
137                rng.standard_normal()
138            };
139
140            // Log-normal growth
141            let growth = ((mu - 0.5 * sigma.powi(2)) * dt + sigma * dt.sqrt() * z).exp();
142            current *= growth;
143            values.push(current);
144        }
145
146        SimulationPath::new(
147            time_horizon.time_points(),
148            values,
149            PathMetadata {
150                path_id,
151                seed: rng.seed(),
152                is_antithetic: false,
153            },
154        )
155    }
156
157    fn generate_antithetic_path(
158        &self,
159        rng: &mut MonteCarloRng,
160        time_horizon: &TimeHorizon,
161        path_id: usize,
162    ) -> SimulationPath {
163        let n = time_horizon.n_steps();
164        let dt = time_horizon.dt();
165
166        let initial = self.total_base_revenue();
167        let mu = self.weighted_growth_rate();
168        let sigma = self.weighted_volatility();
169
170        let mut values = Vec::with_capacity(n + 1);
171        let mut current = initial;
172        values.push(current);
173
174        for _ in 0..n {
175            // Antithetic: negate the random shock
176            let z = -rng.standard_normal();
177            let growth = ((mu - 0.5 * sigma.powi(2)) * dt + sigma * dt.sqrt() * z).exp();
178            current *= growth;
179            values.push(current);
180        }
181
182        SimulationPath::new(
183            time_horizon.time_points(),
184            values,
185            PathMetadata {
186                path_id,
187                seed: rng.seed(),
188                is_antithetic: true,
189            },
190        )
191    }
192}
193
194/// Create a revenue model from CSV data
195impl ProductData {
196    /// Create a new product
197    #[must_use]
198    pub fn new(
199        name: impl Into<String>,
200        base_revenue: f64,
201        growth_rate: f64,
202        volatility: f64,
203    ) -> Self {
204        Self {
205            name: name.into(),
206            base_revenue,
207            growth_rate,
208            volatility,
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn test_bayesian_model_creation() {
219        let products = vec![
220            ProductData::new("Widget", 100_000.0, 0.10, 0.15),
221            ProductData::new("Gadget", 50_000.0, 0.20, 0.25),
222        ];
223
224        let model = BayesianRevenueModel::new(products);
225
226        assert!((model.total_base_revenue() - 150_000.0).abs() < 0.01);
227    }
228
229    #[test]
230    fn test_weighted_metrics() {
231        let products = vec![
232            ProductData::new("A", 100.0, 0.10, 0.20),
233            ProductData::new("B", 100.0, 0.20, 0.30),
234        ];
235
236        let model = BayesianRevenueModel::new(products);
237
238        // Equal weights: average should be midpoint
239        assert!((model.weighted_growth_rate() - 0.15).abs() < 0.01);
240    }
241
242    #[test]
243    fn test_simulation() {
244        let products = vec![ProductData::new("Test", 100_000.0, 0.10, 0.15)];
245
246        let model = BayesianRevenueModel::new(products);
247        let engine = MonteCarloEngine::reproducible(42).with_n_simulations(100);
248        let horizon = TimeHorizon::quarters(4);
249
250        let result = engine.simulate(&model, &horizon);
251
252        assert_eq!(result.n_paths(), 100);
253        assert!(result.final_value_statistics().mean > 0.0);
254    }
255
256    #[test]
257    fn test_correlated_simulation() {
258        let products = vec![
259            ProductData::new("A", 100_000.0, 0.10, 0.15),
260            ProductData::new("B", 50_000.0, 0.15, 0.20),
261        ];
262
263        let model = BayesianRevenueModel::new(products).with_correlation();
264        let engine = MonteCarloEngine::reproducible(42).with_n_simulations(100);
265        let horizon = TimeHorizon::quarters(4);
266
267        let result = engine.simulate(&model, &horizon);
268
269        assert_eq!(result.n_paths(), 100);
270    }
271}