Skip to main content

nautilus_analysis/statistics/
loser_max.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 largest losing trade (most 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 MaxLoser {}
37
38impl Display for MaxLoser {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "Max Loser")
41    }
42}
43
44impl PortfolioStatistic for MaxLoser {
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            .min_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 max_loser = MaxLoser {};
91        let result = max_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 max_loser = MaxLoser {};
99        let pnls = vec![10.0, 20.0, 30.0];
100        let result = max_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 max_loser = MaxLoser {};
108        let pnls = vec![-10.0, -20.0, -30.0];
109        let result = max_loser.calculate_from_realized_pnls(&pnls);
110        assert!(result.is_some());
111        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
112    }
113
114    #[rstest]
115    fn test_mixed_pnls() {
116        let max_loser = MaxLoser {};
117        let pnls = vec![10.0, -20.0, 30.0, -40.0];
118        let result = max_loser.calculate_from_realized_pnls(&pnls);
119        assert!(result.is_some());
120        assert!(approx_eq!(f64, result.unwrap(), -40.0, epsilon = 1e-9));
121    }
122
123    #[rstest]
124    fn test_with_zero() {
125        let max_loser = MaxLoser {};
126        let pnls = vec![10.0, 0.0, -20.0, -30.0];
127        let result = max_loser.calculate_from_realized_pnls(&pnls);
128        assert!(result.is_some());
129        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
130    }
131
132    #[rstest]
133    fn test_single_value() {
134        let max_loser = MaxLoser {};
135        let pnls = vec![-10.0];
136        let result = max_loser.calculate_from_realized_pnls(&pnls);
137        assert!(result.is_some());
138        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
139    }
140
141    #[rstest]
142    fn test_name() {
143        let max_loser = MaxLoser {};
144        assert_eq!(max_loser.name(), "Max Loser");
145    }
146}