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