pub struct Simulator<X, Y>{ /* private fields */ }Expand description
Represents a generic simulator for managing and simulating random walks.
§Type Parameters
-
X: A type that represents the state or value within the random walk. It must adhere to the following bounds:Copy: Allows for efficient copying of values.TryInto<Positive>: Ensures values can be converted into aPositivetype (potentially for validation or numerical operations).AddAssign: Allows addition and assignment (+=) operations.Display: Enables the formatting of values as strings for user-facing output.
-
Y: A type that represents the step or transition within the random walk. It must adhere to the following bounds:TryInto<Positive>: Ensures values can be converted into aPositivetype.Display: Enables the formatting of values as strings for user-facing output.Clone: Allows for creating deep copies of the values.
§Fields
title(String): The name or description of the simulator, primarily used for identification or display purposes.random_walks(Vec<RandomWalk<X, Y>>): A collection ofRandomWalkinstances, where each random walk adheres to the defined typesXandY.
§Usage
This struct is used as a high-level container to manage multiple random walks and perform simulations. Adding specific functionality such as initializing, running simulations, or generating statistical data depends on additional methods provided separately.
Note: This struct is generic and requires types provided for both state (X) and step/transition (Y) that meet the respective
trait bounds.
Implementations§
Source§impl<X, Y> Simulator<X, Y>
impl<X, Y> Simulator<X, Y>
Sourcepub fn new<F, E>(
title: String,
size: usize,
params: &WalkParams<X, Y>,
generator: F,
) -> Result<Self, E>
pub fn new<F, E>( title: String, size: usize, params: &WalkParams<X, Y>, generator: F, ) -> Result<Self, E>
Creates a new simulator that builds size random walks from the
supplied fallible generator.
The generator is invoked once per random walk; if any walk fails, no
partial Simulator is returned and the error is the one of the
lowest-indexed failing walk.
From PARALLEL_MIN_WALKS walks up, the walks are built on the rayon
pool and collected in index order (#860). The seed of every walk is
drawn up front, in order, from the master seed, so a seeded simulator
is bit-identical to the serial build whatever the thread count. Below
the threshold the walks are built serially, which is faster there.
The serial build stops at the first failing walk; the parallel build
works in rounds of 1024 walks and stops at the end of the round that
holds the first failing walk, whose error it returns.
§Parameters
title- A descriptive title; individual walks are titled"{title}_{i}".size- Number of random walks to generate.params- Walk parameters shared across all generated walks. Whenparams.seedisSome(seed), walkireceives thei-thu64drawn fromoptionstratlib_core::utils::deterministic_rng(seed)as its own seed: the walks differ from one another, and the whole simulator is reproducible bit for bit. WithNoneevery walk draws from the thread RNG.generator- A fallible step generator. Cloned per walk; pass a function pointer or a stateless closure for best ergonomics.
§Returns
Ok(Simulator) on success, or Err(E) from the lowest-indexed walk
whose generator invocation fails.
§Errors
Returns the error type produced by the supplied generator. For
chain-backed generators (e.g. crate::simulation::generator_positive)
this is crate::error::SimulationError.
Sourcepub fn get_title(&self) -> &str
pub fn get_title(&self) -> &str
Returns the title of the random walk.
§Returns
A string slice containing the title of the random walk.
Sourcepub fn get_random_walks(&self) -> Vec<&RandomWalk<X, Y>>
pub fn get_random_walks(&self) -> Vec<&RandomWalk<X, Y>>
Retrieves the steps of the random walks contained within the current object.
This method returns a vector of references to RandomWalk instances stored
in the random_walks collection member of the struct. Each RandomWalk
instance represents a step in the random walk process.
§Returns
A Vec containing references to RandomWalk<X, Y> values, where
X and Y are the types used within the random walk structure.
§Note
The returned vector contains borrowed references to the RandomWalk
elements within the struct, and the lifetime of these references
is tied to the lifetime of the parent object.
Sourcepub fn get_random_walk(&self, index: usize) -> Option<&RandomWalk<X, Y>>
pub fn get_random_walk(&self, index: usize) -> Option<&RandomWalk<X, Y>>
Retrieves a reference to the RandomWalk at the specified index.
§Arguments
index- The index of the desiredRandomWalkwithin therandom_walkscollection.
§Returns
Some(&RandomWalk<X, Y>)- The walk atindex.None- Ifindexis out of bounds.
Named get_*, so it follows slice::get rather than
std::ops::Index: an out-of-bounds index is reported, not aborted
on. Use the simulator[index] operator when the index is an invariant
of the caller and a panic is the wanted contract.
Sourcepub fn get_random_walk_mut(
&mut self,
index: usize,
) -> Option<&mut RandomWalk<X, Y>>
pub fn get_random_walk_mut( &mut self, index: usize, ) -> Option<&mut RandomWalk<X, Y>>
Retrieves a mutable reference to a RandomWalk at the specified index.
§Arguments
index- The zero-based index of theRandomWalkto access within therandom_walkscollection.
§Returns
Some(&mut RandomWalk<X, Y>)- The walk atindex.None- Ifindexis out of bounds.
Mutable counterpart of Simulator::get_random_walk, with the same
out-of-bounds contract.
Sourcepub fn first(&self) -> Option<&RandomWalk<X, Y>>
pub fn first(&self) -> Option<&RandomWalk<X, Y>>
Returns a reference to the first RandomWalk element in the random_walks collection, if it exists.
§Returns
Some(&RandomWalk<X, Y>)if therandom_walkscollection is not empty.Noneif therandom_walkscollection is empty.
Sourcepub fn last(&self) -> Option<&RandomWalk<X, Y>>
pub fn last(&self) -> Option<&RandomWalk<X, Y>>
Sourcepub fn get_steps(&self) -> Vec<Vec<&Step<X, Y>>>
pub fn get_steps(&self) -> Vec<Vec<&Step<X, Y>>>
Retrieves a nested vector of references to Step<X, Y> objects.
This function iterates over the elements of the current container (self)
assuming it implements IntoIterator, and for each element,
calls its get_steps method. The results are then collected into a
two-dimensional Vec structure.
§Returns
A Vec where each inner vector contains references to Step<X, Y> objects.
§Type Parameters
X: The type of the first generic parameter inStep.Y: The type of the second generic parameter inStep.
Sourcepub fn get_last_steps(&self) -> Vec<&Step<X, Y>>
pub fn get_last_steps(&self) -> Vec<&Step<X, Y>>
Returns a Vec containing the last Step of each item in the iterator.
This method assumes that each item in the iterator is an iterable itself.
It retrieves the last element of each iterable and collects them into a new Vec.
§Returns
A vector of references to the last Step<X, Y> of each non-empty
random walk. Empty walks are silently skipped, so the returned
vector may be shorter than self.len().
Sourcepub fn get_last_values(&self) -> Vec<&Step<X, Y>>
pub fn get_last_values(&self) -> Vec<&Step<X, Y>>
Retrieves the last value of each non-empty random walk.
§Returns
A Vec of references to the last Step<X, Y> of each non-empty
random walk. Empty walks are silently skipped, so the returned
vector may be shorter than self.len().
Sourcepub fn get_last_positive_values(&self) -> Vec<Positive>
pub fn get_last_positive_values(&self) -> Vec<Positive>
Retrieves the last set of positive values from the internal state.
This method extracts the positive values from the most recent set of steps retrieved
by the last_values method and returns them as a vector of Positive items.
§Returns
Vec<Positive>- A vector containing the last positive values derived from the steps.
§Notes
- The
last_valuesmethod is called internally to obtain the most recent set of steps. - The positive value for each step is retrieved via the
get_positive_valuemethod; a step whose value is not a validPositiveis left out of the result.
Sourcepub fn get_mc_option_price(
&self,
option: &Options,
) -> Result<Positive, PricingError>
pub fn get_mc_option_price( &self, option: &Options, ) -> Result<Positive, PricingError>
Calculates the price of a financial option using Monte Carlo simulation.
This method computes the price of the provided option based on a Monte Carlo
simulation approach. It retrieves the most recent positive values of the
underlying asset, which are then used in the simulation to estimate the option’s price.
§Arguments
option- A reference to anOptionsobject, representing the financial option to be priced.
§Returns
- If successful, it returns a
Positivevalue wrapped inOk, which represents the computed price of the option. - If an error occurs, it returns a
Box<dyn Error>wrapped inErr, indicating the failure during the pricing process.
§Errors
This function will return an error if:
- Retrieving the last positive values fails.
- The Monte Carlo pricing function (
price_option_monte_carlo) encounters an issue during execution.
§Note
The implementation assumes that the underlying asset’s most recent positive values
are available and meaningful for Monte Carlo simulation. Ensure that the input data
and the option are valid before invoking this method.
Trait Implementations§
Source§impl<X, Y> Index<usize> for Simulator<X, Y>
impl<X, Y> Index<usize> for Simulator<X, Y>
Source§type Output = RandomWalk<X, Y>
type Output = RandomWalk<X, Y>
Defines an alias Output for the type RandomWalk<X, Y>.
§Type Parameters
X: Represents the type of the first parameter used in theRandomWalk.Y: Represents the type of the second parameter used in theRandomWalk.
Output can be used as a shorthand to refer to a RandomWalk instance
with specific X and Y types, improving code readability and reducing
verbosity in the type definitions or method signatures.
Source§fn index(&self, index: usize) -> &Self::Output
fn index(&self, index: usize) -> &Self::Output
Retrieves a reference to the element at the specified index in the random_walks vector.
§Parameters
index: The zero-based index of the element to retrieve from therandom_walksvector.
§Returns
A reference to the element at the specified index in the random_walks vector.
§Panics
This function will panic if the given index is out of bounds, i.e., greater than or equal to
the length of the random_walks vector, as indexing a Vec does. Use
Simulator::get_random_walk for the checked form, which returns None instead.
Note: This implementation assumes that Self implements the Index trait and
that random_walks is a field in the implementing struct.
Source§impl<'a, X, Y> IntoIterator for &'a Simulator<X, Y>
impl<'a, X, Y> IntoIterator for &'a Simulator<X, Y>
Source§impl<X, Y> Len for Simulator<X, Y>
impl<X, Y> Len for Simulator<X, Y>
Source§impl MonteCarloPricer for Simulator<Positive, Positive>
impl MonteCarloPricer for Simulator<Positive, Positive>
Source§fn price_monte_carlo(&self, option: &Options) -> Result<Positive, PricingError>
fn price_monte_carlo(&self, option: &Options) -> Result<Positive, PricingError>
Delegates to Simulator::get_mc_option_price: the option is
priced from the terminal value of every walk the simulator holds.
Any failure is reported as PricingError::SimulationError, as
the MonteCarlo arm of price_option has always done.
Source§impl<X, Y> Profit for Simulator<X, Y>
impl<X, Y> Profit for Simulator<X, Y>
Source§fn calculate_profit_at(
&self,
_price: &Positive,
) -> Result<Decimal, PricingError>
fn calculate_profit_at( &self, _price: &Positive, ) -> Result<Decimal, PricingError>
Source§fn get_point_at_price(
&self,
_price: &Positive,
) -> Result<(Decimal, Decimal), PricingError>
fn get_point_at_price( &self, _price: &Positive, ) -> Result<(Decimal, Decimal), PricingError>
Auto Trait Implementations§
impl<X, Y> Freeze for Simulator<X, Y>
impl<X, Y> RefUnwindSafe for Simulator<X, Y>
impl<X, Y> Send for Simulator<X, Y>
impl<X, Y> Sync for Simulator<X, Y>
impl<X, Y> Unpin for Simulator<X, Y>
impl<X, Y> UnsafeUnpin for Simulator<X, Y>
impl<X, Y> UnwindSafe for Simulator<X, Y>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.