optionstratlib 0.16.0

OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341. The existing
// call sites are internal to this file and audited for invariant-bound
// indices (fixed-length buffers, just-pushed slices, etc.).
#![allow(clippy::indexing_slicing)]

use crate::Options;
use crate::error::PricingError;
use crate::pricing::Profit;
use crate::pricing::monte_carlo::price_option_monte_carlo;
use crate::simulation::WalkParams;
use crate::simulation::randomwalk::RandomWalk;
use crate::simulation::steps::Step;
use crate::strategies::base::BasicAble;
use crate::utils::Len;
use crate::visualization::{ColorScheme, Graph, GraphConfig, GraphData, Series2D, TraceMode};
use positive::Positive;
use rust_decimal::Decimal;
use std::fmt::Display;
use std::ops::{AddAssign, Index, IndexMut};

/// 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.
#[derive(Debug, Clone)]
pub struct Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    title: String,
    random_walks: Vec<RandomWalk<X, Y>>,
}

impl<X, Y> Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    /// Creates a new simulator that builds `size` random walks from the
    /// supplied fallible generator.
    ///
    /// The generator is invoked once per random walk; any error short
    /// circuits the constructor and no partial `Simulator` is returned.
    ///
    /// # 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.
    /// * `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 first generator
    /// invocation that fails.
    ///
    /// # Errors
    ///
    /// Returns the error type produced by the supplied generator. For
    /// chain-backed generators (e.g. [`crate::chains::generator_positive`])
    /// this is [`crate::error::ChainError`].
    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,
        X: Copy + TryInto<Positive> + AddAssign + Display,
        Y: TryInto<Positive> + Display + Clone,
    {
        let mut random_walks = Vec::with_capacity(size);
        for i in 0..size {
            let walk_title = format!("{title}_{i}");
            random_walks.push(RandomWalk::new(walk_title, params, generator.clone())?);
        }
        Ok(Self {
            title,
            random_walks,
        })
    }

    /// Returns the title of the random walk.
    ///
    /// # Returns
    ///
    /// A string slice containing the title of the random walk.
    #[must_use]
    pub fn get_title(&self) -> &str {
        &self.title
    }

    /// Updates the title of the random walk.
    ///
    /// # Parameters
    ///
    /// * `title` - The new title to set
    pub fn set_title(&mut self, title: String) {
        self.title = title;
    }

    /// 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.
    #[must_use]
    pub fn get_random_walks(&self) -> Vec<&RandomWalk<X, Y>> {
        self.random_walks.iter().collect::<Vec<&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
    ///
    /// A reference to the `RandomWalk<X, Y>` located at the given `index`.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds for the `random_walks` collection.
    ///
    #[must_use]
    pub fn get_random_walk(&self, index: usize) -> &RandomWalk<X, Y> {
        &self.random_walks[index]
    }

    /// 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
    ///
    /// A mutable reference to the `RandomWalk` object at the given index.
    ///
    /// # Panics
    ///
    /// This function panics if the provided `index` is out of bounds, i.e., if `index >= self.random_walks.len()`.
    ///
    pub fn get_random_walk_mut(&mut self, index: usize) -> &mut RandomWalk<X, Y> {
        &mut self.random_walks[index]
    }

    /// 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.
    ///
    #[must_use]
    pub fn first(&self) -> Option<&RandomWalk<X, Y>> {
        self.random_walks.first()
    }

    /// 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.
    #[must_use]
    pub fn last(&self) -> Option<&RandomWalk<X, Y>> {
        self.random_walks.last()
    }

    /// 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`.
    ///
    #[must_use]
    pub fn get_steps(&self) -> Vec<Vec<&Step<X, Y>>> {
        self.into_iter().map(|step| step.get_steps()).collect()
    }

    /// 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()`.
    #[must_use]
    pub fn get_last_steps(&self) -> Vec<&Step<X, Y>> {
        self.into_iter().filter_map(|step| step.last()).collect()
    }

    /// 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()`.
    #[must_use]
    pub fn get_last_values(&self) -> Vec<&Step<X, Y>> {
        self.into_iter().filter_map(|step| step.last()).collect()
    }

    /// 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.
    ///
    /// # Panics
    /// This function assumes that all steps in `last_values` have valid positive values accessible via
    /// `get_positive_value`. Ensure `last_values` returns valid data to avoid runtime errors.
    #[must_use]
    pub fn get_last_positive_values(&self) -> Vec<Positive> {
        let last_values = self.get_last_values();
        last_values
            .iter()
            .filter_map(|step| step.get_positive_value().ok())
            .collect::<Vec<Positive>>()
    }

    /// 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.
    pub fn get_mc_option_price(&self, option: &Options) -> Result<Positive, PricingError> {
        let last_values = self.get_last_positive_values();
        price_option_monte_carlo(option, &last_values)
    }
}

