optionstratlib 0.17.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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 24/12/25
******************************************************************************/

// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341. The existing
// call sites are internal to this file and audited for invariant-bound
// indices (fixed-length buffers, just-pushed slices, etc.).
#![allow(clippy::indexing_slicing)]

//! # Adjustment Optimizer Module
//!
//! Provides optimization algorithms for finding the best adjustment plan
//! to achieve target Greeks.
//!
//! ## Overview
//!
//! The optimizer evaluates multiple adjustment strategies and selects
//! the one with the best quality score (lowest residual + cost).
//!
//! ## Strategies
//!
//! 1. **Existing legs only**: Adjust quantities of current positions
//! 2. **Add new legs**: Add options from the chain to fill gaps
//! 3. **Use underlying**: Add shares for pure delta adjustment

use crate::chains::chain::OptionChain;
use crate::greeks::Greeks;
use crate::model::position::Position;
use crate::model::types::Side;
use num_traits::Signed;
use positive::Positive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use tracing::{debug, trace};

use super::adjustment::{AdjustmentAction, AdjustmentConfig, AdjustmentError, AdjustmentPlan};
use super::portfolio::{AdjustmentTarget, PortfolioGreeks};

/// Portfolio-level adjustment optimizer.
///
/// Finds the optimal set of adjustments to achieve target Greeks
/// given a set of positions and available options.
pub struct AdjustmentOptimizer<'a> {
    /// Current positions to adjust
    positions: &'a [Position],
    /// Option chain for finding new legs (optional)
    chain: Option<&'a OptionChain>,
    /// Configuration for adjustment behavior
    config: AdjustmentConfig,
    /// Target Greeks to achieve
    target: AdjustmentTarget,
}

impl<'a> AdjustmentOptimizer<'a> {
    /// Creates a new optimizer with positions only (no chain for new legs).
    ///
    /// # Arguments
    ///
    /// * `positions` - Current positions to adjust
    /// * `config` - Configuration for adjustment behavior
    /// * `target` - Target Greeks to achieve
    #[must_use]
    pub fn new(
        positions: &'a [Position],
        config: AdjustmentConfig,
        target: AdjustmentTarget,
    ) -> Self {
        Self {
            positions,
            chain: None,
            config,
            target,
        }
    }

    /// Creates a new optimizer with an option chain for adding new legs.
    ///
    /// # Arguments
    ///
    /// * `positions` - Current positions to adjust
    /// * `chain` - Option chain for finding new legs
    /// * `config` - Configuration for adjustment behavior
    /// * `target` - Target Greeks to achieve
    #[must_use]
    pub fn with_chain(
        positions: &'a [Position],
        chain: &'a OptionChain,
        config: AdjustmentConfig,
        target: AdjustmentTarget,
    ) -> Self {
        Self {
            positions,
            chain: Some(chain),
            config,
            target,
        }
    }

