nanobook 0.16.2

Deterministic Rust execution engine for trading backtests: limit-order book, portfolio simulation, metrics, risk checks, and Python bindings
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
//! Fast backtest bridge: simulate portfolio returns from a pre-computed weight schedule.
//!
//! Python computes the weight schedule (factor models, signals, etc.),
//! Rust handles the inner simulation loop (rebalance, track positions, compute returns).

use std::collections::{HashMap, HashSet, hash_map::Entry};

use crate::portfolio::metrics::{
    DrawdownEvent, Metrics, compute_metrics, drawdown_series, rolling_sharpe,
};
use crate::portfolio::{CostModel, Portfolio};
use crate::types::Symbol;

/// Optional stop simulation configuration.
#[derive(Clone, Debug, Default)]
pub struct BacktestStopConfig {
    /// Fixed stop distance as fraction of entry price (e.g. 0.10 = 10%).
    pub fixed_stop_pct: Option<f64>,
    /// Trailing stop distance as fraction from watermark (e.g. 0.05 = 5%).
    pub trailing_stop_pct: Option<f64>,
    /// ATR multiple for adaptive trailing stop.
    pub atr_multiple: Option<f64>,
    /// Rolling period for ATR approximation (absolute close-to-close changes).
    pub atr_period: usize,
}

impl BacktestStopConfig {
    fn sanitized(&self) -> Option<Self> {
        let fixed = sanitize_pct(self.fixed_stop_pct);
        let trailing = sanitize_pct(self.trailing_stop_pct);
        let atr_multiple = sanitize_positive(self.atr_multiple);
        let atr_period = self.atr_period.max(1);

        if fixed.is_none() && trailing.is_none() && atr_multiple.is_none() {
            return None;
        }

        Some(Self {
            fixed_stop_pct: fixed,
            trailing_stop_pct: trailing,
            atr_multiple,
            atr_period,
        })
    }
}

/// Backtest options for v0.9 API surface.
#[derive(Clone, Debug, Default)]
pub struct BacktestBridgeOptions {
    /// Optional stop simulation configuration.
    pub stop_cfg: Option<BacktestStopConfig>,
}

#[derive(Clone, Debug, Copy)]
pub struct BarPrices {
    pub open: i64,
    pub high: i64,
    pub low: i64,
    pub close: i64,
}

#[derive(Clone, Debug, Copy, PartialEq)]
pub enum FillPolicy {
    SignalBarClose,
    NextBarOpen,
    NextBarTypical,
}

/// Stop event emitted by stop-aware backtest simulation.
#[derive(Clone, Debug)]
pub struct BacktestStopEvent {
    /// Period index where the stop triggered.
    pub period_index: usize,
    /// Symbol that was exited.
    pub symbol: Symbol,
    /// Stop threshold that was breached.
    pub trigger_price: i64,
    /// Executed exit price.
    pub exit_price: i64,
    /// Trigger reason: `fixed`, `trailing`, `atr`.
    pub reason: &'static str,
}

