optionstratlib 0.17.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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 24/3/25
******************************************************************************/
use crate::ExpirationDate;
use crate::error::SimulationError;
use crate::utils::TimeFrame;
use crate::utils::time::convert_time_frame;
use positive::Positive;
use serde::{Serialize, Serializer};
use std::convert::TryInto;
use std::fmt::{Display, Formatter};
use std::ops::AddAssign;
use tracing::debug;

/// Represents a step in a time series with an indexed value at a specific time point.
///
/// This struct encapsulates a value at a specific point in a time series, tracking not only
/// the value itself but also its position (index), the time unit it belongs to, and its
/// associated datetime. It's designed to be used in financial and statistical analysis
/// where tracking values across time is essential.
///
/// The generic parameter `T` allows for different value types while ensuring they can be
/// incrementally accumulated (via `AddAssign`) and converted to a `Positive` type for
/// calculations that require non-negative values.
///
/// # Type Parameters
///
/// * `T` - The type of the value being stored, which must implement `AddAssign`, be convertible
///   to `Positive`, and be `Copy`.
///
/// # Fields
///
/// * `index` - An integer representing the position of this step in a sequence.
///
/// * `value` - The actual data value at this time step, of generic type `T`.
///
/// * `time_unit` - Defines the time granularity (e.g., day, hour, minute) for this step.
///
/// * `datetime` - The specific expiration date associated with this time step,
///   which can be either a relative number of days or an absolute datetime.
///
#[derive(Debug, Clone, Copy)]
pub struct Xstep<T>
where
    T: Copy + TryInto<Positive> + AddAssign + Display,
{
    index: i32,
    step_size_in_time: T,
    time_unit: TimeFrame,
    datetime: ExpirationDate,
}

