optionstratlib 0.15.3

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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
use crate::error::TransactionError;
use crate::model::TradeStatus;
use crate::pnl::utils::PnL;
use crate::{OptionStyle, OptionType, Side};
use chrono::{DateTime, Utc};
use positive::Positive;
use serde::{Deserialize, Serialize};

/// # Transaction
///
/// Represents an options trading transaction with all relevant trade details.
///
/// This structure encapsulates all the information related to an options contract transaction,
/// including the type, style, pricing information, quantity, fees, and market conditions at the time
/// of execution.
///
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Transaction {
    /// * `status` - The current status of the transaction (e.g., open, closed, expired)
    status: TradeStatus,
    /// * `date_time` - The date and time when the transaction occurred
    date_time: Option<DateTime<Utc>>,
    /// * `option_type` - The type of options contract (e.g., European, American)
    option_type: OptionType,
    /// * `side` - The directional exposure of the position (Long or Short)
    side: Side,
    /// * `option_style` - The exercise style of the option (e.g., Put, Call)
    option_style: OptionStyle,
    /// * `quantity` - The number of contracts involved in the transaction
    quantity: Positive,
    /// * `premium` - The premium paid or received in this transaction
    premium: Positive,
    /// * `fees` - Commissions and fees paid for this transaction
    fees: Positive,
    /// * `underlying_price` - The price of the underlying asset at the time of the transaction
    underlying_price: Option<Positive>,
    /// * `days_to_expiration` - The number of days remaining until the option expires
    days_to_expiration: Option<Positive>,
    /// * `implied_volatility` - The implied volatility at the time of the transaction
    implied_volatility: Option<Positive>,
}

impl Transaction {
    /// Creates a new Transaction with all parameters.
    ///
    /// # Parameters
    ///
    /// * `date_time` - The date and time when the transaction occurred
    /// * `option_type` - The type of options contract (e.g., European, American)
    /// * `side` - The directional exposure of the position (Long or Short)
    /// * `option_style` - The exercise style of the option (e.g., Put, Call)
    /// * `price` - The execution price of the transaction
    /// * `quantity` - The number of contracts involved in the transaction
    /// * `premium` - The premium paid or received in this transaction
    /// * `fees` - Commissions and fees paid for this transaction
    /// * `underlying_price` - The price of the underlying asset at the time of the transaction
    /// * `days_to_expiration` - The number of days remaining until the option expires
    /// * `implied_volatility` - The implied volatility at the time of the transaction
    ///
    /// # Returns
    ///
    /// A new `Transaction` instance
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        status: TradeStatus,
        date_time: Option<DateTime<Utc>>,
        option_type: OptionType,
        side: Side,
        option_style: OptionStyle,
        quantity: Positive,
        premium: Positive,
        fees: Positive,
        underlying_price: Option<Positive>,
        days_to_expiration: Option<Positive>,
        implied_volatility: Option<Positive>,
    ) -> Self {
        Transaction {
            status,
            date_time,
            option_type,
            side,
            option_style,
            quantity,
            premium,
            fees,
            underlying_price,
            days_to_expiration,
            implied_volatility,
        }
    }
}

impl Transaction {
    // Getters

    /// Gets the date and time of the transaction.
    pub fn date_time(&self) -> Option<DateTime<Utc>> {
        self.date_time
    }

    /// Gets the option type.
    pub fn option_type(&self) -> OptionType {
        self.option_type.clone()
    }

    /// Gets the side (Long or Short).
    pub fn side(&self) -> Side {
        self.side
    }

    /// Gets the option style (Call or Put).
    pub fn option_style(&self) -> OptionStyle {
        self.option_style
    }

    /// Gets the quantity of contracts.
    pub fn quantity(&self) -> Positive {
        self.quantity
    }

    /// Gets the premium.
    pub fn premium(&self) -> Positive {
        self.premium
    }

    /// Gets the fees.
    pub fn fees(&self) -> Positive {
        self.fees
    }

    /// Gets the underlying price, if available.
    pub fn underlying_price(&self) -> Option<Positive> {
        self.underlying_price
    }

    /// Gets the days to expiration, if available.
    pub fn days_to_expiration(&self) -> Option<Positive> {
        self.days_to_expiration
    }