/// Trade lifecycle detected from target-weight transitions.
#[derive(Debug, Clone, PartialEq)]
pub struct AttributionTrade {
    pub symbol: Symbol,
    pub entry_index: usize,
    pub exit_index: Option<usize>,
    pub entry_weight: f64,
    pub exit_weight: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AttributionResult {
    pub contributions: Vec<Vec<(Symbol, f64)>>,
    pub cumulative_contributions: Vec<Vec<(Symbol, f64)>>,
    pub trades: Vec<AttributionTrade>,
}

/// Aggregate trade lifecycle counts for reporting.
#[derive(Debug, Clone, PartialEq)]
pub struct TradeAnalytics {
    pub trade_count: usize,
    pub open_trade_count: usize,
    pub closed_trade_count: usize,
}

#[derive(Debug, Clone)]
pub struct TearSheet {
    pub monthly_returns: Vec<Vec<f64>>,
    pub rolling_sharpe: Vec<f64>,
    pub drawdown_events: Vec<DrawdownEvent>,
    pub trade_analytics: TradeAnalytics,
}

pub struct BacktestBridgeResult {
    /// Per-period returns.
    pub returns: Vec<f64>,
    /// Equity curve (one entry per date + initial equity).
    pub equity_curve: Vec<i64>,
    /// Final portfolio state.
    pub final_cash: i64,
    /// Computed metrics (None if no returns).
    pub metrics: Option<Metrics>,
    /// Per-period holdings as (symbol, weight).
    pub holdings: Vec<Vec<(Symbol, f64)>>,
    /// Per-period per-symbol close-to-close returns.
    pub symbol_returns: Vec<Vec<(Symbol, f64)>>,
    /// Stop-trigger events (empty when stop simulation disabled or no triggers).
    pub stop_events: Vec<BacktestStopEvent>,
    /// Rebalance indices skipped when the fill policy needs the next bar.
    pub skipped_rebalances: Vec<usize>,
}

/// Simulate portfolio returns from a pre-computed weight schedule.
///
/// Compatibility wrapper (v0.7/v0.8 behavior): stop simulation disabled.
pub fn backtest_weights(
    weight_schedule: &[Vec<(Symbol, f64)>],
    price_schedule: &[Vec<(Symbol, BarPrices)>],
    initial_cash_cents: i64,
    cost_model: CostModel,
    fill_policy: FillPolicy,
    periods_per_year: f64,
    risk_free: f64,
) -> BacktestBridgeResult {
    backtest_weights_with_options(
        weight_schedule,
        price_schedule,
        initial_cash_cents,
        cost_model,
        fill_policy,
        periods_per_year,
        risk_free,
        BacktestBridgeOptions::default(),
    )
}

/// Simulate portfolio returns from a pre-computed weight schedule with optional v0.9 features.
///
/// Returns an empty result (no returns, no metrics) for invalid inputs:
/// mismatched schedule lengths, non-positive cash, NaN/Inf weights,
/// or negative prices.
#[allow(clippy::too_many_arguments)]
pub fn backtest_weights_with_options(
    weight_schedule: &[Vec<(Symbol, f64)>],
    price_schedule: &[Vec<(Symbol, BarPrices)>],
    initial_cash_cents: i64,
    cost_model: CostModel,
    fill_policy: FillPolicy,
    periods_per_year: f64,
    risk_free: f64,
    options: BacktestBridgeOptions,
) -> BacktestBridgeResult {
    if !valid_inputs(weight_schedule, price_schedule, initial_cash_cents) {
        return empty_result(initial_cash_cents);
    }

    let stop_cfg = options
        .stop_cfg
        .as_ref()
        .and_then(BacktestStopConfig::sanitized);

    let mut portfolio = Portfolio::new(initial_cash_cents, cost_model);
    let mut equity_curve = Vec::with_capacity(weight_schedule.len() + 1);
    equity_curve.push(initial_cash_cents);

    let mut holdings = Vec::with_capacity(weight_schedule.len());
    let mut symbol_returns = Vec::with_capacity(weight_schedule.len());
    let mut stop_events = Vec::new();
    let mut skipped_rebalances = Vec::new();

    let mut prev_prices: HashMap<Symbol, i64> = HashMap::new();
    let mut stop_trackers: HashMap<Symbol, StopTracker> = HashMap::new();

    for (period_index, (weights, bars)) in weight_schedule
        .iter()
        .zip(price_schedule.iter())
        .enumerate()
    {
        let close_prices: Vec<(Symbol, i64)> = bars
            .iter()
            .map(|&(symbol, bar_prices)| (symbol, bar_prices.close))
            .collect();
        let price_map: HashMap<Symbol, i64> = close_prices.iter().copied().collect();

        let mut period_symbol_returns = Vec::with_capacity(bars.len());
        for &(sym, bp) in bars {
            let px = bp.close;
            let ret = prev_prices
                .get(&sym)
                .copied()
                .and_then(|p0| {
                    if p0 > 0 && px > 0 {
                        Some((px - p0) as f64 / p0 as f64)
                    } else {
                        None
                    }
                })
                .unwrap_or(f64::NAN);
            period_symbol_returns.push((sym, ret));
        }
        period_symbol_returns.sort_by_key(|(sym, _)| *sym);
        symbol_returns.push(period_symbol_returns);

        if let Some(fill_prices) = fill_prices_for_period(price_schedule, period_index, fill_policy)
        {
            portfolio.rebalance_simple(weights, &fill_prices);
        } else {
            skipped_rebalances.push(period_index);
        }

        // Optional stop simulation runs after target rebalance on each bar.
        if let Some(cfg) = stop_cfg.as_ref() {
            apply_stop_cfg(
                &mut portfolio,
                &price_map,
                period_index,
                cfg,
                &mut stop_trackers,
                &mut stop_events,
            );
        }

        // Record return for this period.
        portfolio.record_return(&close_prices);

        // Track holdings and equity.
        let mut period_holdings = portfolio.current_weights(&close_prices);
        period_holdings.sort_by_key(|(sym, _)| *sym);
        holdings.push(period_holdings);

        let equity = portfolio.total_equity(&close_prices);
        equity_curve.push(equity);

        prev_prices = price_map;
    }

    let returns = portfolio.returns().to_vec();
    let metrics = compute_metrics(&returns, periods_per_year, risk_free);

    BacktestBridgeResult {
        returns,
        equity_curve,
        final_cash: portfolio.cash(),
        metrics,
        holdings,
        symbol_returns,
        stop_events,
        skipped_rebalances,
    }
}

fn fill_prices_for_period(
    price_schedule: &[Vec<(Symbol, BarPrices)>],
    period_index: usize,
    fill_policy: FillPolicy,
) -> Option<Vec<(Symbol, i64)>> {
    match fill_policy {
        FillPolicy::SignalBarClose => Some(
            price_schedule[period_index]
                .iter()
                .map(|&(symbol, bar_prices)| (symbol, bar_prices.close))
                .collect(),
        ),
        FillPolicy::NextBarOpen => {
            let next = price_schedule.get(period_index + 1)?;
            Some(
                next.iter()
                    .map(|&(symbol, bar_prices)| (symbol, bar_prices.open))
                    .collect(),
            )
        }
        FillPolicy::NextBarTypical => {
            let next = price_schedule.get(period_index + 1)?;
            Some(
                next.iter()
                    .map(|&(symbol, bar_prices)| {
                        (
                            symbol,
                            (bar_prices.high + bar_prices.low + bar_prices.close) / 3,
                        )
                    })
                    .collect(),
            )
        }
    }
}

/// Decompose a weight/return schedule into per-symbol contributions and trades.
///
/// Each period contribution is `weight * period_return` for that symbol. Cumulative
/// contribution is a simple running sum per symbol. Trade events are derived from
/// target-weight transitions: zero→non-zero opens a trade, non-zero→zero closes it.
pub fn tear_sheet(
    result: &BacktestBridgeResult,
    rolling_window: usize,
    periods_per_year: usize,
) -> TearSheet {
    let attribution = decompose_backtest(&result.holdings, &result.symbol_returns);
    let equity: Vec<f64> = result
        .equity_curve
        .iter()
        .map(|value| *value as f64)
        .collect();
    TearSheet {
        monthly_returns: monthly_return_matrix(&result.returns, 21),
        rolling_sharpe: rolling_sharpe(&result.returns, rolling_window, periods_per_year),
        drawdown_events: drawdown_series(&equity),
        trade_analytics: TradeAnalytics {
            trade_count: attribution.trades.len(),
            open_trade_count: attribution
                .trades
                .iter()
                .filter(|trade| trade.exit_index.is_none())
                .count(),
            closed_trade_count: attribution
                .trades
                .iter()
                .filter(|trade| trade.exit_index.is_some())
                .count(),
        },
    }
}

fn monthly_return_matrix(returns: &[f64], periods_per_month: usize) -> Vec<Vec<f64>> {
    if periods_per_month == 0 {
        return Vec::new();
    }
    returns
        .chunks(periods_per_month)
        .map(|chunk| chunk.iter().fold(1.0, |acc, value| acc * (1.0 + value)) - 1.0)
        .collect::<Vec<_>>()
        .chunks(12)
        .map(|year| year.to_vec())
        .collect()
}

pub fn decompose_backtest(
    weight_schedule: &[Vec<(Symbol, f64)>],
    return_schedule: &[Vec<(Symbol, f64)>],
) -> AttributionResult {
    if weight_schedule.len() != return_schedule.len() {
        return AttributionResult {
            contributions: Vec::new(),
            cumulative_contributions: Vec::new(),
            trades: Vec::new(),
        };
    }

    let mut cumulative: HashMap<Symbol, f64> = HashMap::new();
    let mut previous_weights: HashMap<Symbol, f64> = HashMap::new();
    let mut open_trades: HashMap<Symbol, (usize, f64)> = HashMap::new();
    let mut contributions = Vec::with_capacity(weight_schedule.len());
    let mut cumulative_contributions = Vec::with_capacity(weight_schedule.len());
    let mut trades = Vec::new();

    for (period_index, (weights, returns)) in
        weight_schedule.iter().zip(return_schedule).enumerate()
    {
        let weight_map: HashMap<Symbol, f64> = weights.iter().copied().collect();
        let return_map: HashMap<Symbol, f64> = returns.iter().copied().collect();
        let mut symbols: Vec<Symbol> = weight_map
            .keys()
            .chain(return_map.keys())
            .chain(previous_weights.keys())
            .copied()
            .collect();
        symbols.sort_unstable();
        symbols.dedup();

        let mut period_contrib = Vec::new();
        let mut period_cumulative = Vec::new();

        for symbol in symbols {
            let weight = weight_map
                .get(&symbol)
                .copied()
                .filter(|value| value.is_finite())
                .unwrap_or(0.0);
            let previous = previous_weights
                .get(&symbol)
                .copied()
                .filter(|value| value.is_finite())
                .unwrap_or(0.0);

            if previous == 0.0 && weight != 0.0 {
                open_trades.insert(symbol, (period_index, weight));
            } else if previous != 0.0 && weight == 0.0 {
                if let Some((entry_index, entry_weight)) = open_trades.remove(&symbol) {
                    trades.push(AttributionTrade {
                        symbol,
                        entry_index,
                        exit_index: Some(period_index),
                        entry_weight,
                        exit_weight: previous,
                    });
                }
            }

            let period_return = return_map
                .get(&symbol)
                .copied()
                .filter(|value| value.is_finite())
                .unwrap_or(0.0);
            let contribution = weight * period_return;
            if contribution != 0.0 || weight != 0.0 || previous != 0.0 {
                let running = cumulative.entry(symbol).or_insert(0.0);
                *running += contribution;
                period_contrib.push((symbol, contribution));
                period_cumulative.push((symbol, *running));
            }
        }

        period_contrib.sort_by_key(|(symbol, _)| *symbol);
        period_cumulative.sort_by_key(|(symbol, _)| *symbol);
        contributions.push(period_contrib);
        cumulative_contributions.push(period_cumulative);
        previous_weights = weight_map;
    }

    for (symbol, (entry_index, entry_weight)) in open_trades {
        let exit_weight = previous_weights
            .get(&symbol)
            .copied()
            .unwrap_or(entry_weight);
        trades.push(AttributionTrade {
            symbol,
            entry_index,
            exit_index: None,
            entry_weight,
            exit_weight,
        });
    }
    trades.sort_by_key(|trade| (trade.entry_index, trade.symbol));

    AttributionResult {
        contributions,
        cumulative_contributions,
        trades,
    }
}

fn valid_inputs(
    weight_schedule: &[Vec<(Symbol, f64)>],
    price_schedule: &[Vec<(Symbol, BarPrices)>],
    initial_cash_cents: i64,
) -> bool {
    if weight_schedule.len() != price_schedule.len() {
        return false;
    }
    if initial_cash_cents <= 0 {
        return false;
    }
    for (weights, prices) in weight_schedule.iter().zip(price_schedule.iter()) {
        for &(_, w) in weights {
            if !w.is_finite() {
                return false;
            }
        }
        for &(_, bp) in prices {
            if bp.open < 0 || bp.high < 0 || bp.low < 0 || bp.close < 0 {
                return false;
            }
            if bp.high < bp.low {
                return false;
            }
        }
    }

    true
}

fn empty_result(initial_cash_cents: i64) -> BacktestBridgeResult {
    BacktestBridgeResult {
        returns: Vec::new(),
        equity_curve: vec![initial_cash_cents],
        final_cash: initial_cash_cents,
        metrics: None,
        holdings: Vec::new(),
        symbol_returns: Vec::new(),
        stop_events: Vec::new(),
        skipped_rebalances: Vec::new(),
    }
}

#[derive(Clone, Debug)]
struct StopTracker {
    side: i8, // +1 long, -1 short
    entry_price: i64,
    reference_price: i64,
    last_price: i64,
    abs_changes: Vec<i64>,
}

impl StopTracker {
    fn new(entry_price: i64, side: i8) -> Self {
        Self {
            side,
            entry_price,
            reference_price: entry_price,
            last_price: entry_price,
            abs_changes: Vec::new(),
        }
    }

