Skip to main content

Simulator

Struct Simulator 

Source
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 a Positive type (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 a Positive type.
    • 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 of RandomWalk instances, where each random walk adheres to the defined types X and Y.

§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>

Source

pub fn new<F, E>( title: String, size: usize, params: &WalkParams<X, Y>, generator: F, ) -> Result<Self, E>
where F: Fn(&WalkParams<X, Y>) -> Result<Vec<Step<X, Y>>, E> + Clone + Send + Sync, E: Send, X: Copy + TryInto<Positive> + AddAssign + Display + Send + Sync, Y: TryInto<Positive> + Display + Clone + Send + Sync,

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. When params.seed is Some(seed), walk i receives the i-th u64 drawn from optionstratlib_core::utils::deterministic_rng(seed) as its own seed: the walks differ from one another, and the whole simulator is reproducible bit for bit. With None every 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.

Source

pub fn get_title(&self) -> &str

Returns the title of the random walk.

§Returns

A string slice containing the title of the random walk.

Source

pub fn set_title(&mut self, title: String)

Updates the title of the random walk.

§Parameters
  • title - The new title to set
Source

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.

Source

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 desired RandomWalk within the random_walks collection.
§Returns
  • Some(&RandomWalk<X, Y>) - The walk at index.
  • None - If index is 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.

Source

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 the RandomWalk to access within the random_walks collection.
§Returns
  • Some(&mut RandomWalk<X, Y>) - The walk at index.
  • None - If index is out of bounds.

Mutable counterpart of Simulator::get_random_walk, with the same out-of-bounds contract.

Source

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 the random_walks collection is not empty.
  • None if the random_walks collection is empty.
Source

pub fn last(&self) -> Option<&RandomWalk<X, Y>>

Returns the last random walk in the collection, if it exists.

§Returns
  • Some(&RandomWalk<X, Y>): A reference to the last RandomWalk in the collection.
  • None: If the collection is empty.
§Note

The last method does not consume the collection; it returns a read-only reference to the last element.

Source

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 in Step.
  • Y: The type of the second generic parameter in Step.
Source

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().

Source

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().

Source

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_values method is called internally to obtain the most recent set of steps.
  • The positive value for each step is retrieved via the get_positive_value method; a step whose value is not a valid Positive is left out of the result.
Source

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 an Options object, representing the financial option to be priced.
§Returns
  • If successful, it returns a Positive value wrapped in Ok, which represents the computed price of the option.
  • If an error occurs, it returns a Box<dyn Error> wrapped in Err, 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> Clone for Simulator<X, Y>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<X, Y> Debug for Simulator<X, Y>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<X, Y> Display for Simulator<X, Y>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<X, Y> Index<usize> for Simulator<X, Y>

Source§

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 the RandomWalk.
  • Y: Represents the type of the second parameter used in the RandomWalk.

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

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 the random_walks vector.
§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<X, Y> IndexMut<usize> for Simulator<X, Y>

Source§

fn index_mut(&mut self, index: usize) -> &mut Self::Output

Retrieves a mutable reference to the walk at index.

§Panics

Panics if index is out of bounds, as indexing a Vec does. Use Simulator::get_random_walk_mut for the checked form, which returns None instead.

Source§

impl<'a, X, Y> IntoIterator for &'a Simulator<X, Y>

Source§

type Item = &'a RandomWalk<X, Y>

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, RandomWalk<X, Y>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<X, Y> Len for Simulator<X, Y>

Source§

fn len(&self) -> usize

Returns the number of elements in the random_walks collection.

§Returns
  • usize: The total count of elements in the random_walks collection.

This method is typically used when you need to determine the size of the internal random_walks data structure.

Source§

fn is_empty(&self) -> bool

Checks if the random_walks collection is empty.

§Returns
  • true - If the random_walks collection contains no elements.
  • false - If the random_walks collection contains one or more elements.
Source§

impl MonteCarloPricer for Simulator<Positive, Positive>

Source§

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>

Source§

fn calculate_profit_at( &self, _price: &Positive, ) -> Result<Decimal, PricingError>

Calculates the profit at a specified price. Read more
Source§

fn get_point_at_price( &self, _price: &Positive, ) -> Result<(Decimal, Decimal), PricingError>

Creates a chart point representation of the profit at the given price. Read more

Auto Trait Implementations§

§

impl<X, Y> Freeze for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: Freeze,

§

impl<X, Y> RefUnwindSafe for Simulator<X, Y>

§

impl<X, Y> Send for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: Send,

§

impl<X, Y> Sync for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: Sync,

§

impl<X, Y> Unpin for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: Unpin,

§

impl<X, Y> UnsafeUnpin for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: UnsafeUnpin,

§

impl<X, Y> UnwindSafe for Simulator<X, Y>
where Vec<RandomWalk<X, Y>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more