impl<X, Y> Len for Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    /// 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.
    fn len(&self) -> usize {
        self.random_walks.len()
    }

    /// 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.
    ///
    fn is_empty(&self) -> bool {
        self.random_walks.is_empty()
    }
}

impl<X, Y> Index<usize> for Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    /// 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.
    type Output = RandomWalk<X, Y>;

    /// 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.
    ///
    /// Note: This implementation assumes that `Self` implements the `Index` trait and
    /// that `random_walks` is a field in the implementing struct.
    fn index(&self, index: usize) -> &Self::Output {
        &self.random_walks[index]
    }
}

impl<X, Y> IndexMut<usize> for Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.random_walks[index]
    }
}

impl<X, Y> Display for Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}", self.title)?;
        for random_walk in &self.random_walks {
            writeln!(f, "\t{random_walk}")?;
        }
        Ok(())
    }
}

impl<X, Y> Profit for Simulator<X, Y>
where
    X: AddAssign + Copy + Display + TryInto<Positive>,
    Y: Clone + Display + TryInto<Positive>,
{
    fn calculate_profit_at(&self, _price: &Positive) -> Result<Decimal, PricingError> {
        Err(PricingError::other(
            "Profit calculation not implemented for Simulator",
        ))
    }
}

impl<X, Y> BasicAble for Simulator<X, Y>
where
    X: AddAssign + Copy + Display + TryInto<Positive>,
    Y: Clone + Display + TryInto<Positive>,
{
    fn get_title(&self) -> String {
        self.title.clone()
    }
}

impl<X, Y> Graph for Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    fn graph_data(&self) -> GraphData {
        let mut series: Vec<Series2D> = Vec::new();
        let random_walks = self.get_steps();
        for (i, steps) in random_walks.iter().enumerate() {
            let y: Vec<Decimal> = steps
                .iter()
                .map(|step| step.get_graph_y_value().unwrap_or(Positive::ZERO).to_dec())
                .collect();
            let x: Vec<Decimal> = steps
                .iter()
                .map(|step| -step.get_graph_x_in_days_left().to_dec())
                .collect();
            let title = format!("Sim_{i}");
            series.push(Series2D {
                x,
                y,
                name: title,
                mode: TraceMode::Lines,
                line_color: None,
                line_width: Some(2.0),
            });
        }
        GraphData::MultiSeries(series)
    }

    fn graph_config(&self) -> GraphConfig {
        GraphConfig {
            title: self.get_title().to_string(),
            x_label: Some("Date".to_string()),
            y_label: Some("Price".to_string()),
            z_label: None,
            width: 1600,
            height: 900,
            show_legend: true,
            color_scheme: ColorScheme::HighContrast,
            line_style: Default::default(),
            legend: None,
        }
    }
}

impl<'a, X, Y> IntoIterator for &'a Simulator<X, Y>
where
    X: Copy + TryInto<Positive> + AddAssign + Display,
    Y: TryInto<Positive> + Display + Clone,
{
    type Item = &'a RandomWalk<X, Y>;
    type IntoIter = std::slice::Iter<'a, RandomWalk<X, Y>>;

    fn into_iter(self) -> Self::IntoIter {
        self.random_walks.iter()
    }
}

#[cfg(test)]
#[allow(irrefutable_let_patterns)]
mod tests {
    use super::*;
    use crate::ExpirationDate;
    use crate::chains::generator_positive;
    use crate::error::SimulationError;
    use crate::simulation::{
        WalkParams, WalkType, WalkTypeAble,
        steps::{Step, Xstep, Ystep},
    };
    use crate::utils::{TimeFrame, time::convert_time_frame};
    use positive::pos_or_panic;
    use rust_decimal_macros::dec;
    use std::convert::Infallible;
    use tracing::{debug, info};
    #[cfg(feature = "plotly")]
    use {std::fs, std::path::Path};

    // Helper structs and functions for testing
    #[derive(Clone)]
    struct TestWalker;

    impl TestWalker {
        fn new() -> Self {
            TestWalker {}
        }
    }
    impl WalkTypeAble<Positive, Positive> for TestWalker {}

    fn test_generator(
        params: &WalkParams<Positive, Positive>,
    ) -> Result<Vec<Step<Positive, Positive>>, Infallible> {
        Ok(vec![params.init_step.clone()])
    }

