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#[repr(C)]
23#[derive(Debug, Clone)]
24#[cfg_attr(
25    feature = "python",
26    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis", from_py_object)
27)]
28#[cfg_attr(
29    feature = "python",
30    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
31)]
32pub struct AvgWinner {}
33
34impl Display for AvgWinner {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "Avg Winner")
37    }
38}
39
40impl PortfolioStatistic for AvgWinner {
41    type Item = f64;
42
43    fn name(&self) -> String {
44        self.to_string()
45    }
46
47    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
48        if realized_pnls.is_empty() {
49            return Some(f64::NAN);
50        }
51
52        let winners: Vec<f64> = realized_pnls
53            .iter()
54            .filter(|&&pnl| pnl > 0.0)
55            .copied()
56            .collect();
57
58        if winners.is_empty() {
59            return Some(f64::NAN);
60        }
61
62        let sum: f64 = winners.iter().sum();
63        Some(sum / winners.len() as f64)
64    }
65
66    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
67        None
68    }
69
70    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
71        None
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use nautilus_core::approx_eq;
78    use rstest::rstest;
79
80    use super::*;
81
82    #[rstest]
83    fn test_empty_pnls() {
84        let avg_winner = AvgWinner {};
85        let result = avg_winner.calculate_from_realized_pnls(&[]);
86        assert!(result.is_some());
87        assert!(result.unwrap().is_nan());
88    }
89
90    #[rstest]
91    fn test_no_winning_trades() {
92        let avg_winner = AvgWinner {};
93        let realized_pnls = vec![-100.0, -50.0, -200.0];
94        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
95        assert!(result.is_some());
96        assert!(result.unwrap().is_nan());
97    }
98
99    #[rstest]
100    fn test_all_winning_trades() {
101        let avg_winner = AvgWinner {};
102        let realized_pnls = vec![100.0, 50.0, 200.0];
103        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
104        assert!(result.is_some());
105        assert!(approx_eq!(
106            f64,
107            result.unwrap(),
108            116.66666666666667,
109            epsilon = 1e-9
110        ));
111    }
112
113    #[rstest]
114    fn test_mixed_trades() {
115        let avg_winner = AvgWinner {};
116        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
117        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
118        assert!(result.is_some());
119        assert!(approx_eq!(f64, result.unwrap(), 150.0, epsilon = 1e-9));
120    }
121
122    #[rstest]
123    fn test_name() {
124        let avg_winner = AvgWinner {};
125        assert_eq!(avg_winner.name(), "Avg Winner");
126    }
127}