/// Implementation for the `Xstep<T>` struct, which represents a time step in a simulation.
///
/// The `Xstep<T>` struct is designed to handle sequential time steps in financial simulations,
/// allowing for forward and backward movement in time. The struct maintains an index counter,
/// a value of type T, a time unit, and an expiration date.
///
/// # Type Parameters
///
/// * `T` - A type that implements `AddAssign`, can be converted into `Positive`, and is `Copy`.
///   This typically represents a numeric value used for calculating time differences.
///
/// # Examples
///
/// ```rust
///
/// // Create a step with 7 days as the value, using days as the time unit
/// use positive::{pos_or_panic, Positive};
/// use optionstratlib::ExpirationDate;
/// use optionstratlib::simulation::steps::Xstep;
/// use optionstratlib::utils::TimeFrame;
/// let step = Xstep::new(pos_or_panic!(7.0), TimeFrame::Day, ExpirationDate::Days(pos_or_panic!(30.0)));
///
/// // Move to the next step (forward in time)
/// let next_step = step.next();
///
/// // Move to the previous step (backward in time)
/// let prev_step = step.previous();
/// ```
impl<T> Xstep<T>
where
    T: Copy + TryInto<Positive> + AddAssign + Display,
{
    /// Creates a new `Xstep` with the specified value, time unit, and datetime.
    ///
    /// # Parameters
    ///
    /// * `value` - The step size value
    /// * `time_unit` - The time unit for this step (e.g., Day, Week, Month)
    /// * `datetime` - The expiration date. Stored as-is when the variant is
    ///   [`ExpirationDate::Days`]; [`ExpirationDate::DateTime`] is normalized
    ///   to `Days` via [`ExpirationDate::get_days`]. If that conversion fails
    ///   (past date / invalid datetime), the step falls back to
    ///   `ExpirationDate::Days(Positive::ZERO)` and emits `tracing::error!`.
    ///
    /// # Returns
    ///
    /// A new `Xstep<T>` instance initialized with the provided parameters and index set to 0.
    pub fn new(value: T, time_unit: TimeFrame, datetime: ExpirationDate) -> Self {
        let datetime = match datetime {
            ExpirationDate::Days(_) => datetime,
            ExpirationDate::DateTime(dt) => match datetime.get_days() {
                Ok(days) => ExpirationDate::Days(days),
                Err(e) => {
                    tracing::error!(
                        datetime = %dt,
                        error = %e,
                        "Xstep::new: could not convert ExpirationDate::DateTime to Days; defaulting to Days(0)"
                    );
                    ExpirationDate::Days(Positive::ZERO)
                }
            },
        };
        Self {
            index: 0,
            step_size_in_time: value,
            time_unit,
            datetime,
        }
    }

    /// Returns a reference to the index of the time step.
    ///
    /// The index represents the position of this step in a sequence of time steps.
    ///
    /// # Returns
    ///
    /// * `&i32` - A reference to the index value.
    pub fn index(&self) -> &i32 {
        &self.index
    }

    /// Returns a reference to the step size in time units.
    ///
    /// This represents the magnitude of this time step in the context of its time frame,
    /// such as the number of days, hours, or other time units.
    ///
    /// # Returns
    ///
    /// * `&T` - A reference to the step size value.
    pub fn step_size_in_time(&self) -> &T {
        &self.step_size_in_time
    }

    /// Returns a reference to the time unit associated with this step.
    ///
    /// The time unit defines the granularity of the time measurement (e.g., day, hour, minute).
    ///
    /// # Returns
    ///
    /// * `&TimeFrame` - A reference to the time unit enumeration.
    pub fn time_unit(&self) -> &TimeFrame {
        &self.time_unit
    }

    /// Returns a reference to the datetime associated with this step.
    ///
    /// This represents the specific point in time (as an expiration date) that
    /// this step corresponds to, which can be either a relative value or an absolute datetime.
    ///
    /// # Returns
    ///
    /// * `&ExpirationDate` - A reference to the expiration date.
    pub fn datetime(&self) -> &ExpirationDate {
        &self.datetime
    }

    /// Calculates the number of days left until the expiry date associated with this step.
    ///
    /// This method delegates to the underlying `ExpirationDate` component to determine
    /// the days remaining until expiration. It provides a consistent way to access time-to-expiry
    /// regardless of how the date was originally specified (as days or as an absolute datetime).
    ///
    /// # Returns
    ///
    /// * `Result<Positive, SimulationError>` - A positive decimal value representing the number of days
    ///   until expiration, or an error if the calculation cannot be performed.
    ///
    /// # Errors
    ///
    /// Returns [`SimulationError::ExpirationDate`] when the stored
    /// [`ExpirationDate`] cannot be resolved to a non-negative day
    /// count (e.g. the datetime is in the past).
    pub fn days_left(&self) -> Result<Positive, SimulationError> {
        Ok(self.datetime.get_days()?)
    }

    /// Generates the next step by reducing the expiration days by the step value.
    ///
    /// This method calculates a new `Xstep` instance with its index incremented by 1,
    /// and the expiration date reduced by the equivalent of `value` in days.
    ///
    /// # Returns
    ///
    /// A new `Xstep<T>` instance with updated index and datetime values.
    ///
    /// # Errors
    ///
    /// Returns [`SimulationError::ExpirationReached`] when the
    /// current step is already at expiration (no forward step is
    /// possible), or [`SimulationError::ExpirationDate`] when the
    /// underlying [`ExpirationDate::get_days`] call fails.
    pub fn next(&self) -> Result<Self, SimulationError> {
        let days = self.datetime.get_days()?;
        if days == Positive::ZERO {
            return Err(SimulationError::ExpirationReached);
        }
        let days_to_rest = convert_time_frame(
            self.step_size_in_time.try_into().map_err(|_| {
                SimulationError::step_error("Failed to convert step size to Positive")
            })?,
            &self.time_unit,
            &TimeFrame::Day,
        );
        let datetime = if days_to_rest <= days {
            ExpirationDate::Days(days - days_to_rest)
        } else {
            ExpirationDate::Days(Positive::ZERO)
        };
        debug!(
            "days_to_rest: {}, days: {}, datetime: {}",
            days_to_rest, days, datetime
        );
        Ok(Self {
            index: self.index + 1,
            step_size_in_time: self.step_size_in_time,
            time_unit: self.time_unit,
            datetime,
        })
    }

    /// Generates the previous step by increasing the expiration days by the step value.
    ///
    /// This method calculates a new `Xstep` instance with its index decremented by 1,
    /// and the expiration date increased by the equivalent of `value` in days.
    ///
    /// # Returns
    ///
    /// A new `Xstep<T>` instance with updated index and datetime values.
    ///
    /// # Errors
    ///
    /// Returns `SimulationError::ExpirationDate` when the underlying
    /// `ExpirationDate::get_days` call fails, or
    /// `SimulationError::step_error` when the step-size conversion
    /// to `Positive` fails.
    ///
    /// # Panics
    ///
    /// The decrement `self.index - 1` is unchecked and will panic in
    /// debug builds (or silently wrap in release) if `self.index` is
    /// already `i32::MIN`. In practice simulations start at `0` and
    /// only call `previous` a bounded number of times, so this is
    /// treated as a caller invariant rather than a runtime check.
    pub fn previous(&self) -> Result<Self, SimulationError> {
        let days = self.datetime.get_days()?;
        let days_to_rest = convert_time_frame(
            self.step_size_in_time.try_into().map_err(|_| {
                SimulationError::step_error("Failed to convert step size to Positive")
            })?,
            &self.time_unit,
            &TimeFrame::Day,
        );
        let datetime = ExpirationDate::Days(days + days_to_rest);
        Ok(Self {
            index: self.index - 1,
            step_size_in_time: self.step_size_in_time,
            time_unit: self.time_unit,
            datetime,
        })
    }
}

