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
//! # Probability Analysis Module
//!
//! This module provides functionality for analyzing the probability metrics of option trading strategies.
//! It includes tools for calculating expected values, profit probabilities, and risk-reward ratios based
//! on various market conditions like volatility and price trends.
//!
//! The `ProbabilityAnalysis` trait extends the `Strategies` and `Profit` traits to provide
//! comprehensive probability analysis capabilities for option strategies.

use positive::{Positive, pos_or_panic};

use crate::error::probability::ProbabilityError;
use crate::model::ProfitLossRange;
use crate::pricing::payoff::Profit;
use crate::strategies::base::Strategies;
use crate::strategies::probabilities::analysis::StrategyProbabilityAnalysis;
use crate::strategies::probabilities::utils::{
    PriceTrend, VolatilityAdjustment, calculate_single_point_probability,
};
use num_traits::ToPrimitive;
use rust_decimal::Decimal;
use tracing::warn;

/// Trait for analyzing probabilities and risk metrics of option strategies
///
/// This trait provides methods to analyze the probability characteristics of options strategies,
/// including probability of profit/loss, expected value, and risk-reward metrics.
///
/// # Type Requirements
///
/// Implementors must also implement:
/// - The `Strategies` trait, which provides access to strategy configuration
/// - The `Profit` trait, which provides profit calculation capabilities
///
/// # Key Features
///
/// - Calculate probability of profit for option strategies
/// - Compute expected values with adjustments for volatility and price trends
/// - Determine break-even points and risk-reward ratios
/// - Analyze extreme outcome probabilities (max profit and max loss scenarios)
///
pub trait ProbabilityAnalysis: Strategies + Profit {
    /// Calculate probability analysis for a strategy
    ///
    /// Performs a comprehensive probability analysis for an option strategy, taking into
    /// account optional volatility adjustments and price trend parameters.
    ///
    /// # Parameters
    ///
    /// - `volatility_adj`: Optional volatility adjustment parameters
    /// - `trend`: Optional price trend parameters indicating market direction bias
    ///
    /// # Returns
    ///
    /// - `Result<StrategyProbabilityAnalysis, ProbabilityError>`: Structured analysis results or an error
    ///
    /// # Analysis Components
    ///
    /// The returned analysis includes:
    /// - Probability of profit
    /// - Probability of reaching maximum profit
    /// - Probability of suffering maximum loss
    /// - Expected value
    /// - Break-even points
    /// - Risk-reward ratio
    fn analyze_probabilities(
        &self,
        volatility_adj: Option<VolatilityAdjustment>,
        trend: Option<PriceTrend>,
    ) -> Result<StrategyProbabilityAnalysis, ProbabilityError> {
        let break_even_points = self.get_break_even_points().unwrap();
        // If both parameters are None, return default probabilities based on profit ranges
        if volatility_adj.is_none() && trend.is_none() {
            let probability_of_profit = self.probability_of_profit(None, None)?;
            let expected_value = self.expected_value(None, None)?;

            return Ok(StrategyProbabilityAnalysis {
                probability_of_profit,
                probability_of_max_profit: Positive::ZERO, // Default value when no volatility adjustment
                probability_of_max_loss: Positive::ZERO, // Default value when no volatility adjustment
                expected_value,
                break_even_points: break_even_points.to_vec(),
                risk_reward_ratio: Positive::new_decimal(self.get_profit_ratio().unwrap())
                    .unwrap_or(Positive::ZERO),
            });
        }

        // If we have adjustments, calculate with them
        let probability_of_profit =
            self.probability_of_profit(volatility_adj.clone(), trend.clone())?;
        let expected_value = self.expected_value(volatility_adj.clone(), trend.clone())?;
        let (prob_max_profit, prob_max_loss) =
            self.calculate_extreme_probabilities(volatility_adj, trend)?;
        let risk_reward_ratio =
            Positive::new_decimal(self.get_profit_ratio().unwrap()).unwrap_or(Positive::ZERO);

        Ok(StrategyProbabilityAnalysis {
            probability_of_profit,
            probability_of_max_profit: prob_max_profit,
            probability_of_max_loss: prob_max_loss,
            expected_value,
            break_even_points: break_even_points.to_vec(),
            risk_reward_ratio,
        })
    }

