optionstratlib 0.17.1

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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 20/1/25
******************************************************************************/
use crate::curves::Point2D;
use crate::error::SurfaceError;
use crate::geometrics::HasX;
use num_traits::FromPrimitive;
use positive::is_positive;
use rust_decimal::Decimal;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::Display;
use utoipa::ToSchema;

/// Represents a point in three-dimensional space with `x`, `y` and `z` coordinates.
///
/// # Overview
/// The `Point3D` struct defines a point in a 3D Cartesian coordinate system.
/// All coordinates (`x`, `y`, and `z`) are stored as `Decimal` values to provide high precision,
/// making it suitable for applications requiring accurate numerical calculations.
///
/// # Fields
/// - **x**: The x-coordinate of the point, represented as a `Decimal`
/// - **y**: The y-coordinate of the point, represented as a `Decimal`
/// - **z**: The z-coordinate of the point, represented as a `Decimal`
///
/// # Examples
/// ```rust
/// use rust_decimal_macros::dec;
/// use optionstratlib::surfaces::Point3D;
///
/// // Create a new 3D point
/// let point = Point3D {
///     x: dec!(1.5),
///     y: dec!(2.0),
///     z: dec!(-3.25),
/// };
/// ```
///
/// # Usage
/// `Point3D` is primarily used within the surface module to represent vertices
/// of 3D surfaces and for various geometric calculations. The high-precision `Decimal`
/// type ensures accuracy in scientific and engineering applications.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct Point3D {
    /// The x-coordinate in the Cartesian system
    pub x: Decimal,
    /// The y-coordinate in the Cartesian system
    pub y: Decimal,
    /// The z-coordinate in the Cartesian system
    pub z: Decimal,
}

impl Display for Point3D {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(x: {}, y: {}, z: {})", self.x, self.y, self.z)
    }
}

impl PartialEq for Point3D {
    fn eq(&self, other: &Self) -> bool {
        self.x == other.x && self.y == other.y
    }
}

impl Eq for Point3D {}

impl PartialOrd for Point3D {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Point3D {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.x.cmp(&other.x) {
            Ordering::Equal => match self.y.cmp(&other.y) {
                Ordering::Equal => self.z.cmp(&other.z),
                y_ordering => y_ordering,
            },
            x_ordering => x_ordering,
        }
    }
}

impl Point3D {
    /// Creates a new instance of `Point3D` using the specified coordinates.
    ///
    /// # Parameters
    /// - `x`: The x-coordinate, which implements `Into<Decimal>`
    /// - `y`: The y-coordinate, which implements `Into<Decimal>`
    /// - `z`: The z-coordinate, which implements `Into<Decimal>`
    pub fn new<T: Into<Decimal>, U: Into<Decimal>, V: Into<Decimal>>(x: T, y: U, z: V) -> Self {
        Self {
            x: x.into(),
            y: y.into(),
            z: z.into(),
        }
    }

    /// Converts the Point3D to a tuple of three values.
    ///
    /// # Type Parameters
    /// - `T`: Type for x-coordinate
    /// - `U`: Type for y-coordinate
    /// - `V`: Type for z-coordinate
    ///
    /// # Errors
    ///
    /// Returns `SurfaceError::Point3DError` in three situations:
    ///
    /// - when one of the target types is `Positive`-like
    ///   (detected via the `is_positive::<T>()` / `is_positive::<U>()`
    ///   / `is_positive::<V>()` checks) and the corresponding
    ///   coordinate is less than or equal to zero.
    /// - when one of the `Decimal` coordinates cannot be converted
    ///   into the target numeric type (e.g. out-of-range for `f32`,
    ///   overflow for `u32`).
    pub fn to_tuple<
        T: TryFrom<Decimal> + 'static,
        U: TryFrom<Decimal> + 'static,
        V: TryFrom<Decimal> + 'static,
    >(
        &self,
    ) -> Result<(T, U, V), SurfaceError> {
        if is_positive::<T>() && self.x <= Decimal::ZERO {
            return Err(SurfaceError::Point3DError {
                reason: "x must be positive for type T",
            });
        }

        if is_positive::<U>() && self.y <= Decimal::ZERO {
            return Err(SurfaceError::Point3DError {
                reason: "y must be positive for type U",
            });
        }

        if is_positive::<V>() && self.z <= Decimal::ZERO {
            return Err(SurfaceError::Point3DError {
                reason: "z must be positive for type V",
            });
        }

        let x = T::try_from(self.x).map_err(|_| SurfaceError::Point3DError {
            reason: "failed to convert x",
        })?;
        let y = U::try_from(self.y).map_err(|_| SurfaceError::Point3DError {
            reason: "failed to convert y",
        })?;
        let z = V::try_from(self.z).map_err(|_| SurfaceError::Point3DError {
            reason: "failed to convert z",
        })?;

        Ok((x, y, z))
    }

