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
//! Comprehensive Financial Analysis and Modeling
//!
//! This module provides a complete suite of financial analysis tools for quantitative
//! finance, algorithmic trading, and risk management. It implements SciPy-compatible
//! APIs while leveraging Rust's performance and safety features for financial modeling.
//!
//! # Module Organization
//!
//! ## Volatility Models
//! [`models`] - Time series volatility models for financial data:
//! - GARCH family models (GARCH, EGARCH, GJR-GARCH, APARCH)
//! - Model selection, estimation, and forecasting
//! - Asymmetric and leverage effects modeling
//! - In-sample and out-of-sample evaluation
//!
//! ## Technical Analysis
//! [`technical_indicators`] - Comprehensive technical analysis indicators:
//! - **Basic indicators**: SMA, EMA, RSI, MACD, Bollinger Bands, ATR
//! - **Advanced indicators**: Ichimoku, ADX, Parabolic SAR, VWAP, Stochastic
//! - **Volume indicators**: Chaikin Oscillator, MFI, OBV
//! - **Momentum indicators**: Williams %R, CCI, Aroon, KAMA
//! - Configurable parameters and multi-timeframe analysis
//!
//! ## Volatility Estimation
//! [`volatility`] - High-frequency volatility estimation techniques:
//! - **High-frequency estimators**: Garman-Klass, Rogers-Satchell, Yang-Zhang
//! - **Model-based estimators**: GARCH, EWMA (RiskMetrics)
//! - **Range-based estimators**: Parkinson, realized volatility
//! - Efficiency comparison and optimal estimator selection
//!
//! ## Risk Management
//! [`risk`] - Comprehensive risk analysis and measurement:
//! - **Value at Risk**: Historical, parametric, Monte Carlo methods
//! - **Expected Shortfall** (Conditional VaR) for tail risk
//! - **Risk-adjusted metrics**: Sharpe, Sortino, Information ratios
//! - **Drawdown analysis**: Maximum drawdown, recovery time, Pain Index
//! - Market risk measures (Beta, Alpha, Treynor ratio)
//!
//! ## Portfolio Management
//! [`portfolio`] - Modern portfolio theory and optimization:
//! - **Portfolio construction**: Mean-variance, risk parity, minimum variance
//! - **Performance analysis**: Comprehensive metrics and attribution
//! - **Risk decomposition**: Component VaR, factor analysis
//! - **Optimization algorithms**: Efficient frontier, maximum Sharpe ratio
//! - **Benchmarking**: Tracking error, information ratio, capture ratios
//!
//! ## Derivative Pricing
//! [`pricing`] - Financial instrument pricing models:
//! - **Black-Scholes**: European option pricing with Greeks
//! - **Implied volatility**: Market-based volatility extraction
//! - **Utility functions**: Present value, normal distributions
//! - Extensible framework for additional pricing models
//!
//! # Comprehensive Financial Analysis Workflow
//!
//! ## 1. Data Preparation and Preprocessing
//! ```rust,no_run
//! use scirs2_series::financial::{
//! volatility::realized_volatility,
//! technical_indicators::{sma, ema, rsi},
//! };
//! use scirs2_core::ndarray::array;
//!
//! // Prepare price and return data (extend for RSI calculation)
//! let prices = array![100.0, 102.0, 101.5, 103.0, 102.5, 104.0, 105.5, 104.0, 106.0, 107.0,
//! 106.5, 108.0, 107.5, 109.0, 108.5, 110.0, 111.5, 110.0, 112.0, 113.0];
//! let returns = array![0.02, -0.0049, 0.0148, -0.0049, 0.0146, 0.0144, -0.0142, 0.0192, 0.0094,
//! -0.0047, 0.0141, -0.0046, 0.0140, -0.0046, 0.0138, 0.0136, -0.0135, 0.0182, 0.0089];
//!
//! // Calculate basic technical indicators
//! let sma_5 = sma(&prices, 5).expect("should succeed");
//! let ema_5 = ema(&prices, 0.2).expect("should succeed");
//! let rsi_14 = rsi(&prices, 14).expect("should succeed");
//!
//! // Estimate realized volatility
//! let vol = realized_volatility(&returns);
//! println!("Realized volatility: {:.4}", vol);
//! ```
//!
//! ## 2. Volatility Modeling and Forecasting
//! ```rust,no_run
//! use scirs2_series::financial::{
//! models::{GarchModel, GarchConfig},
//! volatility::{garman_klass_volatility, ewma_volatility},
//! };
//!
//! // Create larger returns dataset for GARCH fitting
//! let extended_returns = (0..100).map(|i| {
//! 0.01 * (i as f64 * 0.1).sin() + 0.005 * ((i as f64 * 0.05).cos() - 1.0)
//! }).collect::<Vec<f64>>();
//! let returns_array = scirs2_core::ndarray::Array1::from_vec(extended_returns);
//!
//! // Fit GARCH model for volatility forecasting
//! let mut garch_model = GarchModel::new(GarchConfig::default());
//! let garch_result = garch_model.fit(&returns_array).expect("should succeed");
//! println!("GARCH Log-likelihood: {:.2}", garch_result.log_likelihood);
//!
//! // Compare with high-frequency estimator (if OHLC data available)
//! // let high = array![...]; let low = array![...]; let close = array![...]; let open = array![...];
//! // let gk_vol = garman_klass_volatility(&high, &low, &close, &open).expect("should succeed");
//!
//! // EWMA volatility (RiskMetrics approach)
//! let ewma_vol = ewma_volatility(&returns_array, 0.94).expect("should succeed");
//! println!("EWMA volatility: {:.4}", ewma_vol);
//! ```
//!
//! ## 3. Risk Analysis and Management
//! ```rust,no_run
//! use scirs2_series::financial::risk::{
//! var_historical, expected_shortfall, max_drawdown,
//! sharpe_ratio, sortino_ratio, calmar_ratio,
//! };
//!
//! // Calculate VaR and Expected Shortfall (use extended returns)
//! let returns_array = scirs2_core::ndarray::array![0.02, -0.0049, 0.0148, -0.0049, 0.0146, 0.0144];
//! let var_95 = var_historical(&returns_array, 0.95).expect("should succeed");
//! let es_95 = expected_shortfall(&returns_array, 0.95).expect("should succeed");
//! println!("95% VaR: {:.4}, 95% ES: {:.4}", var_95, es_95);
//!
//! // Risk-adjusted performance metrics
//! let risk_free_rate = 0.02;
//! let periods_per_year = 252;
//! let sharpe = sharpe_ratio(&returns_array, risk_free_rate, periods_per_year).expect("should succeed");
//! let sortino = sortino_ratio(&returns_array, risk_free_rate, periods_per_year).expect("should succeed");
//!
//! // Drawdown analysis (extend prices for drawdown calculation)
//! let extended_prices = (0..100).scan(100.0, |price, i| {
//! let return_val = 0.01 * (i as f64 * 0.1).sin() + 0.005 * ((i as f64 * 0.05).cos() - 1.0);
//! *price *= 1.0 + return_val;
//! Some(*price)
//! }).collect::<Vec<f64>>();
//! let prices_array = scirs2_core::ndarray::Array1::from_vec(extended_prices);
//! let max_dd = max_drawdown(&prices_array).expect("should succeed");
//! let calmar = calmar_ratio(&returns_array, &prices_array, periods_per_year).expect("should succeed");
//!
//! println!("Sharpe: {:.3}, Sortino: {:.3}, Calmar: {:.3}", sharpe, sortino, calmar);
//! println!("Max Drawdown: {:.2}%", max_dd * 100.0);
//! ```
//!
//! ## 4. Portfolio Construction and Optimization
//! ```rust,no_run
//! use scirs2_series::financial::portfolio::{
//! Portfolio, risk_parity_portfolio, minimum_variance_portfolio,
//! calculate_portfolio_returns, calculate_portfolio_metrics,
//! };
//! use scirs2_core::ndarray::{Array2, array};
//!
//! // Multi-asset portfolio optimization
//! let asset_names = vec!["AAPL".to_string(), "GOOGL".to_string(), "MSFT".to_string()];
//!
//! // Prepare return matrix (rows: time, cols: assets)
//! // let asset_returns = Array2::from_shape_vec((252, 3), return_data).expect("should succeed");
//!
//! // Risk parity portfolio
//! // let correlation_matrix = calculate_correlation_matrix(&asset_returns).expect("should succeed");
//! // let risk_parity_weights = risk_parity_portfolio(&correlation_matrix).expect("should succeed");
//! // let portfolio = Portfolio::new(risk_parity_weights, asset_names.clone()).expect("should succeed");
//!
//! // Calculate portfolio performance
//! // let portfolio_returns = calculate_portfolio_returns(&asset_returns, portfolio.weights()).expect("should succeed");
//! // let portfolio_metrics = calculate_portfolio_metrics(&portfolio_returns, &portfolio_prices, risk_free_rate, periods_per_year).expect("should succeed");
//! ```
//!
//! ## 5. Derivative Pricing and Greeks Analysis
//! ```rust,no_run
//! use scirs2_series::financial::pricing::{
//! black_scholes, black_scholes_greeks, implied_volatility,
//! };
//!
//! // Option pricing
//! let spot_price = 100.0;
//! let strike_price = 105.0;
//! let time_to_expiry = 0.25; // 3 months
//! let risk_free_rate = 0.05;
//! let volatility = 0.20;
//!
//! // Price call and put options
//! let call_price = black_scholes(spot_price, strike_price, time_to_expiry,
//! risk_free_rate, volatility, true).expect("should succeed");
//! let put_price = black_scholes(spot_price, strike_price, time_to_expiry,
//! risk_free_rate, volatility, false).expect("should succeed");
//!
//! // Calculate Greeks for risk management
//! let greeks = black_scholes_greeks(spot_price, strike_price, time_to_expiry,
//! risk_free_rate, volatility, true).expect("should succeed");
//!
//! println!("Call: ${:.2}, Put: ${:.2}", call_price, put_price);
//! println!("Delta: {:.4}, Gamma: {:.6}, Vega: {:.4}", greeks.delta, greeks.gamma, greeks.vega);
//!
//! // Implied volatility from market price
//! let market_price = 8.5;
//! if let Ok(impl_vol) = implied_volatility(market_price, spot_price, strike_price,
//! time_to_expiry, risk_free_rate, true) {
//! println!("Implied volatility: {:.2}%", impl_vol * 100.0);
//! }
//! ```
//!
//! ## 6. Advanced Technical Analysis
//! ```rust,no_run
//! use scirs2_series::financial::technical_indicators::{
//! advanced_bollinger_bands, advanced_stochastic_oscillator, BollingerBandsConfig, StochasticConfig, IchimokuCloud,
//! adx, parabolic_sar, vwap, chaikin_oscillator, MovingAverageType,
//! };
//!
//! // Advanced technical indicators (use extended prices)
//! let prices_array = scirs2_core::ndarray::array![100.0, 101.0, 102.0, 101.5, 103.0, 102.5, 104.0, 103.5, 105.0, 104.5, 106.0];
//! let bb_conf = BollingerBandsConfig { period: 5, std_dev_multiplier: 2.0, ma_type: MovingAverageType::Simple };
//! let bb_result = advanced_bollinger_bands(&prices_array, &bb_conf).expect("should succeed");
//! println!("Bollinger Bands - Upper: {:.2}, Lower: {:.2}", bb_result.upper_band[0], bb_result.lower_band[0]);
//!
//! // Momentum and trend indicators
//! let stoch_conf = StochasticConfig { k_period: 14, d_period: 3, d_smoothing: MovingAverageType::Simple };
//! // let stoch_result = advanced_stochastic_oscillator(&high, &low, &close, &stoch_conf).expect("should succeed");
//!
//! // let adx_values = adx(&high, &low, &close, 14).expect("should succeed");
//! // let sar_values = parabolic_sar(&high, &low, 0.02, 0.2).expect("should succeed");
//! ```
//!
//! # Integration with SciRS2 Ecosystem
//!
//! The financial module seamlessly integrates with other SciRS2 modules:
//!
//! ## Time Series Analysis
//! - Integration with scirs2-series for time series modeling
//! - Combined ARIMA-GARCH modeling for returns and volatility
//!
//! ## Statistical Analysis
//! - Integration with scirs2-stats for hypothesis testing
//! - Statistical tests for model validation and backtesting
//!
//! ## Optimization
//! - Integration with scirs2-optimize for advanced portfolio optimization
//! - Constrained optimization with transaction costs and constraints
//!
//! ## Machine Learning
//! - Integration with scirs2-neural for predictive modeling
//! - Neural network-based volatility and return forecasting
//!
//! # Performance and Scalability
//!
//! ## Computational Efficiency
//! - Optimized numerical algorithms with minimal allocations
//! - SIMD operations for vectorized calculations
//! - Parallel processing for portfolio and Monte Carlo operations
//! - Memory-efficient implementations for large datasets
//!
//! ## Production Ready
//! - Comprehensive error handling with detailed error messages
//! - Input validation and edge case handling
//! - Extensive test coverage with property-based testing
//! - Benchmarking against SciPy and industry standards
//!
//! # Industry Applications
//!
//! ## Asset Management
//! - Portfolio construction and rebalancing
//! - Risk budgeting and factor modeling
//! - Performance attribution and evaluation
//! - ESG integration and constraints
//!
//! ## Risk Management
//! - Market risk measurement (VaR, ES)
//! - Stress testing and scenario analysis
//! - Credit risk modeling and correlation
//! - Operational risk quantification
//!
//! ## Trading and Market Making
//! - Real-time option pricing and Greeks
//! - Volatility surface construction
//! - Algorithmic trading signal generation
//! - Market microstructure analysis
//!
//! ## Regulatory Compliance
//! - Basel III capital requirements
//! - CCAR stress testing
//! - FRTB market risk modeling
//! - IFRS 17 insurance modeling
//!
//! # Future Development Roadmap
//!
//! ## Additional Models
//! - Jump diffusion models (Merton, Kou)
//! - Stochastic volatility models (Heston, SABR)
//! - Credit risk models (Merton, reduced form)
//! - Interest rate models (Vasicek, CIR, HJM)
//!
//! ## Advanced Pricing
//! - American option pricing (binomial, trinomial)
//! - Exotic options (barrier, Asian, lookback)
//! - Fixed income derivatives (bonds, swaps, caps/floors)
//! - Energy and commodity derivatives
//!
//! ## Machine Learning Integration
//! - Neural network volatility forecasting
//! - Reinforcement learning for portfolio optimization
//! - Alternative data integration
//! - ESG factor modeling
// Re-export the most commonly used types and functions for convenience
// Volatility models
pub use ;
// Technical indicators (basic)
pub use ;
// Technical indicators (advanced)
pub use ;
// Volatility estimators
pub use ;
// Risk management
pub use ;
// Portfolio management
pub use ;
// Pricing models
pub use ;