nautilus_analysis/statistics/
win_rate.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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 win rate of a trading strategy based on realized PnLs.
23///
24/// Win rate is the percentage of profitable trades out of total trades:
25/// `Count(Trades with PnL > 0) / Total Trades`
26///
27/// Returns a value between 0.0 and 1.0, where 1.0 represents 100% winning trades.
28///
29/// Note: While a high win rate is desirable, it should be considered alongside
30/// average win/loss sizes and profit factor for complete system evaluation.
31///
32/// # References
33///
34/// - Standard trading performance metric across the industry
35/// - Tharp, V. K. (1998). *Trade Your Way to Financial Freedom*. McGraw-Hill.
36/// - Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). Wiley.
37#[repr(C)]
38#[derive(Debug, Clone)]
39#[cfg_attr(
40    feature = "python",
41    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
42)]
43pub struct WinRate {}
44
45impl Display for WinRate {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "Win Rate")
48    }
49}
50
51impl PortfolioStatistic for WinRate {
52    type Item = f64;
53
54    fn name(&self) -> String {
55        self.to_string()
56    }
57
58    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
59        if realized_pnls.is_empty() {
60            return Some(f64::NAN);
61        }
62
63        let (winners, losers): (Vec<f64>, Vec<f64>) =
64            realized_pnls.iter().partition(|&&pnl| pnl > 0.0);
65
66        let total_trades = winners.len() + losers.len();
67        Some(winners.len() as f64 / total_trades.max(1) as f64)
68    }
69    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
70        None
71    }
72
73    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
74        None
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use nautilus_core::approx_eq;
81    use rstest::rstest;
82
83    use super::*;
84
85    #[rstest]
86    fn test_empty_pnls() {
87        let win_rate = WinRate {};
88        let result = win_rate.calculate_from_realized_pnls(&[]);
89        assert!(result.is_some());
90        assert!(result.unwrap().is_nan());
91    }
92
93    #[rstest]
94    fn test_all_winning_trades() {
95        let win_rate = WinRate {};
96        let realized_pnls = vec![100.0, 50.0, 200.0];
97        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
98        assert!(result.is_some());
99        assert!(approx_eq!(f64, result.unwrap(), 1.0, epsilon = 1e-9));
100    }
101
102    #[rstest]
103    fn test_all_losing_trades() {
104        let win_rate = WinRate {};
105        let realized_pnls = vec![-100.0, -50.0, -200.0];
106        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
107        assert!(result.is_some());
108        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
109    }
110
111    #[rstest]
112    fn test_mixed_trades() {
113        let win_rate = WinRate {};
114        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
115        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
116        assert!(result.is_some());
117        assert!(approx_eq!(f64, result.unwrap(), 0.5, epsilon = 1e-9));
118    }
119
120    #[rstest]
121    fn test_name() {
122        let win_rate = WinRate {};
123        assert_eq!(win_rate.name(), "Win Rate");
124    }
125}