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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! # Surface-Lib: Advanced Option Pricing and Volatility Surface Calibration
//!
//! `surface-lib` is a high-performance Rust library designed for quantitative finance applications,
//! specifically focused on option pricing and volatility surface modeling. The library provides
//! robust implementations of industry-standard models with advanced calibration capabilities.
//!
//! ## Core Features
//!
//! - **SVI Model**: Stochastic Volatility Inspired model for volatility surface representation
//! - **Advanced Calibration**: CMA-ES and L-BFGS-B optimization with robust parameter estimation
//! - **Option Pricing**: Black-Scholes pricing with model-derived implied volatilities
//! - **Production Ready**: Optimized for real-time trading and backtesting systems
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use surface_lib::{calibrate_svi, price_with_svi, default_configs, CalibrationParams, MarketDataRow, FixedParameters};
//! use surface_lib::models::svi::svi_model::SVIParams;
//!
//! # fn load_market_data() -> Vec<MarketDataRow> { vec![] }
//! // Load your market data
//! let market_data: Vec<MarketDataRow> = load_market_data();
//!
//! // Calibrate SVI model parameters
//! let config = default_configs::fast();
//! let calib_params = CalibrationParams::default();
//! let (objective, params, used_bounds) = calibrate_svi(market_data.clone(), config, calib_params, None)?;
//!
//! // Create SVI parameters for pricing
//! let svi_params = SVIParams {
//! t: 0.0274, a: params[0], b: params[1],
//! rho: params[2], m: params[3], sigma: params[4]
//! };
//! let fixed_params = FixedParameters { r: 0.02, q: 0.0 };
//!
//! // Price options with calibrated model
//! let pricing_results = price_with_svi(svi_params, market_data, fixed_params);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Model Support
//!
//! Currently supported volatility models:
//! - **SVI (Stochastic Volatility Inspired)**: Industry-standard single-slice model
//!
//! ## Configuration Presets
//!
//! The library provides several optimization configuration presets:
//! - `production()`: High accuracy for live trading systems
//! - `fast()`: Balanced speed/accuracy for development
//! - `research()`: High-precision settings for research
//! - `minimal()`: Quick validation settings
// ================================================================================================
// MODULES
// ================================================================================================
// ================================================================================================
// IMPORTS
// ================================================================================================
// Note: HashMap removed as it's no longer used in the API
use Result;
use Ordering;
use ;
use ;
// (removed - using public re-export instead)
use cratecalibrate_model_adaptive;
// ================================================================================================
// PUBLIC RE-EXPORTS
// ================================================================================================
// Core types for market data and configuration
pub use ;
// SVI model types and parameters
pub use ;
// Linear IV model types and functions
pub use ;
// Model parameter types
pub use ;
// Model parameters for users
// ================================================================================================
// DEFAULT CONFIGURATIONS
// ================================================================================================
/// Pre-configured optimization settings for common use cases.
///
/// This module provides several optimization configuration presets tailored for different
/// scenarios, from rapid development to high-precision production trading systems.
///
/// # Available Configurations
///
/// - [`production()`]: Production-grade settings for live trading
/// - [`fast()`]: Development-optimized settings
/// - [`research()`]: High-precision settings for research
/// - [`minimal()`]: Quick validation settings
/// Configuration parameters for SVI model calibration.
/// Calibrate SVI model parameters to market option data.
///
/// This function performs advanced optimization to fit SVI model parameters to observed market
/// implied volatilities. The optimization uses a two-stage approach: global search with CMA-ES
/// followed by local refinement with L-BFGS-B for robust parameter estimation.
///
/// # Arguments
///
/// * `data` - Market option data for a single expiration. Must contain option type, strikes,
/// underlying price, time to expiration, market implied volatilities, and vega values.
/// * `config` - Optimization configuration specifying algorithm parameters, tolerances, and
/// computational limits. Use [`default_configs`] for common presets.
/// * `calib_params` - Calibration-specific parameters controlling log-moneyness range, arbitrage
/// checking, and penalty weights. Use [`CalibrationParams::default()`] for standard settings.
///
/// # Returns
///
/// Returns a tuple containing:
/// - `f64`: Final objective function value (lower is better)
/// - `Vec<f64>`: Optimized SVI parameters `[a, b, rho, m, sigma]`
/// - `SVIParamBounds`: The actual bounds used during optimization (can be fed back as input)
///
/// # Errors
///
/// * `anyhow::Error` if the data contains multiple expirations (SVI requires single expiration)
/// * `anyhow::Error` if market data is insufficient or contains invalid values
/// * `anyhow::Error` if optimization fails to converge within specified limits
///
/// # SVI Parameters
///
/// The SVI model parameterizes total variance as:
/// ```text
/// w(k) = a + b * (ρ(k-m) + sqrt((k-m)² + σ²))
/// ```
/// Where:
/// - `a`: Base variance level (vertical shift)
/// - `b`: Slope factor (overall variance level)
/// - `ρ`: Asymmetry parameter (skew, must be in (-1, 1))
/// - `m`: Horizontal shift (ATM location in log-moneyness)
/// - `σ`: Curvature parameter (smile curvature, must be > 0)
///
/// # Example
///
/// ```rust,no_run
/// use surface_lib::{calibrate_svi, default_configs, CalibrationParams, MarketDataRow};
///
/// // Load market data for a single expiration
/// let market_data: Vec<MarketDataRow> = load_single_expiry_data();
///
/// // Use fast configuration for development
/// let config = default_configs::fast();
/// let calib_params = CalibrationParams::default();
///
/// // Calibrate SVI parameters
/// match calibrate_svi(market_data, config, calib_params, None) {
/// Ok((objective, params, used_bounds)) => {
/// println!("Calibration successful!");
/// println!("Final objective: {:.6}", objective);
/// println!("SVI parameters: {:?}", params);
/// println!("Used bounds: {:?}", used_bounds);
/// }
/// Err(e) => eprintln!("Calibration failed: {}", e),
/// }
/// # fn load_single_expiry_data() -> Vec<MarketDataRow> { vec![] }
/// ```
///
/// # Performance Notes
///
/// - Calibration typically takes 1-10 seconds depending on configuration and data size
/// - Memory usage scales linearly with the number of option contracts
/// - For production systems, consider using [`default_configs::production()`] for optimal accuracy
/// Evaluate the SVI calibration objective for a fixed parameter set.
///
/// This produces **exactly the same loss value** that `calibrate_svi` minimises
/// internally, honouring any ATM-boost and vega-weighting settings embedded in
/// `calib_params`. It enables external callers (e.g. live monitoring) to
/// measure model fit quality without re-running the optimiser.
/// Price European options using calibrated SVI model parameters.
///
/// This function takes pre-calibrated SVI parameters and applies them to price a set of options
/// using the Black-Scholes framework with SVI-derived implied volatilities. The pricing is
/// efficient and suitable for real-time applications.
///
/// # Arguments
///
/// * `params` - Calibrated SVI parameters containing the time to expiration and model coefficients
/// * `market_data` - Option contracts to price (can be same or different from calibration data)
/// * `fixed_params` - Market parameters including risk-free rate and dividend yield
///
/// # Returns
///
/// Vector of [`PricingResult`] containing option details, model prices, and implied volatilities.
/// Results are sorted by strike price in ascending order.
///
/// # Pricing Methodology
///
/// 1. **Log-moneyness calculation**: `k = ln(K/S)` for each option
/// 2. **SVI implied volatility**: `σ(k) = sqrt(w(k)/t)` where `w(k)` is SVI total variance
/// 3. **Black-Scholes pricing**: European option price using SVI-derived volatility
/// 4. **Result compilation**: Organized results with validation and error handling
///
/// # Example
///
/// ```rust,no_run
/// use surface_lib::{
/// price_with_svi, MarketDataRow, FixedParameters,
/// models::svi::svi_model::SVIParams
/// };
///
/// # let market_data: Vec<MarketDataRow> = vec![];
/// // Create SVI parameters (typically from calibration)
/// let svi_params = SVIParams {
/// t: 0.0274, // ~10 days to expiration
/// a: 0.04, // Base variance
/// b: 0.2, // Slope factor
/// rho: -0.3, // Negative skew
/// m: 0.0, // ATM at log-moneyness 0
/// sigma: 0.2, // Curvature
/// };
///
/// // Market parameters
/// let fixed_params = FixedParameters {
/// r: 0.02, // 2% risk-free rate
/// q: 0.0, // No dividend yield
/// };
///
/// // Price options
/// let pricing_results = price_with_svi(svi_params, market_data, fixed_params);
///
/// for result in &pricing_results {
/// println!("Strike {}: Price ${:.2}, IV {:.1}%",
/// result.strike_price,
/// result.model_price,
/// result.model_iv * 100.0);
/// }
/// ```
///
/// # Error Handling
///
/// The function uses robust error handling:
/// - Invalid pricing results default to zero price and implied volatility
/// - Time mismatches between SVI parameters and market data are handled gracefully
/// - Non-finite or negative volatilities are caught and logged
///
/// # Performance Notes
///
/// - Pricing scales linearly with the number of options
/// - Typical performance: 10,000+ options per second on modern hardware
/// - Memory usage is minimal with in-place calculations