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// -------------------------------------------------------------------------------------------------
1516use std::{collections::BTreeMap, fmt::Debug};
1718use nautilus_model::{orders::Order, position::Position};
1920use crate::Returns;
2122const IMPL_ERR: &str = "is not implemented for";
2324#[allow(unused_variables)]
25pub trait PortfolioStatistic: Debug {
26type Item;
2728fn name(&self) -> String;
2930fn calculate_from_returns(&self, returns: &Returns) -> Option<Self::Item> {
31panic!("`calculate_from_returns` {IMPL_ERR} `{}`", self.name());
32 }
3334fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
35panic!(
36"`calculate_from_realized_pnls` {IMPL_ERR} `{}`",
37self.name()
38 );
39 }
4041#[allow(dead_code)]
42fn calculate_from_orders(&self, orders: Vec<Box<dyn Order>>) -> Option<Self::Item> {
43panic!("`calculate_from_orders` {IMPL_ERR} `{}`", self.name());
44 }
4546fn calculate_from_positions(&self, positions: &[Position]) -> Option<Self::Item> {
47panic!("`calculate_from_positions` {IMPL_ERR} `{}`", self.name());
48 }
4950fn check_valid_returns(&self, returns: &Returns) -> bool {
51 !returns.is_empty()
52 }
5354fn downsample_to_daily_bins(&self, returns: &Returns) -> Returns {
55let nanos_per_day = 86_400_000_000_000; // Number of nanoseconds in a day
56let mut daily_bins = BTreeMap::new();
5758for (×tamp, &value) in returns {
59// Calculate the start of the day in nanoseconds for the given timestamp
60let day_start = timestamp - (timestamp.as_u64() % nanos_per_day);
6162// Sum returns for each day
63*daily_bins.entry(day_start).or_insert(0.0) += value;
64 }
6566 daily_bins
67 }
6869fn calculate_std(&self, returns: &Returns) -> f64 {
70let n = returns.len() as f64;
71if n < 2.0 {
72return f64::NAN;
73 }
7475let mean = returns.values().sum::<f64>() / n;
7677let variance = returns.values().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1.0);
7879 variance.sqrt()
80 }
81}