Skip to main content

nautilus_analysis/statistics/
loser_min.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::fmt::Display;
17
18use nautilus_model::position::Position;
19
20use crate::{Returns, statistic::PortfolioStatistic};
21
22/// Calculates the smallest losing trade (least negative PnL) from realized PnLs.
23///
24/// Only negative PnLs count as losers. Returns `NaN` for an empty series or
25/// when there are no losing trades.
26#[repr(C)]
27#[derive(Debug, Clone)]
28#[cfg_attr(
29    feature = "python",
30    pyo3::pyclass(module = "nautilus_trader.analysis", from_py_object)
31)]
32#[cfg_attr(
33    feature = "python",
34    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
35)]
36pub struct MinLoser {}
37
38impl Display for MinLoser {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "Min Loser")
41    }
42}
43
44impl PortfolioStatistic for MinLoser {
45    type Item = f64;
46
47    fn name(&self) -> String {
48        self.to_string()
49    }
50
51    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
52        if realized_pnls.is_empty() {
53            return Some(f64::NAN);
54        }
55
56        let losers: Vec<f64> = realized_pnls
57            .iter()
58            .filter(|&&pnl| pnl < 0.0)
59            .copied()
60            .collect();
61
62        if losers.is_empty() {
63            return Some(f64::NAN);
64        }
65
66        losers
67            .iter()
68            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
69            .copied()
70    }
71
72    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
73        None
74    }
75
76    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
77        None
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use nautilus_core::approx_eq;
84    use rstest::rstest;
85
86    use super::*;
87
88    #[rstest]
89    fn test_empty_pnls() {
90        let min_loser = MinLoser {};
91        let result = min_loser.calculate_from_realized_pnls(&[]);
92        assert!(result.is_some());
93        assert!(result.unwrap().is_nan());
94    }
95
96    #[rstest]
97    fn test_all_positive() {
98        let min_loser = MinLoser {};
99        let pnls = vec![10.0, 20.0, 30.0];
100        let result = min_loser.calculate_from_realized_pnls(&pnls);
101        assert!(result.is_some());
102        assert!(result.unwrap().is_nan());
103    }
104
105    #[rstest]
106    fn test_all_negative() {
107        let min_loser = MinLoser {};
108        let pnls = vec![-10.0, -20.0, -30.0];
109        let result = min_loser.calculate_from_realized_pnls(&pnls);
110        assert!(result.is_some());
111        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
112    }
113
114    #[rstest]
115    fn test_mixed_pnls() {
116        let min_loser = MinLoser {};
117        let pnls = vec![10.0, -20.0, 30.0, -40.0];
118        let result = min_loser.calculate_from_realized_pnls(&pnls);
119        assert!(result.is_some());
120        assert!(approx_eq!(f64, result.unwrap(), -20.0, epsilon = 1e-9));
121    }
122
123    #[rstest]
124    fn test_with_zero() {
125        let min_loser = MinLoser {};
126        let pnls = vec![10.0, 0.0, -20.0, -30.0];
127        let result = min_loser.calculate_from_realized_pnls(&pnls);
128        assert!(result.is_some());
129        // Zero is excluded, so min loser is -20.0 (least negative loss)
130        assert!(approx_eq!(f64, result.unwrap(), -20.0, epsilon = 1e-9));
131    }
132
133    #[rstest]
134    fn test_single_negative() {
135        let min_loser = MinLoser {};
136        let pnls = vec![-10.0];
137        let result = min_loser.calculate_from_realized_pnls(&pnls);
138        assert!(result.is_some());
139        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
140    }
141
142    #[rstest]
143    fn test_name() {
144        let min_loser = MinLoser {};
145        assert_eq!(min_loser.name(), "Min Loser");
146    }
147}