Skip to main content

aprender_monte_carlo/cli/
mod.rs

1//! Command-line interface for Monte Carlo simulations
2
3use clap::{Parser, Subcommand, ValueEnum};
4use std::path::PathBuf;
5
6/// Monte Carlo simulation tool for financial modeling and risk analysis
7#[derive(Parser, Debug)]
8#[command(name = "aprender-monte-carlo")]
9#[command(author = "paiml")]
10#[command(version = "0.1.0")]
11#[command(about = "Monte Carlo simulations for finance and business forecasting")]
12#[command(long_about = r#"
13Monte Carlo simulation tool for:
14  - Stock market analysis using S&P 500 historical data
15  - Business revenue forecasting with Bayesian models
16  - Custom data analysis from CSV files
17
18Examples:
19  # Simulate 30-year retirement portfolio using S&P 500 returns
20  aprender-monte-carlo sp500 --years 30 --initial 100000 --simulations 10000
21
22  # Analyze custom return data from CSV
23  aprender-monte-carlo csv --file returns.csv --initial 50000 --years 10
24
25  # Business revenue forecast
26  aprender-monte-carlo revenue --file products.csv --quarters 8
27"#)]
28pub struct Cli {
29    /// Output format
30    #[arg(short, long, value_enum, default_value_t = OutputFormat::Table)]
31    pub format: OutputFormat,
32
33    /// Random seed for reproducibility
34    #[arg(short, long, default_value_t = 42)]
35    pub seed: u64,
36
37    /// Enable verbose output
38    #[arg(short, long)]
39    pub verbose: bool,
40
41    /// The subcommand to run
42    #[command(subcommand)]
43    pub command: Commands,
44}
45
46/// Available commands
47#[derive(Subcommand, Debug)]
48pub enum Commands {
49    /// Run simulation using embedded S&P 500 historical data
50    Sp500 {
51        /// Simulation horizon in years
52        #[arg(short, long, default_value_t = 30)]
53        years: u32,
54
55        /// Number of simulations to run
56        #[arg(short = 'n', long, default_value_t = 10000)]
57        simulations: usize,
58
59        /// Initial portfolio value
60        #[arg(short, long, default_value_t = 100_000.0)]
61        initial: f64,
62
63        /// Annual withdrawal rate (e.g., 0.04 for 4%)
64        #[arg(short, long)]
65        withdrawal_rate: Option<f64>,
66
67        /// Use inflation-adjusted returns
68        #[arg(long)]
69        real_returns: bool,
70    },
71
72    /// Load and simulate from a CSV file
73    Csv {
74        /// Path to CSV file with returns data
75        #[arg(short, long)]
76        file: PathBuf,
77
78        /// Column name containing returns (default: first numeric column)
79        #[arg(short, long)]
80        column: Option<String>,
81
82        /// Simulation horizon in years
83        #[arg(short = 'y', long, default_value_t = 10)]
84        years: u32,
85
86        /// Number of simulations to run
87        #[arg(short = 'n', long, default_value_t = 10000)]
88        simulations: usize,
89
90        /// Initial value
91        #[arg(short, long, default_value_t = 100.0)]
92        initial: f64,
93    },
94
95    /// Business revenue forecasting
96    Revenue {
97        /// Path to CSV file with product data
98        #[arg(short, long)]
99        file: PathBuf,
100
101        /// Forecast horizon in quarters
102        #[arg(short, long, default_value_t = 4)]
103        quarters: u32,
104
105        /// Number of simulations to run
106        #[arg(short = 'n', long, default_value_t = 10000)]
107        simulations: usize,
108
109        /// Use Bayesian prior from historical data
110        #[arg(long)]
111        bayesian: bool,
112    },
113
114    /// Show embedded S&P 500 data statistics
115    Stats {
116        /// Show monthly statistics
117        #[arg(long)]
118        monthly: bool,
119
120        /// Show decade-by-decade breakdown
121        #[arg(long)]
122        decades: bool,
123    },
124}
125
126/// Output format options
127#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
128pub enum OutputFormat {
129    /// Human-readable table format
130    Table,
131    /// JSON format for programmatic use
132    Json,
133    /// CSV format for spreadsheets
134    Csv,
135}
136
137impl Cli {
138    /// Parse command-line arguments
139    #[must_use]
140    pub fn parse_args() -> Self {
141        Self::parse()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn test_cli_parse_sp500() {
151        let cli = Cli::try_parse_from([
152            "aprender-monte-carlo",
153            "sp500",
154            "--years",
155            "20",
156            "--simulations",
157            "5000",
158        ])
159        .expect("Should parse");
160
161        match cli.command {
162            Commands::Sp500 {
163                years, simulations, ..
164            } => {
165                assert_eq!(years, 20);
166                assert_eq!(simulations, 5000);
167            }
168            _ => panic!("Expected Sp500 command"),
169        }
170    }
171
172    #[test]
173    fn test_cli_parse_csv() {
174        let cli = Cli::try_parse_from([
175            "aprender-monte-carlo",
176            "csv",
177            "--file",
178            "test.csv",
179            "--initial",
180            "50000",
181        ])
182        .expect("Should parse");
183
184        match cli.command {
185            Commands::Csv { initial, file, .. } => {
186                assert!((initial - 50000.0).abs() < 0.01);
187                assert_eq!(file.to_string_lossy(), "test.csv");
188            }
189            _ => panic!("Expected Csv command"),
190        }
191    }
192
193    #[test]
194    fn test_output_format() {
195        let cli = Cli::try_parse_from(["aprender-monte-carlo", "--format", "json", "sp500"])
196            .expect("Should parse");
197
198        assert_eq!(cli.format, OutputFormat::Json);
199    }
200}