    /// Gets the implied volatility, if available.
    pub fn implied_volatility(&self) -> Option<Positive> {
        self.implied_volatility
    }
}

impl Transaction {
    /// Updates the implied volatility for this transaction.
    ///
    /// # Parameters
    ///
    /// * `iv` - The new implied volatility value
    pub fn update_implied_volatility(&mut self, iv: Positive) {
        self.implied_volatility = Some(iv);
    }

    /// Updates the underlying price for this transaction.
    ///
    /// # Parameters
    ///
    /// * `price` - The new underlying price value
    pub fn update_underlying_price(&mut self, price: Positive) {
        self.underlying_price = Some(price);
    }

    /// Updates the days to expiration for this transaction.
    ///
    /// # Parameters
    ///
    /// * `days` - The new days to expiration value
    pub fn update_days_to_expiration(&mut self, days: Positive) {
        self.days_to_expiration = Some(days);
    }
}

impl Transaction {
    /// Calculates the profit and loss for this transaction based on its current status.
    ///
    /// # Parameters
    ///
    /// * `current_price` - The current price of the underlying asset
    ///
    /// # Returns
    ///
    /// A Result containing the PnL or an error
    pub fn pnl(&self) -> Result<PnL, TransactionError> {
        match self.status {
            TradeStatus::Open => self.calculate_open_pnl(),
            TradeStatus::Closed
            | TradeStatus::Expired
            | TradeStatus::Exercised
            | TradeStatus::Assigned
            | TradeStatus::Other(_) => self.calculate_closed_pnl(),
        }
    }

    /// Calculates PnL for an open position.
    ///
    /// # Parameters
    ///
    /// * `current_price` - The current price of the underlying asset
    ///
    /// # Returns
    ///
    /// A Result containing the PnL with unrealized values or an error
    fn calculate_open_pnl(&self) -> Result<PnL, TransactionError> {
        if self.option_type != OptionType::European {
            return Err(TransactionError {
                message: "Unsupported option type in Transaction".to_string(),
            });
        }

        let realized = match self.side {
            Side::Long => -(self.premium + self.fees).to_dec() * self.quantity,
            Side::Short => (self.premium - self.fees).to_dec() * self.quantity,
        };

        Ok(PnL::new(
            Some(realized),
            None,
            self.premium,
            self.fees,
            Utc::now(),
        ))
    }

