libitofin 0.45.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
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
//! Finance-independent global solvers adapted to QuantLib calibration problems.

use crate::errors::{QlError, QlResult};
use crate::math::array::Array;
use crate::math::optimization::endcriteria::{EndCriteria, EndCriteriaType};
use crate::math::optimization::method::OptimizationMethod;
use crate::math::optimization::problem::Problem;
use crate::require;
use itofin_optimize::{
    Bounds, Common, Converged, DifferentialEvolutionOptions, FireflyOptions,
    HybridSimulatedAnnealingOptions, Method, Minimize, MinimizeError, ParticleSwarmOptions,
    Problem as ScalarProblem, Termination, minimize,
};

#[derive(Debug, Clone)]
struct CalibrationAdapter {
    bounds: Bounds,
    method: Method,
    common: Common,
    last_result: Option<Minimize>,
}

impl CalibrationAdapter {
    fn new(bounds: Bounds, method: Method, common: Common) -> QlResult<Self> {
        require!(
            bounds
                .lower
                .iter()
                .chain(&bounds.upper)
                .all(|v| v.is_finite()),
            "{} calibration requires finite bounds",
            solver_name(&method)
        );
        let validation = ScalarProblem {
            x0: bounds.lower.clone(),
            bounds: Some(bounds.clone()),
        };
        validate(&validation, &method, &common)?;
        let common = budgets(&method, &common)?;
        Ok(Self {
            bounds,
            method,
            common,
            last_result: None,
        })
    }

    fn last_result(&self) -> Option<&Minimize> {
        self.last_result.as_ref()
    }
}

fn budgets(method: &Method, common: &Common) -> QlResult<Common> {
    let result = match method {
        Method::DifferentialEvolution(options) => options.budgets(common),
        Method::ParticleSwarm(options) => options.budgets(common),
        Method::Firefly(options) => options.budgets(common),
        Method::HybridSimulatedAnnealing(options) => options.budgets(common),
        _ => return Err(ql_error("calibration adapter requires a global solver")),
    };
    result.map_err(|e| ql_error(e.to_string()))
}

fn solver_name(method: &Method) -> &'static str {
    match method {
        Method::ParticleSwarm(_) => "particle swarm",
        Method::Firefly(_) => "firefly",
        Method::HybridSimulatedAnnealing(_) => "hybrid simulated annealing",
        _ => "differential evolution",
    }
}

fn ql_error(message: impl Into<String>) -> QlError {
    QlError::new(message, file!(), line!())
}

fn validate(problem: &ScalarProblem, method: &Method, common: &Common) -> QlResult<()> {
    problem.validate().map_err(|e| ql_error(e.to_string()))?;
    common.validate().map_err(|e| ql_error(e.to_string()))?;
    method
        .validate(problem)
        .map_err(|e| ql_error(e.to_string()))?;
    budgets(method, common)?;
    Ok(())
}