impl<T> Display for Xstep<T>
where
    T: Copy + TryInto<Positive> + AddAssign + Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Xstep {{ index: {}, value: {}, time_unit: {:?}, datetime: {} }}",
            self.index, self.step_size_in_time, self.time_unit, self.datetime
        )
    }
}

impl<T> Serialize for Xstep<T>
where
    T: Copy + TryInto<Positive> + AddAssign + Display + Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Use a struct with 4 fields to represent Xstep
        use serde::ser::SerializeStruct;
        let step_size_in_time: Positive =
            self.step_size_in_time.try_into().unwrap_or(Positive::ZERO);
        let mut state = serializer.serialize_struct("Xstep", 4)?;
        state.serialize_field("index", &self.index)?;
        state.serialize_field("step_size_in_time", &step_size_in_time)?;
        state.serialize_field("time_unit", &self.time_unit)?;
        state.serialize_field("datetime", &self.datetime)?;
        state.end()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::ExpirationDate;
    use positive::pos_or_panic;

    #[test]
    fn test_days_left() {
        let mut step = Xstep::new(
            1.5f64,
            TimeFrame::Day,
            ExpirationDate::Days(pos_or_panic!(30.0)),
        );
        step.index = 42;

        assert!(step.next().is_ok());

        assert_eq!(step.days_left().unwrap(), pos_or_panic!(30.0));
        let step1 = step.next().unwrap();
        assert_eq!(*step1.index(), 43);
        assert_eq!(step1.days_left().unwrap(), pos_or_panic!(28.5));
        let step2 = step1.next().unwrap();
        assert_eq!(*step2.index(), 44);
        assert_eq!(step2.days_left().unwrap(), pos_or_panic!(27.0));
        let step3 = step2.next().unwrap();
        assert_eq!(*step3.index(), 45);
        assert_eq!(step3.days_left().unwrap(), pos_or_panic!(25.5));
        let step4 = step3.previous().unwrap();
        assert_eq!(*step4.index(), 44);
        assert_eq!(step4.days_left().unwrap(), pos_or_panic!(27.0));
    }
}

#[cfg(test)]
mod tests_serialize {
    use super::*;
    use crate::model::ExpirationDate;
    use positive::pos_or_panic;

    use rust_decimal_macros::dec;
    use serde_json::{Value, json};

    #[test]
    fn test_serialized_structure() {
        // Create an Xstep with f64
        let mut step = Xstep::new(
            1.5f64,
            TimeFrame::Day,
            ExpirationDate::Days(pos_or_panic!(30.0)),
        );
        step.index = 42;

        // Serialize to JSON
        let serialized = serde_json::to_string(&step).unwrap();
        let parsed: Value = serde_json::from_str(&serialized).unwrap();

        // Check all fields exist and have correct types
        assert!(parsed.is_object());
        assert!(parsed.get("index").unwrap().is_i64());
        assert!(parsed.get("step_size_in_time").unwrap().is_number());
        assert!(
            parsed.get("time_unit").unwrap().is_object()
                || parsed.get("time_unit").unwrap().is_string()
        );
        assert!(parsed.get("datetime").unwrap().is_object());

        // Check field values
        assert_eq!(parsed["index"], json!(42));
        assert_eq!(parsed["step_size_in_time"], json!(1.5));
    }

    #[test]
    fn test_serialization_value_conversion() {
        // Create instances with different types but same value
        let step_f64 = Xstep::new(2.5f64, TimeFrame::Day, ExpirationDate::Days(Positive::ONE));
        let step_decimal = Xstep::new(
            dec!(2.5),
            TimeFrame::Day,
            ExpirationDate::Days(Positive::ONE),
        );
        let step_positive = Xstep::new(
            pos_or_panic!(2.5),
            TimeFrame::Day,
            ExpirationDate::Days(Positive::ONE),
        );

        // Serialize all three
        let json_f64 = serde_json::to_string(&step_f64).unwrap();
        let json_decimal = serde_json::to_string(&step_decimal).unwrap();
        let json_positive = serde_json::to_string(&step_positive).unwrap();

        // Parse to access and check the step_size_in_time values
        let parsed_f64: Value = serde_json::from_str(&json_f64).unwrap();
        let parsed_decimal: Value = serde_json::from_str(&json_decimal).unwrap();
        let parsed_positive: Value = serde_json::from_str(&json_positive).unwrap();

        // All should serialize to the same value
        assert_eq!(parsed_f64["step_size_in_time"], json!(2.5));
        assert_eq!(parsed_decimal["step_size_in_time"], json!(2.5));
        assert_eq!(parsed_positive["step_size_in_time"], json!(2.5));
    }

