Skip to main content

nautilus_analysis/
statistic.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::{collections::BTreeMap, fmt::Debug};
17
18use nautilus_model::{orders::Order, position::Position};
19
20use crate::Returns;
21
22const IMPL_ERR: &str = "is not implemented for";
23
24/// Trait for portfolio performance statistics that can be calculated from different data sources.
25///
26/// This trait provides a flexible framework for implementing various financial performance
27/// metrics that can operate on returns, realized PnLs, orders, or positions data.
28/// Each statistic implementation should override the relevant calculation methods.
29#[allow(unused_variables)]
30pub trait PortfolioStatistic: Debug {
31    type Item;
32
33    /// Returns the name of this statistic for display and identification purposes.
34    fn name(&self) -> String;
35
36    /// Calculates the statistic from time-indexed returns data.
37    ///
38    /// # Panics
39    ///
40    /// Panics if this method is not implemented for the specific statistic.
41    fn calculate_from_returns(&self, returns: &Returns) -> Option<Self::Item> {
42        panic!("`calculate_from_returns` {IMPL_ERR} `{}`", self.name());
43    }
44
45    /// Calculates the statistic from realized profit and loss values.
46    ///
47    /// # Panics
48    ///
49    /// Panics if this method is not implemented for the specific statistic.
50    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
51        panic!(
52            "`calculate_from_realized_pnls` {IMPL_ERR} `{}`",
53            self.name()
54        );
55    }
56
57    /// Calculates the statistic from order data.
58    ///
59    /// # Panics
60    ///
61    /// Panics if this method is not implemented for the specific statistic.
62    #[allow(dead_code)]
63    fn calculate_from_orders(&self, orders: Vec<Box<dyn Order>>) -> Option<Self::Item> {
64        panic!("`calculate_from_orders` {IMPL_ERR} `{}`", self.name());
65    }
66
67    /// Calculates the statistic from position data.
68    ///
69    /// # Panics
70    ///
71    /// Panics if this method is not implemented for the specific statistic.
72    fn calculate_from_positions(&self, positions: &[Position]) -> Option<Self::Item> {
73        panic!("`calculate_from_positions` {IMPL_ERR} `{}`", self.name());
74    }
75
76    /// Calculates the statistic from time-indexed strategy returns relative to a benchmark.
77    ///
78    /// Defaults to `None`; only benchmark-relative statistics (beta, alpha, information
79    /// ratio, tracking error, Treynor ratio) override this method. The `None` default
80    /// lets analyzer loops filter results by `Option` — non-benchmark statistics are
81    /// simply skipped, as `get_performance_stats_general` already does with
82    /// `calculate_from_positions` results — rather than panicking.
83    fn calculate_from_returns_with_benchmark(
84        &self,
85        returns: &Returns,
86        benchmark: &Returns,
87    ) -> Option<Self::Item> {
88        None
89    }
90
91    /// Aligns two returns series onto a common daily grid.
92    ///
93    /// Both series are first downsampled to daily bins (geometric compounding within each
94    /// UTC day), then inner-joined on shared timestamps. Timestamps present in only one
95    /// series are dropped (not zero-filled). Returns the aligned `(strategy, benchmark)`
96    /// value vectors, in ascending timestamp order.
97    fn align_returns(&self, a: &Returns, b: &Returns) -> (Vec<f64>, Vec<f64>) {
98        let a_daily = self.downsample_to_daily_bins(a);
99        let b_daily = self.downsample_to_daily_bins(b);
100
101        let mut aligned_a = Vec::new();
102        let mut aligned_b = Vec::new();
103
104        for (timestamp, &a_value) in &a_daily {
105            if let Some(&b_value) = b_daily.get(timestamp) {
106                aligned_a.push(a_value);
107                aligned_b.push(b_value);
108            }
109        }
110
111        (aligned_a, aligned_b)
112    }
113
114    /// Validates that returns data is not empty.
115    fn check_valid_returns(&self, returns: &Returns) -> bool {
116        !returns.is_empty()
117    }
118
119    /// Downsamples high-frequency returns to daily bins by geometric compounding.
120    ///
121    /// Within each UTC day, returns are combined via `(1 + r1)(1 + r2) - 1` to produce
122    /// the day's effective return, which is the standard convention for chaining
123    /// arithmetic period returns. For daily-frequency inputs (one return per day) the
124    /// bin value is identical to the input value, so callers that already operate on
125    /// daily returns observe no behavior change.
126    fn downsample_to_daily_bins(&self, returns: &Returns) -> Returns {
127        let nanos_per_day = 86_400_000_000_000; // Number of nanoseconds in a day
128        let mut daily_bins = BTreeMap::new();
129
130        for (&timestamp, &value) in returns {
131            // Calculate the start of the day in nanoseconds for the given timestamp
132            let day_start = timestamp - (timestamp.as_u64() % nanos_per_day);
133
134            // Geometrically compound returns within each day
135            let entry = daily_bins.entry(day_start).or_insert(0.0_f64);
136            *entry = (1.0_f64 + *entry).mul_add(1.0_f64 + value, -1.0_f64);
137        }
138
139        daily_bins
140    }
141
142    /// Calculates the standard deviation of returns with Bessel's correction.
143    fn calculate_std(&self, returns: &Returns) -> f64 {
144        let n = returns.len() as f64;
145        if n < 2.0 {
146            return f64::NAN;
147        }
148
149        let mean = returns.values().sum::<f64>() / n;
150
151        let variance = returns.values().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1.0);
152
153        variance.sqrt()
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use nautilus_core::{UnixNanos, approx_eq};
160    use rstest::rstest;
161
162    use super::*;
163
164    #[derive(Debug)]
165    struct DummyStat;
166
167    impl PortfolioStatistic for DummyStat {
168        type Item = f64;
169
170        fn name(&self) -> String {
171            "DummyStat".to_string()
172        }
173    }
174
175    const NANOS_PER_DAY: u64 = 86_400_000_000_000;
176    const BASE_NS: u64 = 1_600_000_000_000_000_000;
177
178    #[rstest]
179    fn test_downsample_compounds_intraday_returns() {
180        // Two intraday returns in the same UTC day: +5% then -5%.
181        //   arithmetic sum:  0.05 + (-0.05) = 0.00      (incorrect)
182        //   geometric chain: (1.05)(0.95) - 1 = -0.0025 (correct)
183        let stat = DummyStat;
184        let mut returns: Returns = BTreeMap::new();
185        returns.insert(UnixNanos::from(BASE_NS), 0.05);
186        returns.insert(UnixNanos::from(BASE_NS + 3_600_000_000_000), -0.05);
187
188        let daily = stat.downsample_to_daily_bins(&returns);
189
190        assert_eq!(daily.len(), 1);
191        let value = *daily.values().next().unwrap();
192        assert!(approx_eq!(f64, value, -0.0025, epsilon = 1e-12));
193    }
194
195    #[rstest]
196    fn test_downsample_daily_inputs_unchanged() {
197        // For one-return-per-day inputs the bin value equals the input return,
198        // so existing callers that already pass daily returns see no change.
199        let stat = DummyStat;
200        let mut returns: Returns = BTreeMap::new();
201        returns.insert(UnixNanos::from(BASE_NS), 0.01);
202        returns.insert(UnixNanos::from(BASE_NS + NANOS_PER_DAY), -0.02);
203        returns.insert(UnixNanos::from(BASE_NS + 2 * NANOS_PER_DAY), 0.015);
204
205        let daily = stat.downsample_to_daily_bins(&returns);
206
207        let values: Vec<f64> = daily.values().copied().collect();
208        assert_eq!(values.len(), 3);
209        assert!(approx_eq!(f64, values[0], 0.01, epsilon = 1e-15));
210        assert!(approx_eq!(f64, values[1], -0.02, epsilon = 1e-15));
211        assert!(approx_eq!(f64, values[2], 0.015, epsilon = 1e-15));
212    }
213
214    #[rstest]
215    fn test_downsample_chains_three_intraday_returns() {
216        // Three returns in the same day: +1%, +2%, -1%.
217        //   geometric chain: (1.01)(1.02)(0.99) - 1 = 0.019998
218        let stat = DummyStat;
219        let mut returns: Returns = BTreeMap::new();
220        returns.insert(UnixNanos::from(BASE_NS), 0.01);
221        returns.insert(UnixNanos::from(BASE_NS + 3_600_000_000_000), 0.02);
222        returns.insert(UnixNanos::from(BASE_NS + 7_200_000_000_000), -0.01);
223
224        let daily = stat.downsample_to_daily_bins(&returns);
225
226        assert_eq!(daily.len(), 1);
227        let value = *daily.values().next().unwrap();
228        let expected = 1.01_f64 * 1.02 * 0.99 - 1.0;
229        assert!(approx_eq!(f64, value, expected, epsilon = 1e-12));
230    }
231}