    /// Calculates the optimal adjustment plan.
    ///
    /// Tries multiple strategies and returns the best one based on
    /// quality score (residual delta + cost).
    ///
    /// # Returns
    ///
    /// * `Ok(AdjustmentPlan)` - The optimal adjustment plan
    /// * `Err(AdjustmentError)` - If no viable plan can be found
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentError::NoPositions`] when `positions` is
    /// empty, `AdjustmentError::InfeasibleTarget` when no combination
    /// of candidate strikes can close the delta gap within the
    /// configured tolerance, or `AdjustmentError::CostCeilingBreached`
    /// when every viable plan exceeds the configured `max_cost`.
    pub fn optimize(&self) -> Result<AdjustmentPlan, AdjustmentError> {
        if self.positions.is_empty() {
            return Err(AdjustmentError::NoPositions);
        }

        let current_greeks = PortfolioGreeks::from_positions(self.positions)?;

        // Check if already at target
        if self
            .target
            .is_satisfied(&current_greeks, self.config.delta_tolerance)
        {
            debug!("Already at target, no adjustment needed");
            return Ok(AdjustmentPlan::new(
                vec![],
                Decimal::ZERO,
                current_greeks,
                Decimal::ZERO,
            ));
        }

        let delta_gap = self.target.delta_gap(&current_greeks);
        let gamma_gap = self.target.gamma_gap(&current_greeks);

        debug!(
            "Current delta: {:.4}, gap: {:.4}",
            current_greeks.delta, delta_gap
        );

        let mut best_plan: Option<AdjustmentPlan> = None;

        // Strategy 1: Adjust existing legs only
        if self.config.prefer_existing_legs
            && let Ok(plan) = self.optimize_existing_legs(delta_gap, gamma_gap)
        {
            trace!("Existing legs plan quality: {:.4}", plan.quality_score);
            best_plan = Some(plan);
        }

        // Strategy 2: Add new legs (if allowed and chain available)
        if self.config.allow_new_legs
            && self.chain.is_some()
            && let Ok(plan) = self.optimize_with_new_legs(delta_gap, gamma_gap)
        {
            trace!("New legs plan quality: {:.4}", plan.quality_score);
            let beats_best = best_plan
                .as_ref()
                .is_none_or(|cur| plan.quality_score < cur.quality_score);
            if beats_best {
                best_plan = Some(plan);
            }
        }

        // Strategy 3: Use underlying (if allowed and only delta target)
        if self.config.allow_underlying
            && gamma_gap.is_none()
            && let Ok(plan) = self.optimize_with_underlying(delta_gap)
        {
            trace!("Underlying plan quality: {:.4}", plan.quality_score);
            let beats_best = best_plan
                .as_ref()
                .is_none_or(|cur| plan.quality_score < cur.quality_score);
            if beats_best {
                best_plan = Some(plan);
            }
        }

        best_plan.ok_or(AdjustmentError::NoViablePlan)
    }

    /// Optimizes by adjusting existing leg quantities only.
    fn optimize_existing_legs(
        &self,
        delta_gap: Decimal,
        _gamma_gap: Option<Decimal>,
    ) -> Result<AdjustmentPlan, AdjustmentError> {
        let mut actions = Vec::new();
        let mut remaining_delta = delta_gap;

        // Sort legs by delta contribution (highest first)
        let mut legs_with_delta: Vec<(usize, Decimal, Decimal)> = self
            .positions
            .iter()
            .enumerate()
            .filter_map(|(i, p)| {
                p.option.delta().ok().map(|d| {
                    let sign = if p.option.is_long() {
                        dec!(1)
                    } else {
                        dec!(-1)
                    };
                    let delta_per_contract = d / p.option.quantity.to_dec();
                    (i, d * sign, delta_per_contract * sign)
                })
            })
            .collect();

        // SAFETY: total order on Decimal; f64 fallback to Equal is safe for stable sort
        legs_with_delta.sort_by(|a, b| {
            b.2.abs()
                .partial_cmp(&a.2.abs())
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Greedily adjust quantities
        for (idx, _leg_delta, delta_per_contract) in legs_with_delta {
            if remaining_delta.abs() < self.config.delta_tolerance {
                break;
            }

            if delta_per_contract.abs() < dec!(0.001) {
                continue;
            }

            let current_qty = self.positions[idx].option.quantity.to_dec();
            let adjustment_qty = remaining_delta / delta_per_contract;

            // Calculate new quantity
            let new_qty = current_qty + adjustment_qty;

            // Can't have negative quantity
            if new_qty > Decimal::ZERO
                && let Ok(new_quantity) = Positive::new_decimal(new_qty)
            {
                actions.push(AdjustmentAction::ModifyQuantity {
                    leg_index: idx,
                    new_quantity,
                });
                remaining_delta -= adjustment_qty * delta_per_contract;
            }
        }

        self.build_plan(actions, remaining_delta)
    }

    /// Optimizes by adding new option legs from the chain.
    fn optimize_with_new_legs(
        &self,
        delta_gap: Decimal,
        _gamma_gap: Option<Decimal>,
    ) -> Result<AdjustmentPlan, AdjustmentError> {
        let chain = self.chain.ok_or(AdjustmentError::NoViablePlan)?;
        let mut actions = Vec::new();
        let mut remaining_delta = delta_gap;

        // Find candidate options
        let candidates = self.find_candidate_options(chain, delta_gap)?;

        let max_legs = self.config.max_new_legs.unwrap_or(2);

        for (legs_added, (option, quantity, option_delta)) in candidates.into_iter().enumerate() {
            if remaining_delta.abs() < self.config.delta_tolerance {
                break;
            }
            if legs_added >= max_legs {
                break;
            }

            let side = if delta_gap > Decimal::ZERO {
                Side::Long
            } else {
                Side::Short
            };

            actions.push(AdjustmentAction::AddLeg {
                option: Box::new(option),
                side,
                quantity,
            });

            remaining_delta -= option_delta * quantity.to_dec();
        }

        self.build_plan(actions, remaining_delta)
    }

    /// Optimizes using underlying shares only.
    fn optimize_with_underlying(
        &self,
        delta_gap: Decimal,
    ) -> Result<AdjustmentPlan, AdjustmentError> {
        // Each share has delta = 1
        let shares_needed = delta_gap;

        let actions = vec![AdjustmentAction::AddUnderlying {
            quantity: shares_needed,
        }];

        self.build_plan(actions, Decimal::ZERO)
    }

    /// Finds candidate options for delta adjustment.
    fn find_candidate_options(
        &self,
        chain: &OptionChain,
        delta_gap: Decimal,
    ) -> Result<Vec<(crate::Options, Positive, Decimal)>, AdjustmentError> {
        let mut candidates = Vec::new();
        let target_delta_sign = delta_gap.signum();

        for opt_data in chain.get_single_iter() {
            // Filter by liquidity
            if let Some(min_oi) = self.config.min_liquidity
                && opt_data.open_interest.unwrap_or(0) < min_oi
            {
                continue;
            }

            // Filter by strike range
            if let Some((min_strike, max_strike)) = &self.config.strike_range
                && (opt_data.strike_price < *min_strike || opt_data.strike_price > *max_strike)
            {
                continue;
            }

            // Try both call and put options
            for option_style in &self.config.allowed_styles {
                if let Ok(position) =
                    opt_data.get_position(Side::Long, *option_style, None, None, None)
                {
                    let option = position.option;
                    if let Ok(option_delta) = option.delta() {
                        // Check if this option helps reduce the gap
                        if option_delta.signum() == target_delta_sign {
                            let quantity_needed =
                                (delta_gap.abs() / option_delta.abs()).min(dec!(100));
                            if let Ok(qty) = Positive::new_decimal(quantity_needed) {
                                candidates.push((option, qty, option_delta));
                            }
                        }
                    }
                }
            }
        }

        // Sort by efficiency (delta per dollar cost)
        candidates.sort_by(|a, b| {
            let eff_a = a.2.abs()
                / a.0
                    .calculate_price_black_scholes()
                    .unwrap_or(dec!(1))
                    .max(dec!(0.01));
            let eff_b = b.2.abs()
                / b.0
                    .calculate_price_black_scholes()
                    .unwrap_or(dec!(1))
                    .max(dec!(0.01));
            // SAFETY: total order on Decimal; f64 fallback to Equal is safe for stable sort
            eff_b
                .partial_cmp(&eff_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(candidates)
    }

    /// Builds an adjustment plan from actions.
    fn build_plan(
        &self,
        actions: Vec<AdjustmentAction>,
        residual_delta: Decimal,
    ) -> Result<AdjustmentPlan, AdjustmentError> {
        let cost = self.estimate_cost(&actions)?;

        // Validate cost constraint
        if let Some(max_cost) = &self.config.max_cost
            && cost > max_cost.to_dec()
        {
            return Err(AdjustmentError::CostExceeded);
        }

        // Calculate resulting Greeks
        let new_positions = self.apply_actions_preview(&actions)?;
        let resulting_greeks = PortfolioGreeks::from_positions(&new_positions)?;

        Ok(AdjustmentPlan::new(
            actions,
            cost,
            resulting_greeks,
            residual_delta,
        ))
    }

    /// Estimates the cost of a set of actions.
    fn estimate_cost(&self, actions: &[AdjustmentAction]) -> Result<Decimal, AdjustmentError> {
        let mut cost = Decimal::ZERO;

        for action in actions {
            match action {
                AdjustmentAction::AddLeg {
                    option, quantity, ..
                } => {
                    let price = option
                        .calculate_price_black_scholes()
                        .map_err(|e| AdjustmentError::GreeksError(e.to_string()))?;
                    cost += price * quantity.to_dec();
                }
                AdjustmentAction::AddUnderlying { quantity } => {
                    let spot = self
                        .positions
                        .first()
                        .map(|p| p.option.underlying_price.to_dec())
                        .unwrap_or(Decimal::ZERO);
                    cost += (spot * quantity).abs();
                }
                AdjustmentAction::RollStrike {
                    leg_index,
                    new_strike,
                    quantity,
                } => {
                    if let Some(pos) = self.positions.get(*leg_index) {
                        // Cost is the difference in option prices
                        let old_price = pos
                            .option
                            .calculate_price_black_scholes()
                            .unwrap_or(Decimal::ZERO);
                        // Approximate new price (simplified)
                        let new_price = old_price
                            * (dec!(1)
                                + (new_strike.to_dec() - pos.option.strike_price.to_dec())
                                    / pos.option.underlying_price.to_dec()
                                    * dec!(0.5));
                        cost += (new_price - old_price).abs() * quantity.to_dec();
                    }
                }
                AdjustmentAction::RollExpiration { quantity, .. } => {
                    // Approximate cost for rolling expiration
                    cost += quantity.to_dec() * dec!(0.10); // Simplified estimate
                }
                _ => {}
            }
        }

        Ok(cost)
    }

    /// Applies actions to positions for preview (doesn't modify original).
    fn apply_actions_preview(
        &self,
        actions: &[AdjustmentAction],
    ) -> Result<Vec<Position>, AdjustmentError> {
        let mut positions = self.positions.to_vec();

        for action in actions {
            match action {
                AdjustmentAction::ModifyQuantity {
                    leg_index,
                    new_quantity,
                } => {
                    if let Some(pos) = positions.get_mut(*leg_index) {
                        pos.option.quantity = *new_quantity;
                    }
                }
                AdjustmentAction::AddLeg {
                    option, quantity, ..
                } => {
                    let mut new_option = *option.clone();
                    new_option.quantity = *quantity;
                    positions.push(Position::new(
                        new_option,
                        Positive::ZERO,
                        chrono::Utc::now(),
                        Positive::ZERO,
                        Positive::ZERO,
                        None,
                        None,
                    ));
                }
                AdjustmentAction::CloseLeg { leg_index } if *leg_index < positions.len() => {
                    positions.remove(*leg_index);
                }
                _ => {}
            }
        }

        Ok(positions)
    }
}

#[cfg(test)]
mod tests_optimizer {
    use super::*;
    use crate::model::ExpirationDate;
    use crate::model::types::{OptionStyle, OptionType};
    use positive::pos_or_panic;

    fn create_test_option(
        strike: Positive,
        option_style: OptionStyle,
        side: Side,
        quantity: Positive,
    ) -> crate::Options {
        crate::Options::new(
            OptionType::European,
            side,
            "TEST".to_string(),
            strike,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(0.20),
            quantity,
            Positive::HUNDRED,
            dec!(0.05),
            option_style,
            Positive::ZERO,
            None,
        )
    }

    fn create_test_position(
        strike: Positive,
        option_style: OptionStyle,
        side: Side,
        quantity: Positive,
    ) -> Position {
        let option = create_test_option(strike, option_style, side, quantity);
        Position::new(
            option,
            Positive::TWO,
            chrono::Utc::now(),
            Positive::ZERO,
            Positive::ZERO,
            None,
            None,
        )
    }

    #[test]
    fn test_optimizer_no_positions() {
        let positions: Vec<Position> = vec![];
        let config = AdjustmentConfig::default();
        let target = AdjustmentTarget::delta_neutral();

        let optimizer = AdjustmentOptimizer::new(&positions, config, target);
        let result = optimizer.optimize();

        assert!(matches!(result, Err(AdjustmentError::NoPositions)));
    }

    #[test]
    fn test_optimizer_already_neutral() {
        // Create a delta-neutral position (long call + short call at same strike)
        let pos1 = create_test_position(
            Positive::HUNDRED,
            OptionStyle::Call,
            Side::Long,
            Positive::ONE,
        );
        let pos2 = create_test_position(
            Positive::HUNDRED,
            OptionStyle::Call,
            Side::Short,
            Positive::ONE,
        );
        let positions = vec![pos1, pos2];

        let config = AdjustmentConfig::default();
        let target = AdjustmentTarget::delta_neutral();

        let optimizer = AdjustmentOptimizer::new(&positions, config, target);
        let result = optimizer.optimize();

        assert!(result.is_ok());
        let plan = result.unwrap();
        assert!(plan.actions.is_empty() || plan.is_delta_neutral(dec!(0.01)));
    }

    #[test]
    fn test_optimizer_with_underlying() {
        let pos1 = create_test_position(
            Positive::HUNDRED,
            OptionStyle::Call,
            Side::Long,
            Positive::ONE,
        );
        let positions = vec![pos1];

        let config = AdjustmentConfig::with_underlying();
        let target = AdjustmentTarget::delta_neutral();

        let optimizer = AdjustmentOptimizer::new(&positions, config, target);
        let result = optimizer.optimize();

        assert!(result.is_ok());
    }

    #[test]
    fn test_optimizer_existing_legs_only() {
        let pos1 = create_test_position(
            Positive::HUNDRED,
            OptionStyle::Call,
            Side::Long,
            Positive::TWO,
        );
        let pos2 = create_test_position(
            pos_or_panic!(110.0),
            OptionStyle::Put,
            Side::Long,
            Positive::ONE,
        );
        let positions = vec![pos1, pos2];

        let config = AdjustmentConfig::existing_legs_only();
        let target = AdjustmentTarget::delta_neutral();

        let optimizer = AdjustmentOptimizer::new(&positions, config, target);
        let result = optimizer.optimize();

        // Should either succeed or fail gracefully
        assert!(result.is_ok() || matches!(result, Err(AdjustmentError::NoViablePlan)));
    }
}