    /// This function calculates the expected value of an option strategy
    /// based on an underlying price, volatility adjustments, and price trends.
    ///
    /// # Parameters
    /// - `volatility_adj`: An optional `VolatilityAdjustment` parameter, which contains
    ///   the base volatility and the number of standard deviations to adjust.
    /// - `trend`: An optional `PriceTrend` parameter, which indicates the
    ///   annual drift rate and the confidence level for the trend.
    ///
    /// # Returns
    /// - `Result<Positive, ProbabilityError>`: On success, returns a `Positive` representing
    ///   the expected value. On failure, returns an error message as a `String`.
    ///
    /// The function performs the following operations:
    /// - Determines the pricing range using the underlying asset's price and steps based
    ///   on 1% increments of the current price.
    /// - Calculates the single-point probability for each price within the range using the
    ///   provided volatility adjustments and price trends.
    /// - Computes the expected value by summing up the product of calculated probabilities
    ///   and the strategy's profit at each price point.
    /// - Logs the calculated range with probabilities for diagnostic purposes.
    ///
    /// This function relies on several auxiliary methods and traits, such as
    /// `get_underlying_price`, `best_range_to_show`, and `calculate_profit_at`,
    /// which are defined in the module's traits and utilities.
    fn expected_value(
        &self,
        volatility_adj: Option<VolatilityAdjustment>,
        trend: Option<PriceTrend>,
    ) -> Result<Positive, ProbabilityError> {
        // Special case: when volatility is zero, return the current value
        if let Some(ref vol_adj) = volatility_adj
            && vol_adj.base_volatility == Positive::ZERO
            && vol_adj.std_dev_adjustment == Positive::ZERO
        {
            let current_profit = self.calculate_profit_at(self.get_underlying_price())?;
            return if current_profit <= Decimal::ZERO {
                Ok(Positive::ZERO)
            } else {
                Ok(Positive::new_decimal(current_profit)?)
            };
        }

        let step = self.get_underlying_price() / 100.0;
        let range = self.get_best_range_to_show(step).unwrap();
        let expiration = *self.get_expiration().values().next().unwrap();

        let mut probabilities = Vec::with_capacity(range.len());
        let mut last_prob = Decimal::ZERO;

        for price in range.iter() {
            let prob = calculate_single_point_probability(
                self.get_underlying_price(),
                price,
                volatility_adj.clone(),
                trend.clone(),
                expiration,
                None,
            )?;

            let marginal_prob = prob.0 - last_prob;
            probabilities.push(marginal_prob);
            last_prob = prob.0.to_dec();
        }

        let expected_value =
            range
                .iter()
                .zip(probabilities.iter())
                .fold(0.0, |acc, (price, prob)| {
                    acc + self.calculate_profit_at(price).unwrap().to_f64().unwrap() * *prob
                });

        let total_prob: f64 = probabilities.iter().map(|p| p.to_f64()).sum();
        if (total_prob - 1.0).abs() > 0.05 {
            warn!(
                "Sum of probabilities ({}) deviates significantly from 1.0",
                total_prob
            );
        }
        if expected_value <= 0.0 {
            Ok(Positive::ZERO)
        } else {
            let trend_adjustment = trend.map_or(1.0, |t| 1.0 / (1.0 + t.drift_rate.abs()));
            Ok(pos_or_panic!(expected_value * trend_adjustment))
        }
    }

    /// Calculate probability of profit
    ///
    /// Calculates the probability that the option strategy will result in a profit at expiration.
    /// This method aggregates probabilities across all price ranges that would result in a profit.
    ///
    /// # Parameters
    ///
    /// - `volatility_adj`: Optional volatility adjustment parameters
    /// - `trend`: Optional price trend parameters
    ///
    /// # Returns
    ///
    /// - `Result<Positive, ProbabilityError>`: The probability of profit (between 0 and 1) or an error
    fn probability_of_profit(
        &self,
        volatility_adj: Option<VolatilityAdjustment>,
        trend: Option<PriceTrend>,
    ) -> Result<Positive, ProbabilityError> {
        let mut sum_of_probabilities = Positive::ZERO;
        let ranges = self.get_profit_ranges()?;
        let option = self.one_option();
        let expiration = option.expiration_date;
        let risk_free_rate = option.risk_free_rate;
        let underlying_price = option.underlying_price;
        for mut range in ranges {
            range.calculate_probability(
                &underlying_price,
                volatility_adj.clone(),
                trend.clone(),
                &expiration,
                Some(risk_free_rate),
            )?;
            sum_of_probabilities += range.probability;
        }
        Ok(sum_of_probabilities)
    }