    // Test Simulator creation
    #[test]
    fn test_simulator_creation() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 5,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(simulator) = Simulator::new(
            "Test Simulator".to_string(),
            5,
            &walk_params,
            test_generator,
        ) else {
            unreachable!()
        };

        assert_eq!(simulator.get_title(), "Test Simulator");
        assert_eq!(simulator.len(), 5);
        assert!(!simulator.is_empty());
    }

    // Test title methods
    #[test]
    fn test_simulator_title_methods() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 3,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(mut simulator) = Simulator::new(
            "Original Title".to_string(),
            3,
            &walk_params,
            test_generator,
        ) else {
            unreachable!()
        };

        assert_eq!(simulator.get_title(), "Original Title");

        simulator.set_title("New Title".to_string());
        assert_eq!(simulator.get_title(), "New Title");
    }

    // Test step access methods
    #[test]
    fn test_simulator_step_access() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 3,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(simulator) = Simulator::new(
            "Test Simulator".to_string(),
            3,
            &walk_params,
            test_generator,
        ) else {
            unreachable!()
        };

        // Test get_steps
        let steps = simulator.get_random_walks();
        assert_eq!(steps.len(), 3);

        // Test get_step
        let step = simulator.get_random_walk(1);
        assert_eq!(step.get_title(), "Test Simulator_1");

        // Test first and last
        assert!(simulator.first().is_some());
        assert!(simulator.last().is_some());
        assert_eq!(
            simulator.first().expect("should be Ok").get_title(),
            "Test Simulator_0"
        );
        assert_eq!(
            simulator.last().expect("should be Ok").get_title(),
            "Test Simulator_2"
        );
    }

    // Test Index and IndexMut traits
    #[test]
    fn test_simulator_indexing() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 3,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(mut simulator) = Simulator::new(
            "Test Simulator".to_string(),
            3,
            &walk_params,
            test_generator,
        ) else {
            unreachable!()
        };

        // Test immutable indexing
        assert_eq!(simulator[0].get_title(), "Test Simulator_0");
        assert_eq!(simulator[1].get_title(), "Test Simulator_1");
        assert_eq!(simulator[2].get_title(), "Test Simulator_2");

        // Test mutable indexing
        simulator[1].set_title("Modified Title".to_string());
        assert_eq!(simulator[1].get_title(), "Modified Title");
    }

    // Test display formatting
    #[test]
    fn test_simulator_display() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 2,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(simulator) =
            Simulator::new("Display Test".to_string(), 2, &walk_params, test_generator)
        else {
            unreachable!()
        };

        let display_output = format!("{simulator}");
        assert!(display_output.starts_with("Display Test"));
        assert!(display_output.contains("Display Test_0"));
        assert!(display_output.contains("Display Test_1"));
    }

    // Test simulator with empty collection
    #[test]
    fn test_simulator_empty() {
        let simulator: Simulator<Positive, Positive> = Simulator {
            title: "Empty Simulator".to_string(),
            random_walks: Vec::new(),
        };

        assert_eq!(simulator.get_title(), "Empty Simulator");
        assert_eq!(simulator.len(), 0);
        assert!(simulator.is_empty());
        assert!(simulator.first().is_none());
        assert!(simulator.last().is_none());
    }

    #[test]
    fn test_simulator_new_propagates_generator_error_short_circuits() {
        // Regression for #349: ensure the simulator constructor returns
        // the first generator error and does not silently build a
        // partial simulator.
        use std::cell::Cell;
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 1,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let calls: Cell<u32> = Cell::new(0);
        let result: Result<Simulator<Positive, Positive>, &'static str> =
            Simulator::new("Err Sim".to_string(), 5, &walk_params, |p| {
                let n = calls.get();
                calls.set(n + 1);
                if n == 1 {
                    Err("boom")
                } else {
                    Ok(vec![p.init_step.clone()])
                }
            });

        match result {
            Err(msg) => assert_eq!(msg, "boom"),
            Ok(_) => panic!("expected generator error to propagate"),
        }
        // Generator should have been called twice (success then failure)
        // and not five times — short-circuited.
        assert_eq!(calls.get(), 2);
    }

    // Test panic scenarios (these would typically be in separate test functions)
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_simulator_index_out_of_bounds() {
        let walker = Box::new(TestWalker);
        let initial_price = Positive::HUNDRED;
        let init_step = Step {
            x: Xstep::new(
                Positive::ONE,
                TimeFrame::Minute,
                ExpirationDate::Days(pos_or_panic!(30.0)),
            ),
            y: Ystep::new(0, initial_price),
        };

        let walk_params = WalkParams {
            size: 3,
            init_step,
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(
                    Positive::ONE / pos_or_panic!(30.0),
                    &TimeFrame::Minute,
                    &TimeFrame::Day,
                ),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            walker,
        };

        let Ok(simulator) =
            Simulator::new("Panic Test".to_string(), 3, &walk_params, test_generator)
        else {
            unreachable!()
        };

        // This should panic
        let _ = simulator[3];
    }

    #[test]
    fn test_full_simulation() -> Result<(), SimulationError> {
        let simulator_size: usize = 5;
        let n_steps = 10;
        let initial_price = Positive::HUNDRED;
        let std_dev = pos_or_panic!(20.0);
        let walker = Box::new(TestWalker::new());
        let days = Positive::TWO;

        let walk_params = WalkParams {
            size: n_steps,
            init_step: Step {
                x: Xstep::new(Positive::ONE, TimeFrame::Hour, ExpirationDate::Days(days)),
                y: Ystep::new(0, initial_price),
            },
            walk_type: WalkType::GeometricBrownian {
                dt: convert_time_frame(Positive::ONE / days, &TimeFrame::Hour, &TimeFrame::Day),
                drift: dec!(0.0),
                volatility: std_dev,
            },
            walker,
        };

        assert_eq!(walk_params.size, n_steps);
        assert_eq!(walk_params.init_step.get_value(), &Positive::HUNDRED);
        assert_eq!(walk_params.y(), &Positive::HUNDRED);

        let simulator = Simulator::new(
            "Simulator".to_string(),
            simulator_size,
            &walk_params,
            generator_positive,
        )?;
        debug!("Simulator: {}", simulator);
        assert_eq!(simulator.get_title(), "Simulator");
        assert_eq!(simulator.len(), simulator_size);

        let random_walk = simulator[0].clone();
        assert_eq!(random_walk.get_title(), "Simulator_0");
        assert_eq!(random_walk.len(), n_steps);

        let step = random_walk[0].clone();
        assert_eq!(*step.get_index(), Positive::ONE);
        let step_string = format!("{step}");
        assert_eq!(step.to_string(), step_string);

        let y_step = step.get_y_step();
        assert_eq!(*y_step.index(), 0);
        assert_eq!(*y_step.value(), Positive::HUNDRED);

        let x_step = step.get_x_step();
        assert_eq!(*x_step.index(), 0);
        assert_eq!(*x_step.step_size_in_time(), Positive::ONE);
        assert_eq!(x_step.time_unit(), &TimeFrame::Hour);
        assert_eq!(x_step.days_left()?, Positive::TWO);

        let next_step = step.next(pos_or_panic!(200.0)).expect("should be Ok");
        assert_eq!(next_step.get_value(), &pos_or_panic!(200.0));
        let next_step_string = format!("{next_step}");
        assert_eq!(next_step.to_string(), next_step_string);

        let previous_step = step.previous(pos_or_panic!(50.0))?;
        assert_eq!(previous_step.get_value(), &pos_or_panic!(50.0));
        let previous_step_string = format!("{previous_step}");
        assert_eq!(previous_step.to_string(), previous_step_string);

        let x_step = step.get_x_step();
        let next_x_step = x_step.next().expect("should be Ok");
        assert_eq!(*next_x_step.index(), 1);
        assert_eq!(*next_x_step.step_size_in_time(), Positive::ONE);
        let next_x_step_string = format!("{next_x_step}");
        assert_eq!(next_x_step.to_string(), next_x_step_string);

        let y_step = step.get_y_step();
        assert_eq!(*y_step.index(), 0);
        assert_eq!(*y_step.value(), Positive::HUNDRED);
        assert_eq!(y_step.positive().unwrap(), Positive::HUNDRED);

        let last_steps: Vec<&Step<Positive, Positive>> = simulator
            .into_iter()
            .map(|step| step.last().expect("should be Ok"))
            .collect();
        info!("Last Steps: {:?}", last_steps);
        assert_eq!(last_steps.len(), simulator_size);

        let last_values: Vec<&Positive> = simulator
            .into_iter()
            .map(|step| step.last().expect("should be Ok").get_value())
            .collect();
        info!("Last Values: {:?}", last_values);
        assert_eq!(last_values.len(), simulator_size);

        #[cfg(feature = "plotly")]
        {
            let file_name = "Draws/Simulation/test_simulator.html".as_ref();
            simulator.write_html(file_name)?;
            if Path::new(file_name).exists() {
                fs::remove_file(file_name)
                    .unwrap_or_else(|_| panic!("Failed to remove {}", file_name.to_str().unwrap()));
            }
        }
        Ok(())
    }
}