    #[test]
    fn test_serialization_format_identity() {
        // Create instances with different types
        let step_f64 = Xstep::new(3.1f64, TimeFrame::Hour, ExpirationDate::Days(Positive::ONE));
        let step_decimal = Xstep::new(
            dec!(3.1),
            TimeFrame::Hour,
            ExpirationDate::Days(Positive::ONE),
        );
        let step_positive = Xstep::new(
            pos_or_panic!(3.1),
            TimeFrame::Hour,
            ExpirationDate::Days(Positive::ONE),
        );

        // Serialize all three
        let json_f64 = serde_json::to_string(&step_f64).unwrap();
        let json_decimal = serde_json::to_string(&step_decimal).unwrap();
        let json_positive = serde_json::to_string(&step_positive).unwrap();

        // They should all serialize to identical JSON
        assert_eq!(json_f64, json_decimal);
        assert_eq!(json_decimal, json_positive);
    }

    #[test]
    fn test_serialization_edge_cases() {
        // Test with zero
        let step_zero = Xstep::new(
            0.01f64,
            TimeFrame::Minute,
            ExpirationDate::Days(Positive::ZERO),
        );
        let json_zero = serde_json::to_string(&step_zero).unwrap();
        let parsed_zero: Value = serde_json::from_str(&json_zero).unwrap();
        assert_eq!(parsed_zero["step_size_in_time"], json!(0.01));

        // Test with very small number
        let step_small = Xstep::new(
            0.00001f64,
            TimeFrame::Minute,
            ExpirationDate::Days(Positive::ONE),
        );
        let json_small = serde_json::to_string(&step_small).unwrap();
        let parsed_small: Value = serde_json::from_str(&json_small).unwrap();
        assert!(parsed_small["step_size_in_time"].as_f64().unwrap() > 0.0);
        assert!(parsed_small["step_size_in_time"].as_f64().unwrap() < 0.0001);

        // Test with very large number
        let step_large = Xstep::new(
            1_000_000.01f64,
            TimeFrame::Minute,
            ExpirationDate::Days(Positive::ONE),
        );
        let json_large = serde_json::to_string(&step_large).unwrap();
        let parsed_large: Value = serde_json::from_str(&json_large).unwrap();
        assert_eq!(parsed_large["step_size_in_time"], json!(1_000_000.01));
    }

    #[test]
    fn test_serialization_precision() {
        // Create a step with a value that has many decimal places
        let step = Xstep::new(
            1.23456789f64,
            TimeFrame::Day,
            ExpirationDate::Days(Positive::ONE),
        );

        // Serialize and parse
        let serialized = serde_json::to_string(&step).unwrap();
        let parsed: Value = serde_json::from_str(&serialized).unwrap();

        // Check precision is maintained (to reasonable float precision)
        let value = parsed["step_size_in_time"].as_f64().unwrap();
        assert!((value - 1.23456789).abs() < 0.0000001);
    }

    #[test]
    fn test_datetime_serialization() {
        // Test with Days expiration
        let step_days = Xstep::new(
            1.0f64,
            TimeFrame::Day,
            ExpirationDate::Days(pos_or_panic!(30.0)),
        );

        let serialized_days = serde_json::to_string(&step_days).unwrap();
        let parsed_days: Value = serde_json::from_str(&serialized_days).unwrap();

        assert!(parsed_days["datetime"].is_object());
        assert!(parsed_days["datetime"].get("days").is_some());

        // Note: We don't test DateTime because the new constructor explicitly
        // panics for DateTime variant, which matches the implementation
    }

    #[test]
    fn test_datetime_constructor_normalizes_to_days() {
        // `Xstep::new` now normalizes `ExpirationDate::DateTime` to
        // `Days(N)` rather than panicking (issue #323).
        let date_time = chrono::Utc::now() + chrono::Duration::days(10);
        let step = Xstep::new(1.0f64, TimeFrame::Day, ExpirationDate::DateTime(date_time));
        match step.datetime() {
            ExpirationDate::Days(_) => {}
            other => panic!("expected ExpirationDate::Days, got {other:?}"),
        }
    }
}