    /// Calculate probability of loss
    ///
    /// Calculates the probability that the option strategy will result in a loss at expiration.
    /// This method aggregates probabilities across all price ranges that would result in a loss.
    ///
    /// # Parameters
    ///
    /// - `volatility_adj`: Optional volatility adjustment parameters
    /// - `trend`: Optional price trend parameters
    ///
    /// # Returns
    ///
    /// - `Result<Positive, ProbabilityError>`: The probability of loss (between 0 and 1) or an error
    fn probability_of_loss(
        &self,
        volatility_adj: Option<VolatilityAdjustment>,
        trend: Option<PriceTrend>,
    ) -> Result<Positive, ProbabilityError> {
        let mut sum_of_probabilities = Positive::ZERO;
        let ranges = self.get_loss_ranges()?;
        let option = self.one_option();
        let expiration = option.expiration_date;
        let risk_free_rate = option.risk_free_rate;
        let underlying_price = option.underlying_price;
        for mut range in ranges {
            range.calculate_probability(
                &underlying_price,
                volatility_adj.clone(),
                trend.clone(),
                &expiration,
                Some(risk_free_rate),
            )?;
            sum_of_probabilities += range.probability;
        }
        Ok(sum_of_probabilities)
    }

    /// Calculate extreme probabilities (max profit and max loss)
    ///
    /// Calculates the probabilities of reaching the maximum possible profit and
    /// suffering the maximum possible loss for the strategy.
    ///
    /// # Parameters
    ///
    /// - `volatility_adj`: Optional volatility adjustment parameters
    /// - `trend`: Optional price trend parameters
    ///
    /// # Returns
    ///
    /// - `Result<(Positive, Positive), ProbabilityError>`: A tuple containing (probability_of_max_profit,
    ///   probability_of_max_loss) or an error
    fn calculate_extreme_probabilities(
        &self,
        volatility_adj: Option<VolatilityAdjustment>,
        trend: Option<PriceTrend>,
    ) -> Result<(Positive, Positive), ProbabilityError> {
        let profit_ranges = self.get_profit_ranges()?;
        let loss_ranges = self.get_loss_ranges()?;

        let max_profit_range = profit_ranges
            .iter()
            .find(|range| range.upper_bound.is_none());

        let max_loss_range = loss_ranges.iter().find(|range| range.lower_bound.is_none());
        let expiration = *self.get_expiration().values().next().unwrap();
        let risk_free_rate = *self.get_risk_free_rate().values().next().unwrap();
        let underlying_price = self.get_underlying_price();

        let mut max_profit_prob = Positive::ZERO;
        if let Some(range) = max_profit_range {
            let mut range_clone = range.clone();
            range_clone.calculate_probability(
                underlying_price,
                volatility_adj.clone(),
                trend.clone(),
                expiration,
                Some(*risk_free_rate),
            )?;
            max_profit_prob = range_clone.probability;
        }

        let mut max_loss_prob = Positive::ZERO;
        if let Some(range) = max_loss_range {
            let mut range_clone = range.clone();
            range_clone.calculate_probability(
                underlying_price,
                volatility_adj,
                trend,
                expiration,
                Some(*risk_free_rate),
            )?;
            max_loss_prob = range_clone.probability;
        }

        Ok((max_profit_prob, max_loss_prob))
    }

    /// Get the price ranges that would result in a profit
    ///
    /// # Returns
    /// - `Result<Vec<ProfitLossRange>, ProbabilityError>`: A vector of price ranges
    ///   that result in profit, or an error
    fn get_profit_ranges(&self) -> Result<Vec<ProfitLossRange>, ProbabilityError>;

    /// # Get Profit/Loss Ranges
    ///
    /// Returns a collection of price ranges with associated probabilities for profit and loss scenarios.
    ///
    /// This function analyzes the strategy to identify distinct price ranges where the strategy
    /// would result in either profit or loss at expiration. Each range includes probability
    /// information based on the statistical model for the underlying asset.
    ///
    /// ## Returns
    ///
    /// * `Result<Vec<ProfitLossRange>, ProbabilityError>` - On success, returns a vector of
    ///   profit/loss ranges sorted by their price boundaries. On failure, returns a
    ///   `ProbabilityError` indicating what went wrong during the analysis.
    ///
    fn get_loss_ranges(&self) -> Result<Vec<ProfitLossRange>, ProbabilityError>;
}