    fn update(&mut self, price: i64, atr_period: usize) {
        if price <= 0 {
            return;
        }

        let delta = (price - self.last_price).abs();
        self.abs_changes.push(delta);
        let keep = atr_period.max(1) * 6;
        if self.abs_changes.len() > keep {
            let drop_n = self.abs_changes.len() - keep;
            self.abs_changes.drain(..drop_n);
        }

        self.last_price = price;
        if self.side > 0 {
            self.reference_price = self.reference_price.max(price);
        } else {
            self.reference_price = self.reference_price.min(price);
        }
    }

    fn atr(&self, atr_period: usize) -> Option<f64> {
        if self.abs_changes.is_empty() {
            return None;
        }

        let k = atr_period.max(1).min(self.abs_changes.len());
        // Safe: k is bounded by [1, abs_changes.len()], so len() - k >= 0
        let tail = &self.abs_changes[self.abs_changes.len() - k..];
        let mean = tail.iter().map(|x| *x as f64).sum::<f64>() / k as f64;
        Some(mean)
    }
}

fn apply_stop_cfg(
    portfolio: &mut Portfolio,
    price_map: &HashMap<Symbol, i64>,
    period_index: usize,
    cfg: &BacktestStopConfig,
    trackers: &mut HashMap<Symbol, StopTracker>,
    stop_events: &mut Vec<BacktestStopEvent>,
) {
    let open_positions: Vec<(Symbol, i64, i64)> = portfolio
        .positions()
        .filter_map(|(sym, pos)| {
            if pos.is_flat() {
                return None;
            }
            let px = price_map.get(sym).copied()?;
            if px <= 0 {
                return None;
            }
            Some((*sym, pos.quantity, px))
        })
        .collect();

    let open_symbols: HashSet<Symbol> = open_positions.iter().map(|(s, _, _)| *s).collect();
    trackers.retain(|sym, _| open_symbols.contains(sym));

    for (sym, qty, price) in open_positions {
        let side = if qty >= 0 { 1 } else { -1 };

        let tracker = match trackers.entry(sym) {
            Entry::Occupied(mut entry) => {
                if entry.get().side != side {
                    entry.insert(StopTracker::new(price, side));
                } else {
                    entry.get_mut().update(price, cfg.atr_period);
                }
                entry.into_mut()
            }
            Entry::Vacant(entry) => entry.insert(StopTracker::new(price, side)),
        };

        let Some((stop_level, reason)) = effective_stop_level(cfg, tracker) else {
            continue;
        };

        let breached = if side > 0 {
            price <= stop_level
        } else {
            price >= stop_level
        };

        if breached {
            let closed = portfolio.close_position_at(sym, price);
            if closed {
                stop_events.push(BacktestStopEvent {
                    period_index,
                    symbol: sym,
                    trigger_price: stop_level,
                    exit_price: price,
                    reason,
                });
                trackers.remove(&sym);
            }
        }
    }
}

fn effective_stop_level(
    cfg: &BacktestStopConfig,
    tracker: &StopTracker,
) -> Option<(i64, &'static str)> {
    let mut candidates = Vec::new();

    if let Some(p) = cfg.fixed_stop_pct {
        let level = if tracker.side > 0 {
            (tracker.entry_price as f64 * (1.0 - p)).round() as i64
        } else {
            (tracker.entry_price as f64 * (1.0 + p)).round() as i64
        }
        .max(1);
        candidates.push((level, "fixed"));
    }

    if let Some(p) = cfg.trailing_stop_pct {
        let level = if tracker.side > 0 {
            (tracker.reference_price as f64 * (1.0 - p)).round() as i64
        } else {
            (tracker.reference_price as f64 * (1.0 + p)).round() as i64
        }
        .max(1);
        candidates.push((level, "trailing"));
    }

    // Nested rather than a let-chain: let-chains need Rust 1.88, MSRV is 1.85.
    if let Some(mult) = cfg.atr_multiple {
        if let Some(atr) = tracker.atr(cfg.atr_period) {
            let level = if tracker.side > 0 {
                (tracker.reference_price as f64 - mult * atr).round() as i64
            } else {
                (tracker.reference_price as f64 + mult * atr).round() as i64
            }
            .max(1);
            candidates.push((level, "atr"));
        }
    }

    if candidates.is_empty() {
        return None;
    }

    if tracker.side > 0 {
        candidates.into_iter().max_by_key(|(level, _)| *level)
    } else {
        candidates.into_iter().min_by_key(|(level, _)| *level)
    }
}

fn sanitize_pct(v: Option<f64>) -> Option<f64> {
    v.filter(|x| x.is_finite() && *x > 0.0 && *x < 1.0)
}

fn sanitize_positive(v: Option<f64>) -> Option<f64> {
    v.filter(|x| x.is_finite() && *x > 0.0)
}

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

