Skip to main content

nautilus_analysis/statistics/
returns_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 arithmetic mean of portfolio returns.
23///
24/// All returns are included, so zero returns count toward the average.
25/// Returns `NaN` for an empty series.
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 ReturnsAverage {}
37
38impl Display for ReturnsAverage {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "Average (Return)")
41    }
42}
43
44impl PortfolioStatistic for ReturnsAverage {
45    type Item = f64;
46
47    fn name(&self) -> String {
48        self.to_string()
49    }
50
51    fn calculate_from_returns(&self, returns: &Returns) -> Option<Self::Item> {
52        if !self.check_valid_returns(returns) {
53            return Some(f64::NAN);
54        }
55
56        let sum: f64 = returns.values().sum();
57        let count = returns.len() as f64;
58
59        Some(sum / count)
60    }
61    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
62        None
63    }
64
65    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
66        None
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use std::collections::BTreeMap;
73
74    use nautilus_core::{UnixNanos, approx_eq};
75    use rstest::rstest;
76
77    use super::*;
78
79    fn create_returns(values: &[f64]) -> Returns {
80        let mut new_return = BTreeMap::new();
81        for (i, value) in values.iter().enumerate() {
82            new_return.insert(UnixNanos::from(i as u64), *value);
83        }
84        new_return
85    }
86
87    #[rstest]
88    fn test_empty_returns() {
89        let avg = ReturnsAverage {};
90        let returns = create_returns(&[]);
91        let result = avg.calculate_from_returns(&returns);
92        assert!(result.is_some());
93        assert!(result.unwrap().is_nan());
94    }
95
96    #[rstest]
97    fn test_all_zero() {
98        let avg = ReturnsAverage {};
99        let returns = create_returns(&[0.0, 0.0, 0.0]);
100        let result = avg.calculate_from_returns(&returns);
101        assert!(result.is_some());
102        // Average of [0.0, 0.0, 0.0] = 0.0
103        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
104    }
105
106    #[rstest]
107    fn test_mixed_with_zeros() {
108        let avg = ReturnsAverage {};
109        let returns = create_returns(&[10.0, -20.0, 0.0, 30.0, -40.0]);
110        let result = avg.calculate_from_returns(&returns);
111        assert!(result.is_some());
112        // Average of [10.0, -20.0, 0.0, 30.0, -40.0] = -20 / 5 = -4.0
113        assert!(approx_eq!(f64, result.unwrap(), -4.0, epsilon = 1e-9));
114    }
115
116    #[rstest]
117    fn test_zeros_included_in_average() {
118        let avg = ReturnsAverage {};
119        let returns = create_returns(&[1.0, 0.0, 0.0]);
120        let result = avg.calculate_from_returns(&returns);
121        assert!(result.is_some());
122        // Average of [1.0, 0.0, 0.0] = 1.0 / 3 = 0.333...
123        assert!(approx_eq!(
124            f64,
125            result.unwrap(),
126            0.3333333333333333,
127            epsilon = 1e-9
128        ));
129    }
130
131    #[rstest]
132    fn test_name() {
133        let avg = ReturnsAverage {};
134        assert_eq!(avg.name(), "Average (Return)");
135    }
136}