#[cfg(test)]
mod tests_probability_analysis {
    use super::*;
    use crate::ExpirationDate;
    use crate::strategies::BullCallSpread;
    use rust_decimal_macros::dec;

    fn test_strategy() -> BullCallSpread {
        BullCallSpread::new(
            "GOLD".to_string(),
            pos_or_panic!(2505.8), // underlying_price
            pos_or_panic!(2460.0), // long_strike_itm
            pos_or_panic!(2515.0), // short_strike
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),   // implied_volatility
            dec!(0.05),           // risk_free_rate
            Positive::ZERO,       // dividend_yield
            Positive::ONE,        // quantity
            pos_or_panic!(27.26), // premium_long
            pos_or_panic!(5.33),  // premium_short
            pos_or_panic!(0.58),  // open_fee_long
            pos_or_panic!(0.58),  // close_fee_long
            pos_or_panic!(0.55),  // close_fee_short
            pos_or_panic!(0.54),  // open_fee_short
        )
    }

    #[test]
    fn test_analyze_probabilities_without_adjustments() {
        let strategy = test_strategy();
        let result = strategy.analyze_probabilities(None, None);

        assert!(result.is_ok());
        let analysis = result.unwrap();
        assert!(analysis.probability_of_profit > Positive::ZERO);
        assert_eq!(analysis.probability_of_max_profit, Positive::ZERO);
        assert_eq!(analysis.probability_of_max_loss, Positive::ZERO);
        assert!(analysis.risk_reward_ratio > Positive::ZERO);
    }

    #[test]
    fn test_analyze_probabilities_with_adjustments() {
        let strategy = test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.2),
            std_dev_adjustment: pos_or_panic!(0.05),
        });
        let trend = Some(PriceTrend {
            drift_rate: 0.1,
            confidence: 0.95,
        });

        let result = strategy.analyze_probabilities(vol_adj, trend);

        assert!(result.is_ok());
        let analysis = result.unwrap();
        assert!(analysis.probability_of_profit > Positive::ZERO);
        assert!(analysis.probability_of_max_profit >= Positive::ZERO);
        assert!(analysis.probability_of_max_loss >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_calculation() {
        let strategy = test_strategy();
        let result = strategy.expected_value(None, None);

        assert!(result.is_ok());
        assert!(result.unwrap() > Positive::ZERO);
    }

    #[test]
    fn test_expected_value_with_trend() {
        let strategy = test_strategy();
        let trend = Some(PriceTrend {
            drift_rate: 0.1,
            confidence: 0.95,
        });

        let result = strategy.expected_value(None, trend);

        assert!(result.is_ok());
        assert!(result.unwrap() > Positive::ZERO);
    }

    #[test]
    fn test_probability_of_profit() {
        let strategy = test_strategy();
        let result = strategy.probability_of_profit(None, None);

        assert!(result.is_ok());
        let prob = result.unwrap();
        assert!(prob > Positive::ZERO);
        assert!(prob <= Positive::ONE);
    }

    #[test]
    fn test_probability_of_loss() {
        let strategy = test_strategy();
        let result = strategy.probability_of_loss(None, None);

        assert!(result.is_ok());
        let prob = result.unwrap();
        assert!(prob > Positive::ZERO);
        assert!(prob <= Positive::ONE);
    }

    #[test]
    fn test_calculate_extreme_probabilities() {
        let strategy = test_strategy();
        let result = strategy.calculate_extreme_probabilities(None, None);

        assert!(result.is_ok());
        let (max_profit_prob, max_loss_prob) = result.unwrap();
        assert!(max_profit_prob >= Positive::ZERO);
        assert!(max_loss_prob >= Positive::ZERO);
        assert!(max_profit_prob + max_loss_prob <= Positive::ONE);
    }

    #[test]
    fn test_extreme_probabilities_with_adjustments() {
        let strategy = test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.2),
            std_dev_adjustment: pos_or_panic!(0.05),
        });
        let trend = Some(PriceTrend {
            drift_rate: 0.1,
            confidence: 0.95,
        });

        let result = strategy.calculate_extreme_probabilities(vol_adj, trend);

        assert!(result.is_ok());
        let (max_profit_prob, max_loss_prob) = result.unwrap();
        assert!(max_profit_prob >= Positive::ZERO);
        assert!(max_loss_prob >= Positive::ZERO);
        assert!(max_profit_prob + max_loss_prob <= Positive::ONE);
    }

    #[test]
    fn test_expected_value_with_volatility() {
        let strategy = test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.3),
            std_dev_adjustment: pos_or_panic!(0.05),
        });

        let result = strategy.expected_value(vol_adj, None);
        assert!(result.is_ok());
    }
}