impl CalibrationAdapter {
    fn minimize(
        &mut self,
        problem: &mut Problem<'_>,
        end_criteria: &EndCriteria,
    ) -> QlResult<EndCriteriaType> {
        self.last_result = None;
        let initial = problem.current_value().clone();
        require!(
            initial.size() == self.bounds.lower.len(),
            "calibration bounds must match the free parameter count"
        );
        require!(
            problem.constraint().test(&initial),
            "initial calibration parameters violate the constraint"
        );
        let lower = problem.constraint().lower_bound(&initial);
        let upper = problem.constraint().upper_bound(&initial);
        require!(
            lower.size() == initial.size() && upper.size() == initial.size(),
            "constraint bounds must match the free parameter count"
        );
        require!(
            lower.iter().chain(upper.iter()).all(|v| !v.is_nan()),
            "constraint bounds must not contain NaN"
        );
        let bounds = Bounds {
            lower: self
                .bounds
                .lower
                .iter()
                .zip(lower.iter())
                .map(|(a, b)| a.max(*b))
                .collect(),
            upper: self
                .bounds
                .upper
                .iter()
                .zip(upper.iter())
                .map(|(a, b)| a.min(*b))
                .collect(),
        };
        require!(
            bounds
                .lower
                .iter()
                .zip(&bounds.upper)
                .all(|(lower, upper)| lower <= upper),
            "calibration bounds have an empty constraint intersection"
        );
        let x0: Vec<f64> = initial
            .iter()
            .zip(bounds.lower.iter().zip(&bounds.upper))
            .map(|(value, (lower, upper))| value.clamp(*lower, *upper))
            .collect();
        require!(
            problem.constraint().test(&Array::from(x0.clone())),
            "bounded initial calibration candidate violates the constraint"
        );
        let scalar = ScalarProblem {
            x0,
            bounds: Some(bounds),
        };
        let common = Common {
            maxiter: Some(
                self.common
                    .maxiter
                    .unwrap_or(end_criteria.max_iterations())
                    .min(end_criteria.max_iterations()),
            ),
            ..self.common.clone()
        };
        validate(&scalar, &self.method, &common)?;
        problem.reset();
        let mut objective = |coordinates: &[f64]| -> QlResult<f64> {
            let candidate = Array::from(coordinates.to_vec());
            require!(
                problem.constraint().test(&candidate),
                "{} candidate violates the calibration constraint; supply a wholly feasible box",
                solver_name(&self.method)
            );
            Ok(problem.value(&candidate))
        };
        let result =
            minimize(&mut objective, &scalar, &self.method, &common).map_err(
                |error| match error {
                    MinimizeError::InvalidInput(error) => ql_error(error.to_string()),
                    MinimizeError::Objective(error) => error,
                },
            )?;
        let outcome = match result.status {
            Termination::Converged(Converged::XTol) => Ok(EndCriteriaType::StationaryPoint),
            Termination::Converged(Converged::FTol) => Ok(EndCriteriaType::StationaryFunctionValue),
            Termination::MaxIterations => Ok(EndCriteriaType::MaxIterations),
            Termination::MaxEvaluations => Ok(EndCriteriaType::Unknown),
            status => Err(ql_error(format!("global calibration stopped: {status}"))),
        };
        if outcome.is_ok() {
            problem.set_current_value(Array::from(result.x.clone()));
            problem.set_function_value(result.fun);
        }
        self.last_result = Some(result);
        outcome
    }
}

/// Bounded differential evolution accepted by model calibration.
///
/// Bounds and explicit populations use the projected, free-parameter order.
/// The supplied box must be wholly feasible for the model constraint. Every
/// candidate is tested before pricing; a rejected candidate aborts the run
/// rather than evaluating invalid model parameters or inventing a penalty.
/// General coupled constraints are not supported by this box-based search.
#[derive(Debug, Clone)]
pub struct DifferentialEvolution {
    adapter: CalibrationAdapter,
}

impl DifferentialEvolution {
    /// Constructs a solver with explicit finite bounds and deterministic seed.
    ///
    /// # Errors
    /// Rejects invalid bounds, options or budgets. Calibration evaluation
    /// budgets are capped at ten million to keep legacy integer counts safe.
    pub fn new(
        bounds: Bounds,
        options: DifferentialEvolutionOptions,
        common: Common,
    ) -> QlResult<Self> {
        Ok(Self {
            adapter: CalibrationAdapter::new(
                bounds,
                Method::DifferentialEvolution(options),
                common,
            )?,
        })
    }

    /// The exact optimizer outcome of the last completed solver invocation.
    ///
    /// Exhaustion is retained without claiming convergence. Invalid input and
    /// objective failures during invocation clear previous results; earlier
    /// model preflight failures retain them. Nonfinite termination retains
    /// diagnostics while returning a calibration error.
    pub fn last_result(&self) -> Option<&Minimize> {
        self.adapter.last_result()
    }
}

impl OptimizationMethod for DifferentialEvolution {
    fn minimize(
        &mut self,
        problem: &mut Problem<'_>,
        end_criteria: &EndCriteria,
    ) -> QlResult<EndCriteriaType> {
        self.adapter.minimize(problem, end_criteria)
    }

    fn global_result(&self) -> Option<&Minimize> {
        self.last_result()
    }
}

/// Bounded particle swarm accepted by model calibration.
///
/// Bounds and explicit populations use the projected, free-parameter order.
/// The supplied box must be wholly feasible for the model constraint. Every
/// candidate is tested before pricing; a rejected candidate aborts the run
/// rather than evaluating invalid model parameters or inventing a penalty.
/// General coupled constraints are not supported by this box-based search.
#[derive(Debug, Clone)]
pub struct ParticleSwarm {
    adapter: CalibrationAdapter,
}

impl ParticleSwarm {
    /// Constructs a solver with explicit finite bounds and deterministic seed.
    ///
    /// # Errors
    /// Rejects invalid bounds, options or budgets. Calibration evaluation
    /// budgets are capped at ten million to keep legacy integer counts safe.
    pub fn new(bounds: Bounds, options: ParticleSwarmOptions, common: Common) -> QlResult<Self> {
        Ok(Self {
            adapter: CalibrationAdapter::new(bounds, Method::ParticleSwarm(options), common)?,
        })
    }