    /// Creates a Point3D from a tuple of three values.
    ///
    /// # Errors
    ///
    /// Currently infallible for the blanket `Into<Decimal>`
    /// bounds; the `Result` signature is retained so future
    /// implementations that can reject non-finite or out-of-range
    /// inputs (e.g. via `TryFrom<f64>`) can surface
    /// [`SurfaceError::Point3DError`] without a breaking change.
    pub fn from_tuple<T: Into<Decimal>, U: Into<Decimal>, V: Into<Decimal>>(
        x: T,
        y: U,
        z: V,
    ) -> Result<Self, SurfaceError> {
        Ok(Self::new(x, y, z))
    }

    /// Converts the Point3D to a tuple of f64 values.
    ///
    /// # Errors
    ///
    /// Returns [`SurfaceError::Point3DError`] when any coordinate
    /// cannot be represented as an `f64` (typically a `Decimal`
    /// magnitude that exceeds the `f64` range).
    pub fn to_f64_tuple(&self) -> Result<(f64, f64, f64), SurfaceError> {
        let x = self.x.to_f64();
        let y = self.y.to_f64();
        let z = self.z.to_f64();

        match (x, y, z) {
            (Some(x), Some(y), Some(z)) => Ok((x, y, z)),
            _ => Err(SurfaceError::Point3DError {
                reason: "Error converting Decimal to f64",
            }),
        }
    }

    /// Creates a Point3D from a tuple of f64 values.
    ///
    /// # Errors
    ///
    /// Returns [`SurfaceError::Point3DError`] when any of `x`,
    /// `y` or `z` is `NaN` or infinite and therefore not
    /// representable as a `Decimal`.
    pub fn from_f64_tuple(x: f64, y: f64, z: f64) -> Result<Self, SurfaceError> {
        let x = Decimal::from_f64(x);
        let y = Decimal::from_f64(y);
        let z = Decimal::from_f64(z);

        match (x, y, z) {
            (Some(x), Some(y), Some(z)) => Ok(Self::new(x, y, z)),
            _ => Err(SurfaceError::Point3DError {
                reason: "Error converting f64 to Decimal",
            }),
        }
    }

    /// Converts this `Point3D` instance to a `Point2D` by projecting onto the XY plane.
    ///
    /// # Overview
    /// This method creates a new `Point2D` instance using only the `x` and `y` coordinates
    /// of the current `Point3D` object, effectively projecting the 3D point onto the XY plane.
    /// The `z` coordinate is discarded in this operation.
    ///
    /// # Returns
    /// A heap-allocated `Point2D` instance (`Box<Point2D>`) containing the `x` and `y` coordinates
    /// from this `Point3D` object.
    ///
    /// # Example
    /// ```
    /// use rust_decimal_macros::dec;
    /// use optionstratlib::surfaces::Point3D;
    ///
    /// let point3d = Point3D { x: dec!(1.5), y: dec!(2.0), z: dec!(3.5) };
    /// let point2d = point3d.point2d();
    /// assert_eq!(point2d.x, dec!(1.5));
    /// assert_eq!(point2d.y, dec!(2.0));
    /// ```
    ///
    /// # Use Cases
    /// This method is useful when:
    /// - Working with visualization that requires 2D projections of 3D points
    /// - Analyzing specific planes within a 3D model
    /// - Converting between coordinate systems from 3D to 2D
    #[must_use]
    pub fn point2d(&self) -> Box<Point2D> {
        Box::new(Point2D::new(self.x, self.y))
    }
}

impl From<&Point3D> for Point3D {
    fn from(point: &Point3D) -> Self {
        *point
    }
}

impl HasX for Point3D {
    fn get_x(&self) -> Decimal {
        self.x
    }
}