#[cfg(test)]
mod tests_expected_value {
    use super::*;
    use crate::ExpirationDate;
    use crate::strategies::BullCallSpread;
    use rust_decimal_macros::dec;

    // Helper function to create a test strategy
    fn create_test_strategy() -> BullCallSpread {
        BullCallSpread::new(
            "GOLD".to_string(),
            pos_or_panic!(2505.8), // underlying_price
            pos_or_panic!(2460.0), // long_strike_itm
            pos_or_panic!(2515.0), // short_strike
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.2),   // implied_volatility
            dec!(0.05),           // risk_free_rate
            Positive::ZERO,       // dividend_yield
            Positive::ONE,        // quantity
            pos_or_panic!(27.26), // premium_long
            pos_or_panic!(5.33),  // premium_short
            pos_or_panic!(0.58),  // open_fee_long
            pos_or_panic!(0.58),  // close_fee_long
            pos_or_panic!(0.55),  // close_fee_short
            pos_or_panic!(0.54),  // open_fee_short
        )
    }

    #[test]
    fn test_expected_value_basic() {
        let strategy = create_test_strategy();
        let result = strategy.expected_value(None, None);

        assert!(result.is_ok(), "Expected value calculation should succeed");
        let ev = result.unwrap();
        assert!(
            ev >= Positive::ZERO,
            "Expected value should be non-negative"
        );
    }

    #[test]
    fn test_expected_value_with_volatility() {
        let strategy = create_test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.25),
            std_dev_adjustment: pos_or_panic!(0.1),
        });

        let result = strategy.expected_value(vol_adj, None);
        assert!(result.is_ok());
        assert!(result.unwrap() >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_with_trend() {
        let strategy = create_test_strategy();
        let trend = Some(PriceTrend {
            drift_rate: 0.1,
            confidence: 0.95,
        });

        let result = strategy.expected_value(None, trend);
        assert!(result.is_ok());
        assert!(result.unwrap() >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_with_both_adjustments() {
        let strategy = create_test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.25),
            std_dev_adjustment: pos_or_panic!(0.1),
        });
        let trend = Some(PriceTrend {
            drift_rate: 0.1,
            confidence: 0.95,
        });

        let result = strategy.expected_value(vol_adj, trend);
        assert!(result.is_ok());
        assert!(result.unwrap() >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_with_high_volatility() {
        let strategy = create_test_strategy();
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: Positive::ONE,
            std_dev_adjustment: pos_or_panic!(0.5),
        });

        let result = strategy.expected_value(vol_adj, None);
        assert!(result.is_ok());
        assert!(result.unwrap() >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_with_negative_trend() {
        let strategy = create_test_strategy();
        let trend = Some(PriceTrend {
            drift_rate: -0.2,
            confidence: 0.90,
        });

        let result = strategy.expected_value(None, trend);
        assert!(result.is_ok());
        assert!(result.unwrap() >= Positive::ZERO);
    }

    #[test]
    fn test_expected_value_probabilities_sum() {
        let strategy = create_test_strategy();
        let result = strategy.expected_value(None, None);
        assert!(result.is_ok());

        // Test passes implicitly if no warning is logged about probability sum deviation
        // The actual check is done inside the method using warn!
    }

    #[test]
    fn test_expected_value_with_minimal_volatility() {
        let strategy = create_test_strategy();
        // Use a very small but positive volatility value
        let vol_adj = Some(VolatilityAdjustment {
            base_volatility: pos_or_panic!(0.0001), // Very small but non-zero volatility
            std_dev_adjustment: Positive::ZERO,
        });

        let result = strategy.expected_value(vol_adj, None);
        assert!(
            result.is_ok(),
            "Expected value calculation should succeed with minimal volatility"
        );
        assert!(
            result.unwrap() >= Positive::ZERO,
            "Expected value should be non-negative"
        );
    }
}