Skip to main content

nautilus_analysis/statistics/
winner_avg.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 average winning trade from realized PnLs.
23///
24/// Only positive PnLs count as winners. Returns `NaN` for an empty series or
25/// when there are no winning 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 AvgWinner {}
37
38impl Display for AvgWinner {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "Avg Winner")
41    }
42}
43
44impl PortfolioStatistic for AvgWinner {
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 winners: Vec<f64> = realized_pnls
57            .iter()
58            .filter(|&&pnl| pnl > 0.0)
59            .copied()
60            .collect();
61
62        if winners.is_empty() {
63            return Some(f64::NAN);
64        }
65
66        let sum: f64 = winners.iter().sum();
67        Some(sum / winners.len() as f64)
68    }
69
70    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
71        None
72    }
73
74    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
75        None
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use nautilus_core::approx_eq;
82    use rstest::rstest;
83
84    use super::*;
85
86    #[rstest]
87    fn test_empty_pnls() {
88        let avg_winner = AvgWinner {};
89        let result = avg_winner.calculate_from_realized_pnls(&[]);
90        assert!(result.is_some());
91        assert!(result.unwrap().is_nan());
92    }
93
94    #[rstest]
95    fn test_no_winning_trades() {
96        let avg_winner = AvgWinner {};
97        let realized_pnls = vec![-100.0, -50.0, -200.0];
98        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
99        assert!(result.is_some());
100        assert!(result.unwrap().is_nan());
101    }
102
103    #[rstest]
104    fn test_all_winning_trades() {
105        let avg_winner = AvgWinner {};
106        let realized_pnls = vec![100.0, 50.0, 200.0];
107        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
108        assert!(result.is_some());
109        assert!(approx_eq!(
110            f64,
111            result.unwrap(),
112            116.66666666666667,
113            epsilon = 1e-9
114        ));
115    }
116
117    #[rstest]
118    fn test_mixed_trades() {
119        let avg_winner = AvgWinner {};
120        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
121        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
122        assert!(result.is_some());
123        assert!(approx_eq!(f64, result.unwrap(), 150.0, epsilon = 1e-9));
124    }
125
126    #[rstest]
127    fn test_name() {
128        let avg_winner = AvgWinner {};
129        assert_eq!(avg_winner.name(), "Avg Winner");
130    }
131}