/// Represents the three possible axes in a 3D space.
///
/// This enumeration is commonly used to define or manipulate directions
/// or dimensions within a 3D coordinate system.
///
/// ## Variants
/// - `X`: The axis representing the horizontal direction.
/// - `Y`: The axis representing the vertical direction or elevation.
/// - `Z`: The axis representing depth or the third dimension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Axis {
    X,
    Y,
    Z,
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::surfaces::Surface;
    use positive::{Positive, pos_or_panic};
    use rust_decimal_macros::dec;
    use std::collections::BTreeSet;

    #[test]
    fn test_point3d_new() {
        let point = Point3D::new(dec!(1.0), dec!(2.0), dec!(3.0));
        assert_eq!(point.x, dec!(1.0));
        assert_eq!(point.y, dec!(2.0));
        assert_eq!(point.z, dec!(3.0));

        let display = format!("{point}");
        assert_eq!(display, "(x: 1.0, y: 2.0, z: 3.0)");

        let point2d = point.point2d();
        assert_eq!(point2d.x, dec!(1.0));
        assert_eq!(point2d.y, dec!(2.0));

        let has_x = point.get_x();
        assert_eq!(has_x, dec!(1.0));
    }

    #[test]
    fn test_point3d_negative() {
        let point = Point3D::new(dec!(-1.0), dec!(-2.0), dec!(-3.0));
        assert_eq!(point.x, dec!(-1.0));
        assert_eq!(point.y, dec!(-2.0));
        assert_eq!(point.z, dec!(-3.0));

        let display = format!("{point}");
        assert_eq!(display, "(x: -1.0, y: -2.0, z: -3.0)");

        let tuple = point.to_tuple::<Positive, Decimal, Decimal>();
        assert!(tuple.is_err());
        let tuple = point.to_tuple::<Decimal, Positive, Decimal>();
        assert!(tuple.is_err());
        let tuple = point.to_tuple::<Decimal, Decimal, Positive>();
        assert!(tuple.is_err());
    }

    #[test]
    fn test_point3d_to_tuple() {
        let result = Point3D::from_f64_tuple(1.0, 2.0, 3.0);
        assert!(result.is_ok());
        let point = result.unwrap();
        let result: Result<(Decimal, Decimal, Decimal), _> = point.to_tuple();
        assert!(result.is_ok());
        let (x, y, z) = result.unwrap();
        assert_eq!(x, dec!(1.0));
        assert_eq!(y, dec!(2.0));
        assert_eq!(z, dec!(3.0));
    }

    #[test]
    fn test_point3d_from_tuple() {
        let result = Point3D::from_tuple(dec!(1.0), Positive::TWO, pos_or_panic!(3.0));
        assert!(result.is_ok());
        let point = result.unwrap();
        assert_eq!(point.x, dec!(1.0));
        assert_eq!(point.y, dec!(2.0));
        assert_eq!(point.z, dec!(3.0));
    }

    #[test]
    fn test_point3d_to_f64_tuple() {
        let result = Point3D::from_f64_tuple(1.0, 2.0, 3.0);
        assert!(result.is_ok());
        let point = result.unwrap();
        let result = point.to_f64_tuple();
        assert!(result.is_ok());
        let (x, y, z) = result.unwrap();
        assert_eq!(x, 1.0);
        assert_eq!(y, 2.0);
        assert_eq!(z, 3.0);
    }

    #[test]
    fn test_point3d_from_f64_tuple() {
        let result = Point3D::from_f64_tuple(1.0, 2.0, 3.0);
        assert!(result.is_ok());
        let point = result.unwrap();
        assert_eq!(point.x, dec!(1.0));
        assert_eq!(point.y, dec!(2.0));
        assert_eq!(point.z, dec!(3.0));
    }

    #[test]
    fn test_point3d_ordering() {
        let p1 = Point3D::from_f64_tuple(1.0, 2.0, 3.0).unwrap();
        let p2 = Point3D::from_f64_tuple(1.0, 2.0, 4.0).unwrap();
        let p3 = Point3D::from_f64_tuple(1.0, 3.0, 1.0).unwrap();
        let p4 = Point3D::from_f64_tuple(2.0, 1.0, 1.0).unwrap();

        assert!(p1 < p2); // Same x,y, different z
        assert!(p1 < p3); // Same x, different y
        assert!(p1 < p4); // Different x
    }

    #[test]
    fn test_surface_new() {
        let points = BTreeSet::from_iter(vec![
            Point3D::from_f64_tuple(0.0, 0.0, 0.0).unwrap(),
            Point3D::from_f64_tuple(1.0, 1.0, 1.0).unwrap(),
        ]);
        let surface = Surface::new(points.clone());

        assert_eq!(surface.points, points);
    }

    #[test]
    fn test_error_handling_invalid_f64() {
        let result = Point3D::from_f64_tuple(f64::INFINITY, 2.0, 3.0);
        assert!(result.is_err());
        match result {
            Err(SurfaceError::Point3DError { reason }) => {
                assert_eq!(reason, "Error converting f64 to Decimal");
            }
            _ => panic!("Unexpected error type"),
        }
    }

    #[test]
    fn test_equal() {
        let p1 = Point3D::from_f64_tuple(1.0, 2.0, 3.0).unwrap();
        let p2 = Point3D::from_f64_tuple(1.0, 2.0, 3.0).unwrap();
        let p3 = Point3D::from_f64_tuple(1.0, 2.0, 4.0).unwrap();
        let p4 = Point3D::from_f64_tuple(1.0, 3.0, 3.0).unwrap();
        let p5 = Point3D::from_f64_tuple(2.0, 2.0, 3.0).unwrap();
        assert_eq!(p1, p2);
        assert_eq!(p1, p3);
        assert_ne!(p1, p4);
        assert_ne!(p1, p5);
    }
}

