Skip to main content

nautilus_analysis/statistics/
expectancy.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 super::{loser_avg::AvgLoser, winner_avg::AvgWinner};
21use crate::{Returns, statistic::PortfolioStatistic};
22
23/// Calculates the expectancy of a trading strategy based on realized PnLs.
24///
25/// Expectancy is defined as: `(Average Win × Win Rate) + (Average Loss × Loss Rate)`
26/// This metric provides insight into the expected profitability per trade and helps
27/// evaluate the overall edge of a trading strategy.
28///
29/// A positive expectancy indicates a profitable system over time, while a negative
30/// expectancy suggests losses.
31///
32/// # References
33///
34/// - Tharp, V. K. (1998). *Trade Your Way to Financial Freedom*. McGraw-Hill.
35/// - Elder, A. (1993). *Trading for a Living*. John Wiley & Sons.
36/// - Vince, R. (1992). *The Mathematics of Money Management*. John Wiley & Sons.
37#[repr(C)]
38#[derive(Debug, Clone)]
39#[cfg_attr(
40    feature = "python",
41    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis", from_py_object)
42)]
43#[cfg_attr(
44    feature = "python",
45    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
46)]
47pub struct Expectancy {}
48
49impl Display for Expectancy {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "Expectancy")
52    }
53}
54
55impl PortfolioStatistic for Expectancy {
56    type Item = f64;
57
58    fn name(&self) -> String {
59        self.to_string()
60    }
61
62    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
63        if realized_pnls.is_empty() {
64            return Some(f64::NAN);
65        }
66
67        // Treat NaN as 0.0 for expectancy calculation (no winners/losers = no contribution)
68        let avg_winner = AvgWinner {}
69            .calculate_from_realized_pnls(realized_pnls)
70            .map_or(0.0, |v| if v.is_nan() { 0.0 } else { v });
71        let avg_loser = AvgLoser {}
72            .calculate_from_realized_pnls(realized_pnls)
73            .map_or(0.0, |v| if v.is_nan() { 0.0 } else { v });
74
75        // Count only non-zero trades (zeros are breakeven, neither winners nor losers)
76        let winners: Vec<f64> = realized_pnls
77            .iter()
78            .filter(|&&pnl| pnl > 0.0)
79            .copied()
80            .collect();
81        let losers: Vec<f64> = realized_pnls
82            .iter()
83            .filter(|&&pnl| pnl < 0.0)
84            .copied()
85            .collect();
86
87        let total_trades = winners.len() + losers.len();
88        if total_trades == 0 {
89            return Some(0.0);
90        }
91
92        let win_rate = winners.len() as f64 / total_trades as f64;
93        let loss_rate = losers.len() as f64 / total_trades as f64;
94
95        Some(avg_winner.mul_add(win_rate, avg_loser * loss_rate))
96    }
97    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
98        None
99    }
100
101    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
102        None
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use nautilus_core::approx_eq;
109    use rstest::rstest;
110
111    use super::*;
112
113    #[rstest]
114    fn test_empty_pnl_list() {
115        let expectancy = Expectancy {};
116        let result = expectancy.calculate_from_realized_pnls(&[]);
117        assert!(result.is_some());
118        assert!(result.unwrap().is_nan());
119    }
120
121    #[rstest]
122    fn test_all_winners() {
123        let expectancy = Expectancy {};
124        let pnls = vec![10.0, 20.0, 30.0];
125        let result = expectancy.calculate_from_realized_pnls(&pnls);
126
127        assert!(result.is_some());
128        // Expected: avg_winner = 20.0, win_rate = 1.0, loss_rate = 0.0
129        // Expectancy = (20.0 * 1.0) + (0.0 * 0.0) = 20.0
130        assert!(approx_eq!(f64, result.unwrap(), 20.0, epsilon = 1e-9));
131    }
132
133    #[rstest]
134    fn test_all_losers() {
135        let expectancy = Expectancy {};
136        let pnls = vec![-10.0, -20.0, -30.0];
137        let result = expectancy.calculate_from_realized_pnls(&pnls);
138
139        assert!(result.is_some());
140        // Expected: avg_loser = -20.0, win_rate = 0.0, loss_rate = 1.0
141        // Expectancy = (0.0 * 0.0) + (-20.0 * 1.0) = -20.0
142        assert!(approx_eq!(f64, result.unwrap(), -20.0, epsilon = 1e-9));
143    }
144
145    #[rstest]
146    fn test_mixed_pnls() {
147        let expectancy = Expectancy {};
148        let pnls = vec![10.0, -5.0, 15.0, -10.0];
149        let result = expectancy.calculate_from_realized_pnls(&pnls);
150
151        assert!(result.is_some());
152        // Expected:
153        // avg_winner = 12.5 (average of 10.0 and 15.0)
154        // avg_loser = -7.5 (average of -5.0 and -10.0)
155        // win_rate = 0.5 (2 winners out of 4 trades)
156        // loss_rate = 0.5
157        // Expectancy = (12.5 * 0.5) + (-7.5 * 0.5) = 2.5
158        assert!(approx_eq!(f64, result.unwrap(), 2.5, epsilon = 1e-9));
159    }
160
161    #[rstest]
162    fn test_single_trade() {
163        let expectancy = Expectancy {};
164        let pnls = vec![10.0];
165        let result = expectancy.calculate_from_realized_pnls(&pnls);
166
167        assert!(result.is_some());
168        // Expected: avg_winner = 10.0, win_rate = 1.0, loss_rate = 0.0
169        // Expectancy = (10.0 * 1.0) + (0.0 * 0.0) = 10.0
170        assert!(approx_eq!(f64, result.unwrap(), 10.0, epsilon = 1e-9));
171    }
172
173    #[rstest]
174    fn test_zeros_excluded_from_win_loss_rates() {
175        let expectancy = Expectancy {};
176        let pnls = vec![10.0, 0.0, -10.0];
177        let result = expectancy.calculate_from_realized_pnls(&pnls);
178
179        assert!(result.is_some());
180        // Zeros excluded: only [10.0, -10.0] counted
181        // avg_winner = 10.0, win_rate = 0.5
182        // avg_loser = -10.0, loss_rate = 0.5
183        // Expectancy = (10.0 * 0.5) + (-10.0 * 0.5) = 0.0
184        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
185    }
186
187    #[rstest]
188    fn test_only_zeros() {
189        let expectancy = Expectancy {};
190        let pnls = vec![0.0, 0.0, 0.0];
191        let result = expectancy.calculate_from_realized_pnls(&pnls);
192
193        assert!(result.is_some());
194        // No winners or losers, expectancy = 0.0
195        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
196    }
197
198    #[rstest]
199    fn test_name() {
200        let expectancy = Expectancy {};
201        assert_eq!(expectancy.name(), "Expectancy");
202    }
203}