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::{self, 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 fmt::Formatter<'_>) -> 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(0.0);
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////////////////////////////////////////////////////////////////////////////////
79// Tests
80////////////////////////////////////////////////////////////////////////////////
81
82#[cfg(test)]
83mod tests {
84    use nautilus_core::approx_eq;
85    use rstest::rstest;
86
87    use super::*;
88
89    #[rstest]
90    fn test_empty_pnls() {
91        let win_rate = WinRate {};
92        let result = win_rate.calculate_from_realized_pnls(&[]);
93        assert!(result.is_some());
94        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
95    }
96
97    #[rstest]
98    fn test_all_winning_trades() {
99        let win_rate = WinRate {};
100        let realized_pnls = vec![100.0, 50.0, 200.0];
101        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
102        assert!(result.is_some());
103        assert!(approx_eq!(f64, result.unwrap(), 1.0, epsilon = 1e-9));
104    }
105
106    #[rstest]
107    fn test_all_losing_trades() {
108        let win_rate = WinRate {};
109        let realized_pnls = vec![-100.0, -50.0, -200.0];
110        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
111        assert!(result.is_some());
112        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
113    }
114
115    #[rstest]
116    fn test_mixed_trades() {
117        let win_rate = WinRate {};
118        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
119        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
120        assert!(result.is_some());
121        assert!(approx_eq!(f64, result.unwrap(), 0.5, epsilon = 1e-9));
122    }
123
124    #[rstest]
125    fn test_name() {
126        let win_rate = WinRate {};
127        assert_eq!(win_rate.name(), "Win Rate");
128    }
129}