    /// The exact optimizer outcome of the last completed solver invocation.
    ///
    /// Exhaustion is retained without claiming convergence. Invalid input and
    /// objective failures during invocation clear previous results; earlier
    /// model preflight failures retain them. Nonfinite termination retains
    /// diagnostics while returning a calibration error.
    pub fn last_result(&self) -> Option<&Minimize> {
        self.adapter.last_result()
    }
}

impl OptimizationMethod for ParticleSwarm {
    fn minimize(
        &mut self,
        problem: &mut Problem<'_>,
        end_criteria: &EndCriteria,
    ) -> QlResult<EndCriteriaType> {
        self.adapter.minimize(problem, end_criteria)
    }

    fn global_result(&self) -> Option<&Minimize> {
        self.last_result()
    }
}

/// Bounded hybrid simulated annealing accepted by model calibration.
///
/// Bounds use the projected, free-parameter order. The supplied box must be
/// wholly feasible for the model constraint. Random proposals and local polls
/// are checked before pricing; rejected candidates abort without penalties.
/// General coupled constraints are not supported by this box-based search.
#[derive(Debug, Clone)]
pub struct HybridSimulatedAnnealing {
    adapter: CalibrationAdapter,
}

impl HybridSimulatedAnnealing {
    /// Constructs a solver with explicit finite bounds and a deterministic seed.
    ///
    /// # Errors
    /// Rejects invalid bounds, schedules, local-search options or budgets.
    /// Evaluation budgets are capped at ten million for legacy integer counts.
    pub fn new(
        bounds: Bounds,
        options: HybridSimulatedAnnealingOptions,
        common: Common,
    ) -> QlResult<Self> {
        Ok(Self {
            adapter: CalibrationAdapter::new(
                bounds,
                Method::HybridSimulatedAnnealing(options),
                common,
            )?,
        })
    }

    /// The exact optimizer outcome of the last completed solver invocation.
    ///
    /// Exhaustion is retained without claiming convergence. Invalid input and
    /// objective failures during invocation clear previous results; earlier
    /// model preflight failures retain them. Nonfinite termination retains
    /// diagnostics while returning a calibration error.
    pub fn last_result(&self) -> Option<&Minimize> {
        self.adapter.last_result()
    }
}

impl OptimizationMethod for HybridSimulatedAnnealing {
    fn minimize(
        &mut self,
        problem: &mut Problem<'_>,
        end_criteria: &EndCriteria,
    ) -> QlResult<EndCriteriaType> {
        self.adapter.minimize(problem, end_criteria)
    }

    fn global_result(&self) -> Option<&Minimize> {
        self.last_result()
    }
}

/// Bounded firefly search accepted by model calibration.
///
/// Bounds and explicit populations use the projected, free-parameter order.
/// The supplied box must be wholly feasible for the model constraint. Every
/// candidate is checked before pricing; rejected candidates abort the run
/// instead of evaluating invalid parameters or inventing a penalty.
/// General coupled constraints are not supported by this box-based search.
#[derive(Debug, Clone)]
pub struct Firefly {
    adapter: CalibrationAdapter,
}

impl Firefly {
    /// Constructs a solver with explicit finite bounds and a deterministic seed.
    ///
    /// # Errors
    /// Rejects invalid bounds, population, coefficients or budgets. Evaluation
    /// budgets are capped at ten million to keep legacy integer counts safe.
    pub fn new(bounds: Bounds, options: FireflyOptions, common: Common) -> QlResult<Self> {
        Ok(Self {
            adapter: CalibrationAdapter::new(bounds, Method::Firefly(options), common)?,
        })
    }

    /// The exact optimizer outcome of the last completed solver invocation.
    ///
    /// Exhaustion is retained without claiming convergence. Invalid input and
    /// objective failures during invocation clear previous results; earlier
    /// model preflight failures retain them. Nonfinite termination retains
    /// diagnostics while returning a calibration error.
    pub fn last_result(&self) -> Option<&Minimize> {
        self.adapter.last_result()
    }
}

impl OptimizationMethod for Firefly {
    fn minimize(
        &mut self,
        problem: &mut Problem<'_>,
        end_criteria: &EndCriteria,
    ) -> QlResult<EndCriteriaType> {
        self.adapter.minimize(problem, end_criteria)
    }

    fn global_result(&self) -> Option<&Minimize> {
        self.last_result()
    }
}

#[cfg(test)]
mod firefly_tests;

#[cfg(test)]
mod hybrid_simulated_annealing_tests;

#[cfg(test)]
mod tests;

#[cfg(test)]
mod particle_swarm_tests;