    /// Calculates PnL for a closed position.
    ///
    /// # Parameters
    ///
    /// * `current_price` - The current price of the underlying asset
    ///
    /// # Returns
    ///
    /// A Result containing the PnL with realized values or an error
    fn calculate_closed_pnl(&self) -> Result<PnL, TransactionError> {
        if self.option_type != OptionType::European {
            return Err(TransactionError {
                message: "Unsupported option type in Transaction".to_string(),
            });
        }

        let realized = match self.side {
            Side::Short => -(self.premium + self.fees).to_dec() * self.quantity,
            Side::Long => (self.premium - self.fees).to_dec() * self.quantity,
        };

        Ok(PnL::new(
            Some(realized),
            None,
            self.premium,
            self.fees,
            Utc::now(),
        ))
    }
}

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

    use chrono::Utc;
    use positive::{Positive, pos_or_panic, spos};
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;

    #[test]
    fn test_long_call_position_profitable_close() {
        // 1. Create an open long call position
        let open_date = Utc::now();
        let mut long_call = Transaction::new(
            TradeStatus::Open,    // Initial status is Open
            Some(open_date),      // Transaction date
            OptionType::European, // European option
            Side::Long,           // Long position
            OptionStyle::Call,    // Call option
            Positive::ONE,        // 1 contract
            pos_or_panic!(5.0),   // Premium paid: $5.00
            Positive::ONE,        // Fees: $1.00
            spos!(100.0),         // Underlying price at open: $100.00
            spos!(30.0),          // 30 days to expiration
            spos!(0.2),           // IV: 20%
        );

        // 2. Calculate initial PnL (should be negative as we paid premium + fees)
        let initial_pnl = long_call.pnl().unwrap();
        assert!(initial_pnl.realized.unwrap() < Decimal::ZERO);
        assert_eq!(initial_pnl.realized.unwrap(), dec!(-6.0)); // Premium + fees = -$6.00

        // 3. Now let's simulate price movement and close the position
        // Price has increased from $100 to $110
        long_call.update_underlying_price(pos_or_panic!(110.0));

        // Close the position
        let closed_date = Utc::now();
        let closed_call = Transaction::new(
            TradeStatus::Closed,  // Status is now Closed
            Some(closed_date),    // Closing date
            OptionType::European, // European option
            Side::Long,           // Long position
            OptionStyle::Call,    // Call option
            Positive::ONE,        // 1 contract
            pos_or_panic!(12.0),  // Closing premium: $12.00 (higher due to price increase)
            Positive::ONE,        // Closing fees: $1.00
            spos!(110.0),         // Underlying price at close: $110.00
            spos!(20.0),          // 20 days to expiration (10 days elapsed)
            spos!(0.22),          // IV: 22%
        );

        // 4. Calculate closing PnL (should be positive as closing premium > initial premium + fees)
        let closing_pnl = closed_call.pnl().unwrap();
        assert!(closing_pnl.realized.unwrap() > Decimal::ZERO);
        assert_eq!(closing_pnl.realized.unwrap(), dec!(11.0)); // Selling premium - fees = $12.00 - $1.00 = $11.00

        // 5. Verify total profit by comparing the two PnLs
        let total_profit = closing_pnl.realized.unwrap() + initial_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(5.0)); // Net profit of $5.00 ($11.00 - $6.00)
    }

    #[test]
    fn test_long_call_position_unprofitable_close() {
        // Create an open long call position
        let open_date = Utc::now();
        let mut long_call = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::ONE,
            pos_or_panic!(5.0), // Premium paid: $5.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        // Calculate initial PnL
        let initial_pnl = long_call.pnl().unwrap();
        assert_eq!(initial_pnl.realized.unwrap(), dec!(-6.0));

        // Price has decreased from $100 to $95
        long_call.update_underlying_price(pos_or_panic!(95.0));

        // Close the position for less than we paid
        let closed_date = Utc::now();
        let closed_call = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::ONE,
            Positive::TWO, // Closing premium: $2.00 (lower due to price decrease)
            Positive::ONE, // Closing fees: $1.00
            spos!(95.0),
            spos!(20.0),
            spos!(0.18),
        );

        // Calculate closing PnL
        let closing_pnl = closed_call.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(1.0)); // Selling premium - fees = $2.00 - $1.00 = $1.00

        // Verify total loss
        let total_profit = closing_pnl.realized.unwrap() + initial_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(-5.0)); // Net loss of $5.00 ($1.00 - $6.00)
    }

    #[test]
    fn test_short_call_position_profitable_close() {
        // 1. Create an open short call position
        let open_date = Utc::now();
        let mut short_call = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Short,        // Short position
            OptionStyle::Call,  // Call option
            Positive::ONE,      // 1 contract
            pos_or_panic!(5.0), // Premium received: $5.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),       // Underlying price at open: $100.00
            spos!(30.0),        // 30 days to expiration
            spos!(0.2),         // IV: 20%
        );

        // 2. Calculate initial PnL (should be positive as we receive premium - fees)
        let initial_pnl = short_call.pnl().unwrap();
        assert!(initial_pnl.realized.unwrap() > Decimal::ZERO);
        assert_eq!(initial_pnl.realized.unwrap(), dec!(4.0)); // Premium - fees = $5.00 - $1.00 = $4.00

        // 3. Simulate price decrease from $100 to $95 (favorable for short call)
        short_call.update_underlying_price(pos_or_panic!(95.0));

        // 4. Close the position by buying it back for less than we received
        let closed_date = Utc::now();
        let closed_call = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::ONE,
            Positive::TWO, // Closing premium: $2.00 (lower due to price decrease)
            Positive::ONE, // Closing fees: $1.00
            spos!(95.0),
            spos!(20.0),
            spos!(0.18),
        );

        // 5. Calculate closing PnL (should be negative as we're paying to close)
        let closing_pnl = closed_call.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(-3.0)); // Premium paid + fees = $2.00 + $1.00 = $3.00

        // 6. Verify total profit
        let total_profit = initial_pnl.realized.unwrap() + closing_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(1.0)); // Net profit of $1.00 ($4.00 - $3.00)
    }

    #[test]
    fn test_short_call_position_unprofitable_close() {
        // 1. Create an open short call position
        let open_date = Utc::now();
        let mut short_call = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::ONE,
            pos_or_panic!(5.0), // Premium received: $5.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        // 2. Calculate initial PnL
        let initial_pnl = short_call.pnl().unwrap();
        assert_eq!(initial_pnl.realized.unwrap(), dec!(4.0)); // Premium - fees = $4.00

        // 3. Simulate price increase from $100 to $110 (unfavorable for short call)
        short_call.update_underlying_price(pos_or_panic!(110.0));

        // 4. Close the position by buying it back for more than we received
        let closed_date = Utc::now();
        let closed_call = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::ONE,
            pos_or_panic!(12.0), // Closing premium: $12.00 (higher due to price increase)
            Positive::ONE,       // Closing fees: $1.00
            spos!(110.0),
            spos!(20.0),
            spos!(0.22),
        );

        // 5. Calculate closing PnL
        let closing_pnl = closed_call.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(-13.0)); // Premium paid + fees = $12.00 + $1.00 = $13.00

        // 6. Verify total loss
        let total_profit = initial_pnl.realized.unwrap() + closing_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(-9.0)); // Net loss of $7.00 ($4.00 - $13.00)
    }

    #[test]
    fn test_long_put_position_profitable_close() {
        // 1. Create an open long put position
        let open_date = Utc::now();
        let mut long_put = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Long,         // Long position
            OptionStyle::Put,   // Put option
            Positive::ONE,      // 1 contract
            pos_or_panic!(4.0), // Premium paid: $4.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),       // Underlying price at open: $100.00
            spos!(30.0),        // 30 days to expiration
            spos!(0.2),         // IV: 20%
        );

        // 2. Calculate initial PnL (should be negative as we paid premium + fees)
        let initial_pnl = long_put.pnl().unwrap();
        assert!(initial_pnl.realized.unwrap() < Decimal::ZERO);
        assert_eq!(initial_pnl.realized.unwrap(), dec!(-5.0)); // Premium + fees = -$5.00

        // 3. Simulate price decrease from $100 to $90 (favorable for long put)
        long_put.update_underlying_price(pos_or_panic!(90.0));

        // 4. Close the position by selling it for more than we paid
        let closed_date = Utc::now();
        let closed_put = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Long,
            OptionStyle::Put,
            Positive::ONE,
            pos_or_panic!(10.0), // Closing premium: $10.00 (higher due to price decrease)
            Positive::ONE,       // Closing fees: $1.00
            spos!(90.0),
            spos!(20.0),
            spos!(0.25),
        );

        // 5. Calculate closing PnL
        let closing_pnl = closed_put.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(9.0)); // Selling premium - fees = $10.00 - $1.00 = $9.00

        // 6. Verify total profit
        let total_profit = closing_pnl.realized.unwrap() + initial_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(4.0)); // Net profit of $4.00 ($9.00 - $5.00)
    }

    #[test]
    fn test_long_put_position_unprofitable_close() {
        // 1. Create an open long put position
        let open_date = Utc::now();
        let mut long_put = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Long,
            OptionStyle::Put,
            Positive::ONE,
            pos_or_panic!(4.0), // Premium paid: $4.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        // 2. Calculate initial PnL
        let initial_pnl = long_put.pnl().unwrap();
        assert_eq!(initial_pnl.realized.unwrap(), dec!(-5.0)); // Premium + fees = -$5.00

        // 3. Simulate price increase from $100 to $105 (unfavorable for long put)
        long_put.update_underlying_price(pos_or_panic!(105.0));

        // 4. Close the position by selling it for less than we paid
        let closed_date = Utc::now();
        let closed_put = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Long,
            OptionStyle::Put,
            Positive::ONE,
            Positive::TWO, // Closing premium: $2.00 (lower due to price increase)
            Positive::ONE, // Closing fees: $1.00
            spos!(105.0),
            spos!(20.0),
            spos!(0.18),
        );

        // 5. Calculate closing PnL
        let closing_pnl = closed_put.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(1.0)); // Selling premium - fees = $2.00 - $1.00 = $1.00

        // 6. Verify total loss
        let total_profit = closing_pnl.realized.unwrap() + initial_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(-4.0)); // Net loss of $4.00 ($1.00 - $5.00)
    }

    #[test]
    fn test_short_put_position_profitable_close() {
        // 1. Create an open short put position
        let open_date = Utc::now();
        let mut short_put = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Short,        // Short position
            OptionStyle::Put,   // Put option
            Positive::ONE,      // 1 contract
            pos_or_panic!(4.0), // Premium received: $4.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),       // Underlying price at open: $100.00
            spos!(30.0),        // 30 days to expiration
            spos!(0.2),         // IV: 20%
        );

        // 2. Calculate initial PnL (should be positive as we receive premium - fees)
        let initial_pnl = short_put.pnl().unwrap();
        assert!(initial_pnl.realized.unwrap() > Decimal::ZERO);
        assert_eq!(initial_pnl.realized.unwrap(), dec!(3.0)); // Premium - fees = $4.00 - $1.00 = $3.00

        // 3. Simulate price increase from $100 to $105 (favorable for short put)
        short_put.update_underlying_price(pos_or_panic!(105.0));

        // 4. Close the position by buying it back for less than we received
        let closed_date = Utc::now();
        let closed_put = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Put,
            Positive::ONE,
            pos_or_panic!(1.5), // Closing premium: $1.50 (lower due to price increase)
            Positive::ONE,      // Closing fees: $1.00
            spos!(105.0),
            spos!(20.0),
            spos!(0.15),
        );

        // 5. Calculate closing PnL
        let closing_pnl = closed_put.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(-2.5)); // Premium paid + fees = $1.50 + $1.00 = $2.50

        // 6. Verify total profit
        let total_profit = initial_pnl.realized.unwrap() + closing_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(0.5)); // Net profit of $2.50 ($3.00 - $2.50)
    }

    #[test]
    fn test_short_put_position_unprofitable_close() {
        // 1. Create an open short put position
        let open_date = Utc::now();
        let mut short_put = Transaction::new(
            TradeStatus::Open,
            Some(open_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Put,
            Positive::ONE,
            pos_or_panic!(4.0), // Premium received: $4.00
            Positive::ONE,      // Fees: $1.00
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        // 2. Calculate initial PnL
        let initial_pnl = short_put.pnl().unwrap();
        assert_eq!(initial_pnl.realized.unwrap(), dec!(3.0)); // Premium - fees = $3.00

        // 3. Simulate price decrease from $100 to $90 (unfavorable for short put)
        short_put.update_underlying_price(pos_or_panic!(90.0));

        // 4. Close the position by buying it back for more than we received
        let closed_date = Utc::now();
        let closed_put = Transaction::new(
            TradeStatus::Closed,
            Some(closed_date),
            OptionType::European,
            Side::Short,
            OptionStyle::Put,
            Positive::ONE,
            pos_or_panic!(10.0), // Closing premium: $10.00 (higher due to price decrease)
            Positive::ONE,       // Closing fees: $1.00
            spos!(90.0),
            spos!(20.0),
            spos!(0.25),
        );

        // 5. Calculate closing PnL
        let closing_pnl = closed_put.pnl().unwrap();
        assert_eq!(closing_pnl.realized.unwrap(), dec!(-11.0)); // Premium paid + fees = $10.00 + $1.00 = $11.00

        // 6. Verify total loss
        let total_profit = initial_pnl.realized.unwrap() + closing_pnl.realized.unwrap();
        assert_eq!(total_profit, dec!(-8.0)); // Net loss of $6.00 ($3.00 - $11.00)
    }
}

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

    use chrono::Utc;
    use positive::{Positive, pos_or_panic, spos};

    fn create_test_transaction() -> Transaction {
        Transaction::new(
            TradeStatus::Open,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        )
    }

    #[test]
    fn test_date_time_getter() {
        let transaction = create_test_transaction();
        assert!(transaction.date_time().is_some());
    }

    #[test]
    fn test_option_type_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.option_type(), OptionType::European);
    }

    #[test]
    fn test_side_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.side(), Side::Long);
    }

    #[test]
    fn test_option_style_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.option_style(), OptionStyle::Call);
    }

    #[test]
    fn test_quantity_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.quantity(), Positive::TWO);
    }

    #[test]
    fn test_premium_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.premium(), pos_or_panic!(5.0));
    }

    #[test]
    fn test_fees_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.fees(), Positive::ONE);
    }

    #[test]
    fn test_underlying_price_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.underlying_price(), spos!(100.0));
    }

    #[test]
    fn test_days_to_expiration_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.days_to_expiration(), spos!(30.0));
    }

    #[test]
    fn test_implied_volatility_getter() {
        let transaction = create_test_transaction();
        assert_eq!(transaction.implied_volatility(), spos!(0.2));
    }
}

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

    use chrono::Utc;
    use positive::{Positive, pos_or_panic, spos};

    fn create_test_transaction() -> Transaction {
        Transaction::new(
            TradeStatus::Open,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        )
    }

    #[test]
    fn test_update_implied_volatility() {
        let mut transaction = create_test_transaction();
        transaction.update_implied_volatility(pos_or_panic!(0.25));
        assert_eq!(transaction.implied_volatility(), spos!(0.25));
    }

    #[test]
    fn test_update_underlying_price() {
        let mut transaction = create_test_transaction();
        transaction.update_underlying_price(pos_or_panic!(110.0));
        assert_eq!(transaction.underlying_price(), spos!(110.0));
    }

    #[test]
    fn test_update_days_to_expiration() {
        let mut transaction = create_test_transaction();
        transaction.update_days_to_expiration(pos_or_panic!(25.0));
        assert_eq!(transaction.days_to_expiration(), spos!(25.0));
    }
}

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

    use chrono::Utc;
    use positive::{Positive, pos_or_panic, spos};
    use rust_decimal_macros::dec;

    #[test]
    fn test_open_european_long_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Open,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(-12.0)); // (-(5.0 + 1.0) * 2.0)
    }

    #[test]
    fn test_open_european_short_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Open,
            Some(Utc::now()),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(8.0)); // ((5.0 - 1.0) * 2.0)
    }

    #[test]
    fn test_closed_european_long_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Closed,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(8.0)); // ((5.0 - 1.0) * 2.0)
    }

    #[test]
    fn test_closed_european_short_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Closed,
            Some(Utc::now()),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(-12.0)); // (-(5.0 + 1.0) * 2.0)
    }

    #[test]
    fn test_expired_european_long_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Expired,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(0.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(8.0)); // ((5.0 - 1.0) * 2.0)
    }

    #[test]
    fn test_exercised_european_long_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Exercised,
            Some(Utc::now()),
            OptionType::European,
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(110.0),
            spos!(0.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(8.0)); // ((5.0 - 1.0) * 2.0)
    }

    #[test]
    fn test_assigned_european_short_call_pnl() {
        let transaction = Transaction::new(
            TradeStatus::Assigned,
            Some(Utc::now()),
            OptionType::European,
            Side::Short,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(110.0),
            spos!(0.0),
            spos!(0.2),
        );

        let pnl = transaction.pnl().unwrap();
        assert_eq!(pnl.realized.unwrap(), dec!(-12.0)); // (-(5.0 + 1.0) * 2.0)
    }

    #[test]
    fn test_unsupported_option_type_open() {
        let transaction = Transaction::new(
            TradeStatus::Open,
            Some(Utc::now()),
            OptionType::American, // Unsupported type
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let result = transaction.pnl();
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().message,
            "Unsupported option type in Transaction"
        );
    }

    #[test]
    fn test_unsupported_option_type_closed() {
        let transaction = Transaction::new(
            TradeStatus::Closed,
            Some(Utc::now()),
            OptionType::American, // Unsupported type
            Side::Long,
            OptionStyle::Call,
            Positive::TWO,
            pos_or_panic!(5.0),
            Positive::ONE,
            spos!(100.0),
            spos!(30.0),
            spos!(0.2),
        );

        let result = transaction.pnl();
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().message,
            "Unsupported option type in Transaction"
        );
    }
}