#[cfg(test)]
mod tests_point3d_serde {
    use super::*;
    use rust_decimal_macros::dec;
    use serde_json::Value;

    #[test]
    fn test_basic_serialization() {
        let point = Point3D {
            x: dec!(1.5),
            y: dec!(2.5),
            z: dec!(3.5),
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point.x, deserialized.x);
        assert_eq!(point.y, deserialized.y);
        assert_eq!(point.z, deserialized.z);
    }

    #[test]
    fn test_zero_values() {
        let point = Point3D {
            x: dec!(0.0),
            y: dec!(0.0),
            z: dec!(0.0),
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point, deserialized);
    }

    #[test]
    fn test_negative_values() {
        let point = Point3D {
            x: dec!(-1.5),
            y: dec!(-2.5),
            z: dec!(-3.5),
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point, deserialized);
    }

    #[test]
    fn test_high_precision_values() {
        let point = Point3D {
            x: dec!(1.12345678901234567890),
            y: dec!(2.12345678901234567890),
            z: dec!(3.12345678901234567890),
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point.x, deserialized.x);
        assert_eq!(point.y, deserialized.y);
        assert_eq!(point.z, deserialized.z);
    }

    #[test]
    fn test_json_structure() {
        let point = Point3D {
            x: dec!(1.5),
            y: dec!(2.5),
            z: dec!(3.5),
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let json_value: Value = serde_json::from_str(&serialized).unwrap();

        // Verify JSON structure
        assert!(json_value.is_object());
        assert_eq!(json_value.as_object().unwrap().len(), 3);
        assert!(json_value.get("x").is_some());
        assert!(json_value.get("y").is_some());
        assert!(json_value.get("z").is_some());
    }

    #[test]
    fn test_pretty_print() {
        let point = Point3D {
            x: dec!(1.5),
            y: dec!(2.5),
            z: dec!(3.5),
        };

        let serialized = serde_json::to_string_pretty(&point).unwrap();

        // Verify pretty print format
        assert!(serialized.contains('\n'));
        assert!(serialized.contains("  "));

        // Verify we can still deserialize pretty-printed JSON
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();
        assert_eq!(point, deserialized);
    }

    #[test]
    fn test_deserialize_from_integers() {
        let json_str = r#"{"x": 1, "y": 2, "z": 3}"#;
        let point: Point3D = serde_json::from_str(json_str).unwrap();

        assert_eq!(point.x, dec!(1.0));
        assert_eq!(point.y, dec!(2.0));
        assert_eq!(point.z, dec!(3.0));
    }

    #[test]
    fn test_deserialize_from_strings() {
        let json_str = r#"{"x": "1.5", "y": "2.5", "z": "3.5"}"#;
        let point: Point3D = serde_json::from_str(json_str).unwrap();

        assert_eq!(point.x, dec!(1.5));
        assert_eq!(point.y, dec!(2.5));
        assert_eq!(point.z, dec!(3.5));
    }

    #[test]
    fn test_invalid_json() {
        // Missing field
        let json_str = r#"{"x": 1.5, "y": 2.5}"#;
        let result = serde_json::from_str::<Point3D>(json_str);
        assert!(result.is_err());

        // Invalid number format
        let json_str = r#"{"x": "invalid", "y": 2.5, "z": 3.5}"#;
        let result = serde_json::from_str::<Point3D>(json_str);
        assert!(result.is_err());

        // Wrong data type
        let json_str = r#"{"x": true, "y": 2.5, "z": 3.5}"#;
        let result = serde_json::from_str::<Point3D>(json_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_max_values() {
        let point = Point3D {
            x: Decimal::MAX,
            y: Decimal::MAX,
            z: Decimal::MAX,
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point, deserialized);
    }

    #[test]
    fn test_min_values() {
        let point = Point3D {
            x: Decimal::MIN,
            y: Decimal::MIN,
            z: Decimal::MIN,
        };

        let serialized = serde_json::to_string(&point).unwrap();
        let deserialized: Point3D = serde_json::from_str(&serialized).unwrap();

        assert_eq!(point, deserialized);
    }

    #[test]
    fn test_json_to_vec() {
        let points = vec![
            Point3D {
                x: dec!(1.0),
                y: dec!(2.0),
                z: dec!(3.0),
            },
            Point3D {
                x: dec!(4.0),
                y: dec!(5.0),
                z: dec!(6.0),
            },
        ];

        let serialized = serde_json::to_string(&points).unwrap();
        let deserialized: Vec<Point3D> = serde_json::from_str(&serialized).unwrap();

        assert_eq!(points, deserialized);
    }

    #[test]
    fn test_array() {
        let json_str = "[1.5,  2.5, 3.5]";
        let result = serde_json::from_str::<Point3D>(json_str);
        assert!(result.is_ok());
    }
}