Skip to main content

optionstratlib_simulation/simulation/
mod.rs

1//! # Random Walk Simulation Library
2//!
3//! This library provides tools for simulating and analyzing random walk processes
4//! and other stochastic models. It includes implementations of various random walk algorithms
5//! and statistical utilities; charts of a walk are drawn by the `optionstratlib` facade.
6//!
7//! The library is organized into several modules:
8//! - `model`: Contains the data structures and types that represent stochastic processes
9//! - `simulator`: Provides simulation engines and algorithms for running the models
10//! - `utils`: Utility functions and helpers for statistical analysis and data manipulation
11//! - `walk`: Public API for creating and running random walk simulations
12//!
13//! ## Core Components
14//!
15//! ## Mathematical Background
16//!
17//! The random walk implementation follows the geometric Brownian motion model with:
18//!
19//! 1. Price changes: dS = μSdt + σSdW
20//!    - S: Asset price
21//!    - μ: Drift (mean return)
22//!    - σ: Volatility
23//!    - dW: Wiener process increment
24//!
25//! 2. Volatility updates: σ(t) ~ N(σ, σ_change)
26//!    - Stochastic volatility component
27//!    - Updates based on volatility_window
28//!
29//! ## Features
30//!
31//! - Geometric Brownian motion simulation
32//! - Stochastic volatility modeling
33//! - Real-time volatility estimation
34//! - Integration with option pricing parameters
35//! - Iterator interface for sequential processing
36//!
37//! ## Performance Considerations
38//!
39//! - Time Complexity: O(n) for generation, where n is the number of steps
40//! - Space Complexity: O(n) for storing the price path
41//! - Volatility calculation: O(w) where w is the volatility window size
42//!
43//! ## Implementation Notes
44//!
45//! - All prices are strictly positive (enforced by Positive)
46//! - Volatility is estimated using rolling windows
47//! - The iterator provides option pricing parameters for each step
48//! - Thread-safe random number generation
49//! - Supports various time frames (daily, weekly, monthly)
50
51/// Contains data structures and types that represent stochastic processes.
52///
53/// This module defines the mathematical models and their parameters used in
54/// random walk simulations, including different types of distributions and
55/// process configurations.
56mod model;
57
58/// Provides simulation engines and algorithms for running stochastic models.
59///
60/// This module contains the core simulation logic that powers the random walk
61/// implementations, including time-stepping algorithms and state management.
62pub mod simulator;
63
64/// # Random Walk Module
65///
66/// This module provides implementations of various random walk algorithms and related utilities.
67/// Random walks are mathematical objects that describe a path consisting of a succession of random steps
68/// in some mathematical space.
69///
70/// ## Usage
71///
72/// Typically used for stochastic process simulation and analysis, Monte Carlo methods,
73/// and modeling natural phenomena with random components.
74///
75pub mod randomwalk;
76
77/// Module containing functionality for stepping through data or calculations.
78///
79/// This module provides components and utilities for managing step-based operations,
80/// such as iterative calculations, data processing steps, or any process that requires
81/// incremental progression through a series of operations.
82///
83/// The stepping functionality is particularly useful for scenarios where:
84/// - Operations need to be performed in a specific sequence
85/// - Progress tracking is required through a multi-stage process
86/// - Incremental state changes need to be managed
87///
88pub mod steps;
89
90/// Module containing trait definitions for the financial modeling library.
91///
92/// This module defines the core traits that establish behavior contracts for
93/// various components of the financial modeling system. These traits provide
94/// interfaces for implementing different financial models, pricing methods,
95/// and data processing techniques.
96///
97///
98/// # Usage
99///
100/// Traits defined in this module are typically implemented by concrete types
101/// throughout the library to ensure consistent behavior and interoperability
102/// between different components of the system.
103mod traits;
104
105/// Module containing parameter definitions and structures for financial models.
106///
107/// This module defines the various parameter types, configurations, and constants
108/// used across different financial models in the library. It provides structured
109/// representation of inputs required for financial calculations and simulations.
110///
111/// # Usage
112///
113/// Parameter structures from this module are used as inputs to the various
114/// financial models, pricing functions, and simulation methods throughout the library.
115/// They encapsulate all the necessary inputs while ensuring proper validation.
116mod params;
117
118/// Module containing exit policy definitions for option trading strategies.
119///
120/// This module defines various exit conditions and policies that can be used
121/// to determine when to close an option position during simulations or live trading.
122/// Exit policies include percentage-based targets, fixed prices, time-based exits,
123/// and composite conditions using AND/OR logic.
124///
125/// # Usage
126///
127/// Exit policies are used in simulations to automatically close positions when
128/// specific conditions are met, enabling systematic strategy testing and risk management.
129pub mod exit;
130
131/// Generic path evaluation contracts: [`PathEvaluator`], [`PathOutcome`],
132/// [`PathStatistics`] and the [`evaluate_paths`] driver. They let a
133/// simulation be evaluated and summarised without naming a strategy; the
134/// backtesting layer adapts its strategy-bound result types to them.
135mod outcome;
136
137/// Generic walk driver shared by every step generator.
138///
139/// Contains [`walk_steps`], the single implementation of the
140/// dispatch/advance/build loop that the chain, series and positive
141/// generators share, plus [`generator_positive`] (relocated here from
142/// `chains::` — it never depended on option chains).
143mod walk_driver;
144
145/// Deterministic walkers shared by the generator test suites.
146#[cfg(test)]
147pub(crate) mod walk_test_support;
148
149pub use exit::{ExitPolicy, check_exit_policy};
150pub use model::{WalkPath, WalkType};
151pub use outcome::{PathEvaluator, PathOutcome, PathStatistics, evaluate_paths};
152pub use params::WalkParams;
153pub use traits::{
154    WalkTypeAble, WalkTypeAbleClone, custom_walk, garch_walk, heston_walk, telegraph_walk,
155};
156pub mod ou;
157pub use ou::generate_ou_process;
158pub use walk_driver::{expanding_window_vols, generator_positive, walk_steps, walk_steps_par};
159
160use crate::error::SimulationError;
161
162/// An empty buffer able to hold `len + extra` path points without growing.
163///
164/// A walk's length is caller input. `Vec::with_capacity` panics with
165/// `capacity overflow` when the points do not fit in `isize::MAX` bytes, and
166/// aborts the process when the allocator refuses the request, so a walk of
167/// `usize::MAX` steps used to take its caller down. `try_reserve_exact`
168/// reserves the same capacity and reports both cases (#788).
169///
170/// # Errors
171///
172/// Returns [`SimulationError::InvalidParameters`] when `len + extra`
173/// overflows `usize` or the buffer cannot be allocated.
174pub(crate) fn path_buffer<T>(len: usize, extra: usize) -> Result<Vec<T>, SimulationError> {
175    let capacity = len.checked_add(extra).ok_or_else(|| {
176        SimulationError::invalid_parameters(&format!(
177            "walk size {len} leaves no room for {extra} more point(s)"
178        ))
179    })?;
180    let mut buffer = Vec::new();
181    buffer.try_reserve_exact(capacity).map_err(|e| {
182        SimulationError::invalid_parameters(&format!(
183            "cannot allocate a path of {capacity} points: {e}"
184        ))
185    })?;
186    Ok(buffer)
187}
188
189#[cfg(test)]
190mod tests_path_buffer {
191    use super::*;
192
193    #[test]
194    fn test_path_buffer_reserves_the_requested_points() -> Result<(), SimulationError> {
195        let buffer: Vec<u64> = path_buffer(4, 1)?;
196        assert!(buffer.is_empty());
197        assert!(buffer.capacity() >= 5);
198        Ok(())
199    }
200
201    #[test]
202    fn test_path_buffer_overflowing_or_unallocatable_size_returns_error() {
203        for (len, extra) in [(usize::MAX, 1), (usize::MAX / 2, 0)] {
204            let result: Result<Vec<u64>, SimulationError> = path_buffer(len, extra);
205            assert!(
206                matches!(result, Err(SimulationError::InvalidParameters { .. })),
207                "{len} + {extra}"
208            );
209        }
210    }
211}