    fn aapl() -> Symbol {
        Symbol::new("AAPL")
    }
    fn msft() -> Symbol {
        Symbol::new("MSFT")
    }
    fn bar(p: i64) -> BarPrices {
        BarPrices {
            open: p,
            high: p,
            low: p,
            close: p,
        }
    }

    #[test]
    fn signal_bar_close_parity_with_degenerate_ohlc() {
        let weights = vec![vec![(aapl(), 1.0)]; 3];
        let close_prices = [100_00i64, 110_00, 99_00];
        let prices: Vec<Vec<(Symbol, BarPrices)>> = close_prices
            .iter()
            .map(|&p| vec![(aapl(), bar(p))])
            .collect();
        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );
        assert_eq!(result.equity_curve.len(), 4);
        assert!(result.skipped_rebalances.is_empty());
        assert!(result.equity_curve[2] > result.equity_curve[0]);
    }

    #[test]
    fn next_bar_open_fills_at_open_t_plus_1() {
        let n = 4usize;
        let closes = [100_00i64, 101_00, 102_00, 103_00];
        let opens = [99_00i64, 100_00 + 100, 101_00 + 100, 102_00 + 100];
        let prices: Vec<Vec<(Symbol, BarPrices)>> = (0..n)
            .map(|i| {
                vec![(
                    aapl(),
                    BarPrices {
                        open: opens[i],
                        high: opens[i].max(closes[i]),
                        low: opens[i].min(closes[i]),
                        close: closes[i],
                    },
                )]
            })
            .collect();
        let weights = vec![vec![(aapl(), 1.0)]; n];
        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::NextBarOpen,
            252.0,
            0.0,
        );
        assert!(result.skipped_rebalances.contains(&(n - 1)));
        assert_eq!(result.equity_curve.len(), n + 1);
    }

    #[test]
    fn next_bar_typical_fill_price_is_hlc3() {
        let base = 100_00i64;
        let h1 = base * 102 / 100;
        let l1 = base * 99 / 100;
        let c1 = base;
        let prices = vec![
            vec![(aapl(), bar(base))],
            vec![(
                aapl(),
                BarPrices {
                    open: c1,
                    high: h1,
                    low: l1,
                    close: c1,
                },
            )],
        ];
        let weights = vec![vec![(aapl(), 1.0)]; 2];
        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::NextBarTypical,
            252.0,
            0.0,
        );
        assert!(result.skipped_rebalances.contains(&1));
        assert_eq!(result.equity_curve.len(), 3);
    }

    #[test]
    fn last_bar_skip_with_next_bar_open() {
        let n = 3usize;
        let p = 100_00i64;
        let prices: Vec<Vec<(Symbol, BarPrices)>> =
            (0..n).map(|_| vec![(aapl(), bar(p))]).collect();
        let weights: Vec<Vec<(Symbol, f64)>> = (0..n).map(|_| vec![(aapl(), 1.0)]).collect();
        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::NextBarOpen,
            252.0,
            0.0,
        );
        assert!(result.skipped_rebalances.contains(&(n - 1)));
        assert_eq!(result.equity_curve.len(), n + 1);
        assert_eq!(result.returns.len(), n);
    }

    #[test]
    fn tear_sheet_contains_reporting_payload() {
        let weights = vec![vec![(aapl(), 1.0)]; 24];
        let prices: Vec<Vec<(Symbol, BarPrices)>> = (0..24)
            .map(|i| vec![(aapl(), bar(100_00 + i as i64 * 100))])
            .collect();
        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );

        let sheet = tear_sheet(&result, 5, 252);

        assert_eq!(sheet.monthly_returns.len(), 1);
        assert_eq!(sheet.monthly_returns[0].len(), 2);
        assert_eq!(sheet.rolling_sharpe.len(), result.returns.len());
        assert!(sheet.trade_analytics.trade_count >= 1);
    }

    #[test]
    fn monthly_return_matrix_compounds_chunks() {
        let matrix = monthly_return_matrix(&[0.1, 0.1, -0.1], 2);
        assert_eq!(matrix.len(), 1);
        assert!((matrix[0][0] - 0.21).abs() < 1e-12);
        assert!((matrix[0][1] + 0.1).abs() < 1e-12);
    }

    #[test]
    fn decompose_backtest_computes_contribution_and_cumulative_sum() {
        let weights = vec![
            vec![(aapl(), 0.6), (msft(), 0.4)],
            vec![(aapl(), 0.5), (msft(), 0.5)],
        ];
        let returns = vec![
            vec![(aapl(), 0.10), (msft(), -0.05)],
            vec![(aapl(), 0.02), (msft(), 0.04)],
        ];

        let result = decompose_backtest(&weights, &returns);

        assert_eq!(
            result.contributions[0],
            vec![(aapl(), 0.06), (msft(), -0.020000000000000004)]
        );
        assert_eq!(
            result.contributions[1],
            vec![(aapl(), 0.01), (msft(), 0.02)]
        );
        assert!((result.cumulative_contributions[1][0].1 - 0.07).abs() < 1e-12);
        assert!((result.cumulative_contributions[1][1].1 - 0.0).abs() < 1e-12);
    }

    #[test]
    fn decompose_backtest_detects_entries_exits_and_open_trades() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 0.5), (msft(), 0.5)],
            vec![(msft(), 1.0)],
        ];
        let returns = vec![
            vec![(aapl(), 0.01)],
            vec![(aapl(), 0.01), (msft(), 0.02)],
            vec![(msft(), 0.03)],
        ];

        let result = decompose_backtest(&weights, &returns);

        assert!(result.trades.iter().any(|trade| {
            trade.symbol == aapl()
                && trade.entry_index == 0
                && trade.exit_index == Some(2)
                && trade.entry_weight == 1.0
                && trade.exit_weight == 0.5
        }));
        assert!(result.trades.iter().any(|trade| {
            trade.symbol == msft() && trade.entry_index == 1 && trade.exit_index.is_none()
        }));
    }

    #[test]
    fn decompose_backtest_rejects_mismatched_lengths_with_empty_result() {
        let result = decompose_backtest(&[vec![(aapl(), 1.0)]], &[]);
        assert!(result.contributions.is_empty());
        assert!(result.cumulative_contributions.is_empty());
        assert!(result.trades.is_empty());
    }

    #[test]
    fn decompose_backtest_integrates_with_backtest_weights_outputs() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(110_00))],
            vec![(aapl(), bar(99_00))],
        ];
        let backtest = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );

        let attribution = decompose_backtest(&backtest.holdings, &backtest.symbol_returns);

        for (period, contributions) in attribution.contributions.iter().enumerate() {
            let summed: f64 = contributions.iter().map(|(_, value)| value).sum();
            assert!((summed - backtest.returns[period]).abs() < 1e-12);
        }
    }

    #[test]
    fn decompose_backtest_treats_non_finite_returns_as_zero() {
        let weights = vec![vec![(aapl(), 1.0)]];
        let returns = vec![vec![(aapl(), f64::NAN)]];

        let result = decompose_backtest(&weights, &returns);

        assert_eq!(result.contributions, vec![vec![(aapl(), 0.0)]]);
        assert_eq!(result.cumulative_contributions, vec![vec![(aapl(), 0.0)]]);
    }

    #[test]
    fn basic_two_period_backtest() {
        let weights = vec![
            vec![(aapl(), 0.5), (msft(), 0.5)],
            vec![(aapl(), 0.3), (msft(), 0.7)],
        ];
        let prices = vec![
            vec![(aapl(), bar(150_00)), (msft(), bar(300_00))],
            vec![(aapl(), bar(155_00)), (msft(), bar(310_00))],
        ];

        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel {
                commission_bps: 10.0,
                slippage_bps: 0.0,
                min_commission: 0,
            },
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );

        assert_eq!(result.returns.len(), 2);
        assert_eq!(result.equity_curve.len(), 3); // initial + 2 periods
        assert!(result.metrics.is_some());
        assert_eq!(result.holdings.len(), 2);
        assert_eq!(result.symbol_returns.len(), 2);
    }

    #[test]
    fn zero_cost_preserves_equity() {
        let weights = vec![vec![(aapl(), 0.5)]];
        let prices = vec![vec![(aapl(), bar(100_00))]];

        let result = backtest_weights(
            &weights,
            &prices,
            1_000_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );

        // With zero cost and no price movement, equity should be ~initial
        let final_eq = *result
            .equity_curve
            .last()
            .expect("equity curve has one point");
        assert!((final_eq - 1_000_000_00).abs() < 200_00); // rounding tolerance
    }

    #[test]
    fn empty_schedule() {
        let result = backtest_weights(
            &[],
            &[],
            1_000_000_00,
            CostModel {
                commission_bps: 10.0,
                slippage_bps: 0.0,
                min_commission: 0,
            },
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
        );
        assert!(result.returns.is_empty());
        assert!(result.metrics.is_none());
        assert_eq!(result.equity_curve.len(), 1);
        assert!(result.holdings.is_empty());
        assert!(result.symbol_returns.is_empty());
    }

    #[test]
    fn fixed_stop_triggers_exit() {
        let weights = vec![vec![(aapl(), 1.0)], vec![(aapl(), 1.0)]];
        let prices = vec![vec![(aapl(), bar(100_00))], vec![(aapl(), bar(85_00))]];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].reason, "fixed");
        assert_eq!(result.stop_events[0].period_index, 1);
        assert_eq!(result.stop_events[0].trigger_price, 90_00);
        assert_eq!(result.stop_events[0].exit_price, 85_00);
        assert!(result.holdings[1].is_empty());
    }

    #[test]
    fn trailing_stop_emits_event() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(110_00))],
            vec![(aapl(), bar(95_00))],
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: None,
                trailing_stop_pct: Some(0.10),
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert!(!result.stop_events.is_empty());
        assert_eq!(result.stop_events[0].reason, "trailing");
    }

    #[test]
    fn first_breach_triggers_once_per_position_lifecycle() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(90_00))], // fixed 10% stop breaches here
            vec![(aapl(), bar(89_00))], // reopened, new stop basis, no second trigger
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].period_index, 1);
        assert_eq!(result.stop_events[0].reason, "fixed");
    }

    #[test]
    fn tighter_stop_reason_is_reported_when_multiple_rules_enabled() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(110_00))], // updates trailing reference
            vec![(aapl(), bar(103_00))], // breaches trailing(104.5) but not fixed(90)
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: Some(0.05),
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].reason, "trailing");
        assert_eq!(result.stop_events[0].trigger_price, 104_50);
    }

    #[test]
    fn atr_stop_triggers_on_high_volatility() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        // High volatility: 100 -> 110 -> 95 -> 85 (large moves)
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(110_00))],
            vec![(aapl(), bar(95_00))],
            vec![(aapl(), bar(85_00))],
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: None,
                trailing_stop_pct: None,
                atr_multiple: Some(2.0), // 2x ATR stop
                atr_period: 3,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        // Should trigger on high volatility
        assert!(!result.stop_events.is_empty());
        assert_eq!(result.stop_events[0].reason, "atr");
    }

    #[test]
    fn short_position_fixed_stop_triggers_on_rise() {
        let weights = vec![vec![(aapl(), -1.0)], vec![(aapl(), -1.0)]];
        // Short position: stop triggers when price rises
        let prices = vec![vec![(aapl(), bar(100_00))], vec![(aapl(), bar(115_00))]];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10), // 10% stop
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].reason, "fixed");
        assert_eq!(result.stop_events[0].trigger_price, 110_00); // 100 * 1.10
        assert_eq!(result.stop_events[0].exit_price, 115_00);
    }

    #[test]
    fn short_position_trailing_stop_adjusts_downward() {
        let weights = vec![
            vec![(aapl(), -1.0)],
            vec![(aapl(), -1.0)],
            vec![(aapl(), -1.0)],
        ];
        // Short: trailing stop moves down as price falls, then triggers on a rebound.
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(90_00))], // profit, trailing stop adjusts down to 94.50
            vec![(aapl(), bar(98_00))], // rebounds through adjusted stop
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: None,
                trailing_stop_pct: Some(0.05),
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].reason, "trailing");
        assert_eq!(result.stop_events[0].trigger_price, 94_50);
        assert_eq!(result.stop_events[0].exit_price, 98_00);
    }

    #[test]
    fn multiple_symbols_independent_stops() {
        let weights = vec![
            vec![(aapl(), 0.5), (msft(), 0.5)],
            vec![(aapl(), 0.5), (msft(), 0.5)],
        ];
        // AAPL drops 15% (triggers 10% stop), MSFT drops 5% (no trigger)
        let prices = vec![
            vec![(aapl(), bar(100_00)), (msft(), bar(100_00))],
            vec![(aapl(), bar(85_00)), (msft(), bar(95_00))],
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].symbol, aapl());
        assert!(result.holdings[1].iter().all(|(sym, _)| *sym != aapl()));
    }

    #[test]
    fn position_flip_resets_stop_tracker() {
        let weights = vec![
            vec![(aapl(), 1.0)],  // long
            vec![(aapl(), -1.0)], // flip to short
            vec![(aapl(), -1.0)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(95_00))],
            vec![(aapl(), bar(110_00))], // short stop would trigger at 105
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        // Should trigger on short position after flip
        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].period_index, 2);
    }

    #[test]
    fn stop_loss_with_low_volatility_no_atr_trigger() {
        let weights = vec![
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
            vec![(aapl(), 1.0)],
        ];
        // Low volatility: small price moves
        let prices = vec![
            vec![(aapl(), bar(100_00))],
            vec![(aapl(), bar(101_00))],
            vec![(aapl(), bar(102_00))],
            vec![(aapl(), bar(101_50))],
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: None,
                trailing_stop_pct: None,
                atr_multiple: Some(3.0), // high multiple but low volatility
                atr_period: 3,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        // Should not trigger - low volatility keeps ATR small
        assert!(result.stop_events.is_empty());
    }

    #[test]
    fn stop_loss_with_rebalance_keeps_tracking() {
        let weights = vec![
            vec![(aapl(), 0.8), (msft(), 0.2)],
            vec![(aapl(), 0.6), (msft(), 0.4)], // rebalance
            vec![(aapl(), 0.6), (msft(), 0.4)],
        ];
        let prices = vec![
            vec![(aapl(), bar(100_00)), (msft(), bar(100_00))],
            vec![(aapl(), bar(95_00)), (msft(), bar(95_00))], // both drop
            vec![(aapl(), bar(85_00)), (msft(), bar(95_00))], // AAPL triggers
        ];

        let options = BacktestBridgeOptions {
            stop_cfg: Some(BacktestStopConfig {
                fixed_stop_pct: Some(0.10),
                trailing_stop_pct: None,
                atr_multiple: None,
                atr_period: 14,
            }),
        };

        let result = backtest_weights_with_options(
            &weights,
            &prices,
            100_000_00,
            CostModel::zero(),
            FillPolicy::SignalBarClose,
            252.0,
            0.0,
            options,
        );

        // AAPL should trigger, MSFT should continue
        assert_eq!(result.stop_events.len(), 1);
        assert_eq!(result.stop_events[0].symbol, aapl());
        assert!(result.holdings[2].iter().any(|(sym, _)| *sym == msft()));
    }
}