Skip to main content

nautilus_analysis/
analyzer.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, sync::Arc};
17
18use ahash::AHashMap;
19use indexmap::{IndexMap, IndexSet};
20use nautilus_core::{DurationNanos, UUID4, UnixNanos};
21use nautilus_model::{
22    accounts::{Account, AccountAny},
23    events::PortfolioSnapshot,
24    identifiers::{AccountId, PositionId},
25    position::Position,
26    types::{Currency, Money, fixed::MAX_FLOAT_PRECISION},
27};
28use rust_decimal::{Decimal, prelude::ToPrimitive};
29
30use crate::{
31    Returns,
32    snapshot::PortfolioStatistics,
33    statistic::PortfolioStatistic,
34    statistics::{
35        expectancy::Expectancy, long_ratio::LongRatio, loser_avg::AvgLoser, loser_max::MaxLoser,
36        loser_min::MinLoser, profit_factor::ProfitFactor, returns_avg::ReturnsAverage,
37        returns_avg_loss::ReturnsAverageLoss, returns_avg_win::ReturnsAverageWin,
38        returns_kurtosis::ReturnsKurtosis, returns_skewness::ReturnsSkewness,
39        returns_volatility::ReturnsVolatility, risk_return_ratio::RiskReturnRatio,
40        sharpe_ratio::SharpeRatio, sortino_ratio::SortinoRatio, tail_ratio::TailRatio,
41        win_rate::WinRate, winner_avg::AvgWinner, winner_max::MaxWinner, winner_min::MinWinner,
42    },
43};
44
45pub type Statistic = Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync>;
46
47/// Analyzes portfolio performance and calculates various statistics.
48///
49/// The `PortfolioAnalyzer` tracks account balances, positions, and realized PnLs
50/// to provide portfolio analysis including returns, PnL calculations,
51/// and customizable statistics.
52#[repr(C)]
53#[derive(Debug)]
54#[cfg_attr(feature = "python", pyo3::pyclass(module = "nautilus_trader.analysis"))]
55#[cfg_attr(
56    feature = "python",
57    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
58)]
59pub struct PortfolioAnalyzer {
60    pub statistics: AHashMap<String, Statistic>,
61    pub account_balances_starting: IndexMap<Currency, Money>,
62    pub account_balances: IndexMap<Currency, Money>,
63    pub positions: Vec<Position>,
64    pub realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>,
65    pub recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>,
66    pub position_returns: Returns,
67    pub portfolio_returns: Returns,
68    /// Alias for the primary returns source.
69    ///
70    /// Contains portfolio returns when available, otherwise position returns.
71    /// Kept as a public field for API stability; prefer the `returns()` accessor.
72    pub returns: Returns,
73}
74
75impl Default for PortfolioAnalyzer {
76    /// Creates a new default [`PortfolioAnalyzer`] instance.
77    fn default() -> Self {
78        let mut analyzer = Self::new();
79        analyzer.register_statistic(Arc::new(MaxWinner {}));
80        analyzer.register_statistic(Arc::new(AvgWinner {}));
81        analyzer.register_statistic(Arc::new(MinWinner {}));
82        analyzer.register_statistic(Arc::new(MinLoser {}));
83        analyzer.register_statistic(Arc::new(AvgLoser {}));
84        analyzer.register_statistic(Arc::new(MaxLoser {}));
85        analyzer.register_statistic(Arc::new(Expectancy {}));
86        analyzer.register_statistic(Arc::new(WinRate {}));
87        analyzer.register_statistic(Arc::new(ReturnsVolatility::new(None)));
88        analyzer.register_statistic(Arc::new(ReturnsSkewness::new()));
89        analyzer.register_statistic(Arc::new(ReturnsKurtosis::new()));
90        analyzer.register_statistic(Arc::new(ReturnsAverage {}));
91        analyzer.register_statistic(Arc::new(ReturnsAverageLoss {}));
92        analyzer.register_statistic(Arc::new(ReturnsAverageWin {}));
93        analyzer.register_statistic(Arc::new(SharpeRatio::new(None)));
94        analyzer.register_statistic(Arc::new(SortinoRatio::new(None)));
95        analyzer.register_statistic(Arc::new(TailRatio {}));
96        analyzer.register_statistic(Arc::new(ProfitFactor {}));
97        analyzer.register_statistic(Arc::new(RiskReturnRatio {}));
98        analyzer.register_statistic(Arc::new(LongRatio::new(None)));
99        analyzer
100    }
101}
102
103impl PortfolioAnalyzer {
104    /// Creates a new [`PortfolioAnalyzer`] instance.
105    ///
106    /// Starts with empty state.
107    #[must_use]
108    pub fn new() -> Self {
109        Self {
110            statistics: AHashMap::new(),
111            account_balances_starting: IndexMap::new(),
112            account_balances: IndexMap::new(),
113            positions: Vec::new(),
114            realized_pnls: AHashMap::new(),
115            recorded_realized_pnls: AHashMap::new(),
116            position_returns: BTreeMap::new(),
117            portfolio_returns: BTreeMap::new(),
118            returns: BTreeMap::new(),
119        }
120    }
121
122    /// Registers a new portfolio statistic for calculation.
123    pub fn register_statistic(&mut self, statistic: Statistic) {
124        self.statistics.insert(statistic.name(), statistic);
125    }
126
127    /// Removes a specific statistic from calculation.
128    pub fn deregister_statistic(&mut self, statistic: &Statistic) {
129        self.statistics.remove(&statistic.name());
130    }
131
132    /// Removes all registered statistics.
133    pub fn deregister_statistics(&mut self) {
134        self.statistics.clear();
135    }
136
137    /// Replaces the registered statistics with `statistics`.
138    ///
139    /// Used to carry a caller's registered set onto an analyzer built for a single
140    /// calculation, so custom statistics participate alongside the built-in defaults.
141    pub fn replace_statistics(&mut self, statistics: AHashMap<String, Statistic>) {
142        self.statistics = statistics;
143    }
144
145    /// Resets all analysis data to initial state.
146    ///
147    /// Registered statistics are retained; use [`Self::deregister_statistics`] to clear them.
148    pub fn reset(&mut self) {
149        self.account_balances_starting.clear();
150        self.account_balances.clear();
151        self.positions.clear();
152        self.realized_pnls.clear();
153        self.recorded_realized_pnls.clear();
154        self.position_returns.clear();
155        self.portfolio_returns.clear();
156        self.returns.clear();
157    }
158
159    /// Returns all tracked currencies.
160    #[must_use]
161    pub fn currencies(&self) -> Vec<&Currency> {
162        self.account_balances.keys().collect()
163    }
164
165    /// Retrieves a specific statistic by name.
166    #[must_use]
167    pub fn statistic(&self, name: &str) -> Option<&Statistic> {
168        self.statistics.get(name)
169    }
170
171    /// Returns the primary calculated returns.
172    ///
173    /// This returns portfolio returns when available, otherwise it falls back
174    /// to position returns for backward compatibility.
175    #[must_use]
176    pub const fn returns(&self) -> &Returns {
177        &self.returns
178    }
179
180    /// Returns the per-position calculated returns.
181    #[must_use]
182    pub const fn position_returns(&self) -> &Returns {
183        &self.position_returns
184    }
185
186    /// Returns the portfolio calculated returns.
187    #[must_use]
188    pub const fn portfolio_returns(&self) -> &Returns {
189        &self.portfolio_returns
190    }
191
192    /// Calculates statistics based on account and position data.
193    ///
194    /// This clears calculated state before calculating, while preserving
195    /// close-time PnLs recorded during portfolio processing.
196    pub fn calculate_statistics(&mut self, account: &dyn Account, positions: &[Position]) {
197        self.account_balances_starting = account.starting_balances().into_iter().collect();
198        self.account_balances = account.balances_total().into_iter().collect();
199        self.positions.clear();
200        self.realized_pnls.clear();
201        self.position_returns.clear();
202        self.portfolio_returns.clear();
203        self.returns.clear();
204
205        self.add_positions(positions);
206
207        if let Some(account_returns) = Self::calculate_account_returns(account) {
208            self.portfolio_returns = account_returns;
209            self.sync_returns_alias();
210        }
211    }
212
213    /// Builds a populated analyzer from venue accounts and positions.
214    ///
215    /// Aggregates starting and total balances across all `accounts`, adds `positions` and
216    /// `snapshots`, and seeds `recorded_realized_pnls` (close-time PnLs observed during the run).
217    #[must_use]
218    pub fn from_accounts(
219        accounts: &[AccountAny],
220        positions: &[Position],
221        snapshots: &[Position],
222        recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>,
223    ) -> Self {
224        Self::from_accounts_with_snapshots(
225            accounts,
226            positions,
227            snapshots,
228            &[],
229            recorded_realized_pnls,
230        )
231    }
232
233    /// Builds a populated analyzer from accounts, positions, and portfolio snapshots.
234    ///
235    /// Portfolio returns use daily mark-to-market equity when at least two UTC dates are
236    /// available and every account resolves to one common currency. Otherwise the primary
237    /// returns source falls back to position returns.
238    #[must_use]
239    pub fn from_accounts_with_snapshots<'a>(
240        accounts: &[AccountAny],
241        positions: &[Position],
242        position_snapshots: &[Position],
243        portfolio_snapshots: impl IntoIterator<Item = &'a PortfolioSnapshot>,
244        recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>,
245    ) -> Self {
246        let mut analyzer = Self::default();
247        let mut account_ids = Vec::with_capacity(accounts.len());
248
249        for account in accounts {
250            let account_ref: &dyn Account = match account {
251                AccountAny::Margin(margin) => margin,
252                AccountAny::Cash(cash) => cash,
253                AccountAny::Betting(betting) => betting,
254                AccountAny::Wallet(wallet) => wallet,
255            };
256            account_ids.push(account_ref.id());
257
258            for (currency, money) in account_ref.starting_balances() {
259                analyzer
260                    .account_balances_starting
261                    .entry(currency)
262                    .and_modify(|existing| *existing = *existing + money)
263                    .or_insert(money);
264            }
265
266            for (currency, money) in account_ref.balances_total() {
267                analyzer
268                    .account_balances
269                    .entry(currency)
270                    .and_modify(|existing| *existing = *existing + money)
271                    .or_insert(money);
272            }
273        }
274
275        analyzer.add_positions(positions);
276        analyzer.add_positions(position_snapshots);
277        analyzer.recorded_realized_pnls = recorded_realized_pnls;
278        analyzer.set_portfolio_returns_from_snapshots(&account_ids, portfolio_snapshots);
279        analyzer
280    }
281
282    /// Replaces the primary returns source with snapshot-backed portfolio returns when resolvable.
283    pub fn set_portfolio_returns_from_snapshots<'a>(
284        &mut self,
285        account_ids: &[AccountId],
286        snapshots: impl IntoIterator<Item = &'a PortfolioSnapshot>,
287    ) {
288        if let Some(returns) = Self::calculate_snapshot_returns(account_ids, snapshots) {
289            self.portfolio_returns = returns;
290            self.sync_returns_alias();
291        }
292    }
293
294    /// Collects an owned [`PortfolioStatistics`] snapshot from the current analyzer state.
295    #[must_use]
296    pub fn statistics(&self) -> PortfolioStatistics {
297        let mut pnls = AHashMap::new();
298
299        for currency in self.currencies() {
300            if let Ok(stats) = self.get_performance_stats_pnls(Some(currency), None) {
301                pnls.insert(currency.code.to_string(), stats);
302            }
303        }
304        PortfolioStatistics {
305            pnls,
306            returns: self.get_performance_stats_returns(),
307            general: self.get_performance_stats_general(),
308            returns_series: self.returns.clone(),
309        }
310    }
311
312    /// Adds new positions for analysis.
313    pub fn add_positions(&mut self, positions: &[Position]) {
314        self.positions.extend_from_slice(positions);
315        for position in positions {
316            if let Some(ref pnl) = position.realized_pnl {
317                self.add_trade(&position.id, position.ts_last, pnl);
318            }
319
320            if let Some(ts_closed) = position.ts_closed
321                && ts_closed.as_u64() > 0
322                && position.realized_pnl.is_some()
323            {
324                self.add_position_return(ts_closed, position.realized_return);
325            }
326        }
327    }
328
329    /// Records a trade's PnL realized at `ts_event`.
330    pub fn add_trade(&mut self, position_id: &PositionId, ts_event: UnixNanos, pnl: &Money) {
331        let currency = pnl.currency;
332        let entry = self.realized_pnls.entry(currency).or_default();
333        entry.push((*position_id, ts_event, trade_pnl_value(pnl)));
334    }
335
336    /// Records a trade's PnL realized at `ts_event`, observed during portfolio processing.
337    pub fn record_trade(&mut self, position_id: &PositionId, ts_event: UnixNanos, pnl: &Money) {
338        let currency = pnl.currency;
339        let entry = self.recorded_realized_pnls.entry(currency).or_default();
340        entry.push((*position_id, ts_event, trade_pnl_value(pnl)));
341    }
342
343    /// Records a position return at a specific timestamp.
344    pub fn add_position_return(&mut self, timestamp: UnixNanos, value: f64) {
345        self.position_returns
346            .entry(timestamp)
347            .and_modify(|existing_value| *existing_value += value)
348            .or_insert(value);
349
350        // Mirror writes into the `returns` alias when no portfolio returns exist.
351        // This avoids calling `sync_returns_alias` (which clones the full map)
352        // on every insert.
353        if self.portfolio_returns.is_empty() {
354            self.returns
355                .entry(timestamp)
356                .and_modify(|existing_value| *existing_value += value)
357                .or_insert(value);
358        }
359    }
360
361    /// Records a return at a specific timestamp.
362    ///
363    /// This is a backward-compatible alias for [`Self::add_position_return`].
364    pub fn add_return(&mut self, timestamp: UnixNanos, value: f64) {
365        self.add_position_return(timestamp, value);
366    }
367
368    /// Computes daily portfolio returns from account balance snapshots.
369    ///
370    /// Returns `None` (falling back to per-position returns) when:
371    /// - Fewer than two account state events exist.
372    /// - Any event carries multiple balance currencies.
373    /// - The balance currency changes between events.
374    /// - Fewer than two distinct calendar days have balance data.
375    ///
376    /// Multi-currency accounts are not yet supported; the caller silently
377    /// receives per-position returns in that case.
378    fn calculate_account_returns(account: &dyn Account) -> Option<Returns> {
379        let mut events = account.events();
380        if events.len() < 2 {
381            return None;
382        }
383
384        events.sort_by_key(|event| event.ts_event);
385
386        let mut currency = None;
387        let mut daily_balances = BTreeMap::new();
388
389        for event in events {
390            if event.balances.is_empty() {
391                continue;
392            }
393
394            if event.balances.len() != 1 {
395                return None;
396            }
397
398            let balance = event.balances[0];
399
400            if let Some(existing_currency) = currency {
401                if existing_currency != balance.currency {
402                    return None;
403                }
404            } else {
405                currency = Some(balance.currency);
406            }
407
408            let day_start = event.ts_event.floor(DurationNanos::from_days(1));
409            daily_balances.insert(day_start, balance.total.as_f64());
410        }
411
412        Self::calculate_daily_returns(&daily_balances)
413    }
414
415    fn calculate_snapshot_returns<'a>(
416        account_ids: &[AccountId],
417        snapshots: impl IntoIterator<Item = &'a PortfolioSnapshot>,
418    ) -> Option<Returns> {
419        let expected_accounts: IndexSet<AccountId> = account_ids.iter().copied().collect();
420        if expected_accounts.is_empty() {
421            return None;
422        }
423
424        let mut currency = None;
425        let mut equity_by_account: AHashMap<AccountId, BTreeMap<UnixNanos, f64>> = AHashMap::new();
426
427        for snapshot in snapshots {
428            if !expected_accounts.contains(&snapshot.account_id) {
429                continue;
430            }
431
432            if !snapshot.unpriced_instruments.is_empty() {
433                continue;
434            }
435
436            if snapshot.total_equity.len() != 1 {
437                return None;
438            }
439
440            let equity = snapshot
441                .base_currency_equity
442                .unwrap_or(snapshot.total_equity[0]);
443
444            if let Some(existing_currency) = currency {
445                if existing_currency != equity.currency {
446                    return None;
447                }
448            } else {
449                currency = Some(equity.currency);
450            }
451
452            let is_registration = !equity_by_account.contains_key(&snapshot.account_id);
453            let day_start = Self::snapshot_day_start(snapshot.ts_event, is_registration);
454            equity_by_account
455                .entry(snapshot.account_id)
456                .or_default()
457                .insert(day_start, equity.as_f64());
458        }
459
460        if equity_by_account.len() != expected_accounts.len() {
461            return None;
462        }
463
464        let first_day = equity_by_account
465            .values()
466            .filter_map(|equity| equity.keys().next().copied())
467            .min()?;
468        let last_day = equity_by_account
469            .values()
470            .filter_map(|equity| equity.keys().next_back().copied())
471            .max()?;
472        let mut daily_equity = BTreeMap::new();
473        let mut current_equity = AHashMap::new();
474        let mut current_day = first_day;
475
476        loop {
477            for account_id in &expected_accounts {
478                if let Some(equity) = equity_by_account
479                    .get(account_id)
480                    .and_then(|values| values.get(&current_day))
481                {
482                    current_equity.insert(*account_id, *equity);
483                }
484            }
485
486            if current_equity.len() == expected_accounts.len() {
487                let total = expected_accounts
488                    .iter()
489                    .map(|account_id| current_equity[account_id])
490                    .sum();
491                daily_equity.insert(current_day, total);
492            }
493
494            if current_day >= last_day {
495                break;
496            }
497
498            current_day += DurationNanos::from_days(1);
499        }
500
501        Self::calculate_daily_returns(&daily_equity)
502    }
503
504    fn snapshot_day_start(ts_event: UnixNanos, is_registration: bool) -> UnixNanos {
505        let day = DurationNanos::from_days(1);
506        let day_start = ts_event.floor(day);
507        if is_registration || (ts_event == day_start && !ts_event.is_zero()) {
508            day_start.saturating_sub(day)
509        } else {
510            day_start
511        }
512    }
513
514    fn calculate_daily_returns(daily_equity: &BTreeMap<UnixNanos, f64>) -> Option<Returns> {
515        if daily_equity.len() < 2 {
516            return None;
517        }
518
519        let mut returns = Returns::new();
520        let mut current_day = *daily_equity.keys().next()?;
521        let last_day = *daily_equity.keys().next_back()?;
522        let mut current_balance: Option<f64> = None;
523        let mut previous_balance: Option<f64> = None;
524
525        loop {
526            if let Some(balance) = daily_equity.get(&current_day) {
527                current_balance = Some(*balance);
528            }
529
530            let balance = current_balance?;
531
532            if let Some(previous) = previous_balance
533                && previous != 0.0
534            {
535                let value: f64 = (balance / previous) - 1.0;
536                if value.is_finite() {
537                    returns.insert(current_day, value);
538                }
539            }
540
541            previous_balance = Some(balance);
542
543            if current_day >= last_day {
544                break;
545            }
546
547            current_day += DurationNanos::from_days(1);
548        }
549
550        (!returns.is_empty()).then_some(returns)
551    }
552
553    /// Retrieves trade PnL records for a specific currency.
554    ///
555    /// Each record is `(position_id, ts_event, realized_pnl)`, where `ts_event` is the
556    /// position's last event time (the close time for closed cycles). Duplicate position
557    /// IDs are preserved for NETTING position cycles. Records are returned in ascending
558    /// `ts_event` order, with ties keeping their source order.
559    ///
560    /// Native PnLs (derived from analyzed positions) and PnLs recorded live during
561    /// portfolio processing are merged per cycle: a native record is excluded only when a
562    /// recorded record shares its `(position_id, ts_event)`. Recorded values therefore take
563    /// precedence for the cycles they cover, while native cycles that were never recorded
564    /// are retained rather than dropped by position ID.
565    ///
566    /// Returns `None` if no PnLs exist, or if multiple currencies exist
567    /// without an explicit currency specified.
568    #[must_use]
569    pub fn trade_pnl_records(
570        &self,
571        currency: Option<&Currency>,
572    ) -> Option<Vec<(PositionId, UnixNanos, f64)>> {
573        if self.realized_pnls.is_empty() && self.recorded_realized_pnls.is_empty() {
574            return None;
575        }
576
577        // Require explicit currency for multi-currency portfolios to avoid nondeterminism
578        let currency = self.resolve_pnl_currency(currency).ok()?;
579
580        let realized_pnls = self.realized_pnls.get(&currency);
581        let recorded_realized_pnls = self.recorded_realized_pnls.get(&currency);
582
583        let mut output = match (realized_pnls, recorded_realized_pnls) {
584            (None, None) => return None,
585            (Some(realized_pnls), None) => realized_pnls.clone(),
586            (None, Some(recorded_realized_pnls)) => recorded_realized_pnls.clone(),
587            (Some(realized_pnls), Some(recorded_realized_pnls)) => {
588                let recorded_keys: IndexSet<(PositionId, UnixNanos)> = recorded_realized_pnls
589                    .iter()
590                    .map(|(position_id, ts_event, _)| {
591                        (canonical_position_id(*position_id), *ts_event)
592                    })
593                    .collect();
594                let mut merged: Vec<(PositionId, UnixNanos, f64)> = realized_pnls
595                    .iter()
596                    .copied()
597                    .filter(|(position_id, ts_event, _)| {
598                        let key = (canonical_position_id(*position_id), *ts_event);
599                        !recorded_keys.contains(&key)
600                    })
601                    .collect();
602                merged.extend(recorded_realized_pnls.iter().copied());
603
604                merged
605            }
606        };
607
608        // Stable sort, so records sharing a timestamp keep their source order and the
609        // sequence stays deterministic across runs.
610        output.sort_by_key(|(_, ts_event, _)| *ts_event);
611
612        Some(output)
613    }
614
615    /// Retrieves realized PnLs for a specific currency.
616    ///
617    /// Each record is `(position_id, ts_event, realized_pnl)`, in ascending `ts_event` order.
618    /// Returns `None` if no PnLs exist, or if multiple currencies exist without an explicit
619    /// currency specified.
620    #[must_use]
621    pub fn realized_pnls(
622        &self,
623        currency: Option<&Currency>,
624    ) -> Option<Vec<(PositionId, UnixNanos, f64)>> {
625        self.trade_pnl_records(currency)
626    }
627
628    /// Calculates total PnL including unrealized PnL if provided.
629    ///
630    /// # Errors
631    ///
632    /// Returns an error if:
633    /// - No currency is specified in a multi-currency portfolio.
634    /// - The specified currency is not found in account balances.
635    /// - The unrealized PnL currency does not match the specified currency.
636    #[expect(clippy::missing_panics_doc)] // Guarded by length check
637    pub fn total_pnl(
638        &self,
639        currency: Option<&Currency>,
640        unrealized_pnl: Option<&Money>,
641    ) -> Result<f64, &'static str> {
642        if self.account_balances.is_empty() {
643            return Ok(0.0);
644        }
645
646        // Require explicit currency for multi-currency portfolios to avoid nondeterminism
647        let currency = match currency {
648            Some(c) => c,
649            None if self.account_balances.len() == 1 => {
650                self.account_balances.keys().next().expect("len is 1")
651            }
652            None => return Err("Currency must be specified for multi-currency portfolio"),
653        };
654
655        if let Some(unrealized_pnl) = unrealized_pnl
656            && unrealized_pnl.currency != *currency
657        {
658            return Err("Unrealized PnL currency does not match specified currency");
659        }
660
661        let account_balance = self
662            .account_balances
663            .get(currency)
664            .ok_or("Specified currency not found in account balances")?;
665
666        let default_money = &Money::zero(*currency);
667        let account_balance_starting = self
668            .account_balances_starting
669            .get(currency)
670            .unwrap_or(default_money);
671
672        let unrealized_pnl_f64 = unrealized_pnl.map_or(0.0, Money::as_f64);
673        Ok((account_balance.as_f64() - account_balance_starting.as_f64()) + unrealized_pnl_f64)
674    }
675
676    /// Calculates total PnL as a percentage of starting balance.
677    ///
678    /// # Errors
679    ///
680    /// Returns an error if:
681    /// - No currency is specified in a multi-currency portfolio.
682    /// - The specified currency is not found in account balances.
683    /// - The unrealized PnL currency does not match the specified currency.
684    #[expect(clippy::missing_panics_doc)] // Guarded by length check
685    pub fn total_pnl_percentage(
686        &self,
687        currency: Option<&Currency>,
688        unrealized_pnl: Option<&Money>,
689    ) -> Result<f64, &'static str> {
690        if self.account_balances.is_empty() {
691            return Ok(0.0);
692        }
693
694        // Require explicit currency for multi-currency portfolios to avoid nondeterminism
695        let currency = match currency {
696            Some(c) => c,
697            None if self.account_balances.len() == 1 => {
698                self.account_balances.keys().next().expect("len is 1")
699            }
700            None => return Err("Currency must be specified for multi-currency portfolio"),
701        };
702
703        if let Some(unrealized_pnl) = unrealized_pnl
704            && unrealized_pnl.currency != *currency
705        {
706            return Err("Unrealized PnL currency does not match specified currency");
707        }
708
709        let account_balance = self
710            .account_balances
711            .get(currency)
712            .ok_or("Specified currency not found in account balances")?;
713
714        let default_money = &Money::zero(*currency);
715        let account_balance_starting = self
716            .account_balances_starting
717            .get(currency)
718            .unwrap_or(default_money);
719
720        if account_balance_starting.as_decimal() == Decimal::ZERO {
721            return Ok(0.0);
722        }
723
724        let unrealized_pnl_f64 = unrealized_pnl.map_or(0.0, Money::as_f64);
725        let current = account_balance.as_f64() + unrealized_pnl_f64;
726        let starting = account_balance_starting.as_f64();
727        let difference = current - starting;
728
729        Ok((difference / starting) * 100.0)
730    }
731
732    /// Gets all PnL-related performance statistics.
733    ///
734    /// # Errors
735    ///
736    /// Returns an error if:
737    ///
738    /// - No currency specified for a multi-currency portfolio.
739    /// - Unrealized PnL currency not matching the specified currency.
740    /// - Specified currency not found in account balances.
741    pub fn get_performance_stats_pnls(
742        &self,
743        currency: Option<&Currency>,
744        unrealized_pnl: Option<&Money>,
745    ) -> Result<AHashMap<String, f64>, &'static str> {
746        let mut output = AHashMap::new();
747
748        output.insert(
749            "PnL (total)".to_string(),
750            self.total_pnl(currency, unrealized_pnl)?,
751        );
752        output.insert(
753            "PnL% (total)".to_string(),
754            self.total_pnl_percentage(currency, unrealized_pnl)?,
755        );
756
757        let records = self.trade_pnl_records(currency);
758        let has_records = !self.realized_pnls.is_empty() || !self.recorded_realized_pnls.is_empty();
759
760        // `trade_pnl_records` returns `None` both when the resolved currency has no records
761        // and when an unspecified currency cannot be resolved. Only the first may dispatch on
762        // an empty slice; the second would report values that ignore real PnLs.
763        if records.is_none() && has_records {
764            self.resolve_pnl_currency(currency)?;
765        }
766
767        let realized_pnls: Vec<f64> = records
768            .unwrap_or_default()
769            .iter()
770            .map(|(_, _, pnl)| *pnl)
771            .collect();
772
773        for (name, stat) in &self.statistics {
774            if let Some(value) = stat.calculate_from_realized_pnls(&realized_pnls) {
775                output.insert(name.clone(), value);
776            }
777        }
778
779        Ok(output)
780    }
781
782    /// Gets all return-based performance statistics.
783    #[must_use]
784    pub fn get_performance_stats_returns(&self) -> AHashMap<String, f64> {
785        self.calculate_returns_stats(self.returns())
786    }
787
788    /// Gets all position-return-based performance statistics.
789    #[must_use]
790    pub fn get_performance_stats_position_returns(&self) -> AHashMap<String, f64> {
791        self.calculate_returns_stats(self.position_returns())
792    }
793
794    /// Gets all portfolio-return-based performance statistics.
795    #[must_use]
796    pub fn get_performance_stats_portfolio_returns(&self) -> AHashMap<String, f64> {
797        self.calculate_returns_stats(self.portfolio_returns())
798    }
799
800    /// Gets all benchmark-relative return statistics for the primary returns.
801    ///
802    /// This is stateless: the `benchmark` series is supplied by the caller rather
803    /// than stored on the analyzer. Only statistics that override
804    /// [`PortfolioStatistic::calculate_from_returns_with_benchmark`] (the benchmark-relative
805    /// statistics) contribute values; all others return `None` and are skipped.
806    #[must_use]
807    pub fn get_performance_stats_returns_vs_benchmark(
808        &self,
809        benchmark: &Returns,
810    ) -> AHashMap<String, f64> {
811        let mut output = AHashMap::new();
812
813        for (name, stat) in &self.statistics {
814            if let Some(value) =
815                stat.calculate_from_returns_with_benchmark(self.returns(), benchmark)
816            {
817                output.insert(name.clone(), value);
818            }
819        }
820
821        output
822    }
823
824    /// Gets general portfolio statistics.
825    #[must_use]
826    pub fn get_performance_stats_general(&self) -> AHashMap<String, f64> {
827        let mut output = AHashMap::new();
828
829        for (name, stat) in &self.statistics {
830            if let Some(value) = stat.calculate_from_positions(&self.positions) {
831                output.insert(name.clone(), value);
832            }
833        }
834
835        output
836    }
837
838    /// Calculates the maximum length of statistic names for formatting.
839    fn get_max_length_name(&self) -> usize {
840        self.statistics.keys().map(String::len).max().unwrap_or(0)
841    }
842
843    fn calculate_returns_stats(&self, returns: &Returns) -> AHashMap<String, f64> {
844        let mut output = AHashMap::new();
845
846        for (name, stat) in &self.statistics {
847            if let Some(value) = stat.calculate_from_returns(returns) {
848                output.insert(name.clone(), value);
849            }
850        }
851
852        output
853    }
854
855    fn format_returns_stats(&self, stats: AHashMap<String, f64>) -> Vec<String> {
856        let max_length = self.get_max_length_name();
857        let mut entries: Vec<_> = stats.into_iter().collect();
858        entries.sort_by(|(a, _), (b, _)| a.cmp(b));
859
860        let mut output = Vec::new();
861
862        for (k, v) in entries {
863            let padding = max_length.saturating_sub(k.len()) + 1;
864            output.push(format!("{}: {}{:.2}", k, " ".repeat(padding), v));
865        }
866
867        output
868    }
869
870    fn sync_returns_alias(&mut self) {
871        if self.portfolio_returns.is_empty() {
872            self.returns = self.position_returns.clone();
873            return;
874        }
875
876        self.returns = self.portfolio_returns.clone();
877    }
878
879    /// Resolves the currency for PnL record queries: the explicit currency when given,
880    /// otherwise the single account-balance currency, otherwise the single currency across
881    /// realized PnL records.
882    ///
883    /// # Errors
884    ///
885    /// Returns an error if the currency is unspecified and cannot be resolved to exactly
886    /// one currency.
887    fn resolve_pnl_currency(&self, currency: Option<&Currency>) -> Result<Currency, &'static str> {
888        match currency {
889            Some(c) => Ok(*c),
890            None if self.account_balances.len() == 1 => {
891                Ok(*self.account_balances.keys().next().expect("len is 1"))
892            }
893            None => {
894                let mut currencies: IndexSet<Currency> =
895                    self.realized_pnls.keys().copied().collect();
896                currencies.extend(self.recorded_realized_pnls.keys().copied());
897                if currencies.len() != 1 {
898                    return Err("Currency must be specified for multi-currency portfolio");
899                }
900
901                Ok(*currencies.first().expect("len is 1"))
902            }
903        }
904    }
905
906    /// Gets formatted PnL statistics as strings.
907    ///
908    /// # Errors
909    ///
910    /// Returns an error if PnL statistics calculation fails.
911    pub fn get_stats_pnls_formatted(
912        &self,
913        currency: Option<&Currency>,
914        unrealized_pnl: Option<&Money>,
915    ) -> Result<Vec<String>, String> {
916        let max_length = self.get_max_length_name();
917        let stats = self.get_performance_stats_pnls(currency, unrealized_pnl)?;
918
919        let mut entries: Vec<_> = stats.into_iter().collect();
920        entries.sort_by(|(a, _), (b, _)| a.cmp(b));
921
922        let mut output = Vec::new();
923
924        for (k, v) in entries {
925            let padding = if max_length > k.len() {
926                max_length - k.len() + 1
927            } else {
928                1
929            };
930            output.push(format!("{}: {}{:.2}", k, " ".repeat(padding), v));
931        }
932
933        Ok(output)
934    }
935
936    /// Gets formatted return statistics as strings.
937    #[must_use]
938    pub fn get_stats_returns_formatted(&self) -> Vec<String> {
939        self.format_returns_stats(self.get_performance_stats_returns())
940    }
941
942    /// Gets formatted position-return statistics as strings.
943    #[must_use]
944    pub fn get_stats_position_returns_formatted(&self) -> Vec<String> {
945        self.format_returns_stats(self.get_performance_stats_position_returns())
946    }
947
948    /// Gets formatted portfolio-return statistics as strings.
949    #[must_use]
950    pub fn get_stats_portfolio_returns_formatted(&self) -> Vec<String> {
951        self.format_returns_stats(self.get_performance_stats_portfolio_returns())
952    }
953
954    /// Gets formatted general statistics as strings.
955    #[must_use]
956    pub fn get_stats_general_formatted(&self) -> Vec<String> {
957        let max_length = self.get_max_length_name();
958        let stats = self.get_performance_stats_general();
959
960        let mut entries: Vec<_> = stats.into_iter().collect();
961        entries.sort_by(|(a, _), (b, _)| a.cmp(b));
962
963        let mut output = Vec::new();
964
965        for (k, v) in entries {
966            let padding = max_length - k.len() + 1;
967            output.push(format!("{}: {}{}", k, " ".repeat(padding), v));
968        }
969
970        output
971    }
972}
973
974fn trade_pnl_value(pnl: &Money) -> f64 {
975    if pnl.currency.precision > MAX_FLOAT_PRECISION {
976        pnl.as_decimal()
977            .to_f64()
978            .expect("Decimal money values fit in f64")
979    } else {
980        pnl.as_f64()
981    }
982}
983
984fn canonical_position_id(position_id: PositionId) -> PositionId {
985    const UUID4_STRING_LEN: usize = 36;
986
987    let value = position_id.as_str();
988    let Some(separator_index) = value.len().checked_sub(UUID4_STRING_LEN + 1) else {
989        return position_id;
990    };
991
992    if separator_index == 0 || value.as_bytes()[separator_index] != b'-' {
993        return position_id;
994    }
995
996    let suffix = &value[separator_index + 1..];
997    if suffix.parse::<UUID4>().is_ok() {
998        PositionId::new(&value[..separator_index])
999    } else {
1000        position_id
1001    }
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use std::sync::Arc;
1007
1008    use ahash::{AHashMap, AHashSet};
1009    use indexmap::IndexMap;
1010    use nautilus_core::{DurationNanos, UUID4, approx_eq, datetime::NANOSECONDS_IN_DAY};
1011    use nautilus_model::{
1012        accounts::{AccountAny, CashAccount},
1013        enums::{AccountType, InstrumentClass, LiquiditySide, OrderSide, PositionSide},
1014        events::{AccountState, OrderFilled, PortfolioSnapshot},
1015        fees::MakerTakerFeeRates,
1016        identifiers::{
1017            AccountId, ClientOrderId,
1018            stubs::{instrument_id_aud_usd_sim, strategy_id_ema_cross, trader_id},
1019        },
1020        instruments::InstrumentAny,
1021        stubs::TestDefault,
1022        types::{AccountBalance, Money, Price, Quantity},
1023    };
1024    use rstest::rstest;
1025
1026    use super::*;
1027    use crate::statistics::beta_ratio::BetaRatio;
1028
1029    /// Mock implementation of `PortfolioStatistic` for testing.
1030    #[derive(Debug)]
1031    struct MockStatistic {
1032        name: String,
1033    }
1034
1035    impl MockStatistic {
1036        fn new(name: &str) -> Self {
1037            Self {
1038                name: name.to_string(),
1039            }
1040        }
1041    }
1042
1043    impl PortfolioStatistic for MockStatistic {
1044        type Item = f64;
1045
1046        fn name(&self) -> String {
1047            self.name.clone()
1048        }
1049
1050        fn calculate_from_realized_pnls(&self, pnls: &[f64]) -> Option<f64> {
1051            Some(pnls.iter().sum())
1052        }
1053
1054        fn calculate_from_returns(&self, returns: &Returns) -> Option<f64> {
1055            Some(returns.values().sum())
1056        }
1057
1058        fn calculate_from_positions(&self, positions: &[Position]) -> Option<f64> {
1059            Some(positions.len() as f64)
1060        }
1061    }
1062
1063    /// Mock implementation returning a fixed value for every input category.
1064    ///
1065    /// Two instances can share a name while differing in value, which makes
1066    /// duplicate-name replacement observable.
1067    #[derive(Debug)]
1068    struct ConstantStatistic {
1069        name: String,
1070        value: f64,
1071    }
1072
1073    impl ConstantStatistic {
1074        fn new(name: &str, value: f64) -> Self {
1075            Self {
1076                name: name.to_string(),
1077                value,
1078            }
1079        }
1080    }
1081
1082    impl PortfolioStatistic for ConstantStatistic {
1083        type Item = f64;
1084
1085        fn name(&self) -> String {
1086            self.name.clone()
1087        }
1088
1089        fn calculate_from_realized_pnls(&self, _pnls: &[f64]) -> Option<f64> {
1090            Some(self.value)
1091        }
1092
1093        fn calculate_from_returns(&self, _returns: &Returns) -> Option<f64> {
1094            Some(self.value)
1095        }
1096
1097        fn calculate_from_positions(&self, _positions: &[Position]) -> Option<f64> {
1098            Some(self.value)
1099        }
1100    }
1101
1102    fn create_mock_position(
1103        id: &str,
1104        realized_pnl: f64,
1105        realized_return: f64,
1106        currency: Currency,
1107    ) -> Position {
1108        Position {
1109            events: Vec::new(),
1110            adjustments: Vec::new(),
1111            replay_events: Vec::new(),
1112            fill_voids: Vec::new(),
1113            trader_id: trader_id(),
1114            strategy_id: strategy_id_ema_cross(),
1115            instrument_id: instrument_id_aud_usd_sim(),
1116            id: PositionId::new(id),
1117            account_id: AccountId::new("test-account"),
1118            opening_order_id: ClientOrderId::test_default(),
1119            closing_order_id: None,
1120            entry: OrderSide::Buy,
1121            side: PositionSide::Flat,
1122            signed_qty: 0.into(),
1123            quantity: Quantity::default(),
1124            peak_qty: Quantity::default(),
1125            price_precision: 2,
1126            size_precision: 2,
1127            multiplier: Quantity::default(),
1128            is_inverse: false,
1129            is_currency_pair: true,
1130            instrument_class: InstrumentClass::Spot,
1131            base_currency: None,
1132            quote_currency: Currency::USD(),
1133            settlement_currency: Currency::USD(),
1134            ts_init: UnixNanos::default(),
1135            ts_opened: UnixNanos::default(),
1136            ts_last: UnixNanos::default(),
1137            ts_closed: Some(UnixNanos::from(1_706_659_200_000_000_000)),
1138            duration_ns: DurationNanos::new(2),
1139            avg_px_open: 0.into(),
1140            avg_px_close: None,
1141            realized_return,
1142            realized_pnl: Some(Money::new(realized_pnl, currency)),
1143            trade_ids: AHashSet::new(),
1144            buy_qty: Quantity::default(),
1145            sell_qty: Quantity::default(),
1146            commissions: IndexMap::new(),
1147            cost_open: 0.into(),
1148            cost_close: 0.into(),
1149            qty_closed: 0.into(),
1150            realized_pnl_remainder: 0.into(),
1151            allows_negative_price: Some(false),
1152        }
1153    }
1154
1155    struct MockAccount {
1156        starting_balances: AHashMap<Currency, Money>,
1157        current_balances: AHashMap<Currency, Money>,
1158        events: Vec<AccountState>,
1159    }
1160
1161    impl Account for MockAccount {
1162        fn starting_balances(&self) -> IndexMap<Currency, Money> {
1163            self.starting_balances.clone().into_iter().collect()
1164        }
1165        fn balances_total(&self) -> IndexMap<Currency, Money> {
1166            self.current_balances.clone().into_iter().collect()
1167        }
1168        fn id(&self) -> AccountId {
1169            todo!()
1170        }
1171        fn account_type(&self) -> AccountType {
1172            todo!()
1173        }
1174        fn base_currency(&self) -> Option<Currency> {
1175            todo!()
1176        }
1177        fn is_cash_account(&self) -> bool {
1178            todo!()
1179        }
1180        fn is_margin_account(&self) -> bool {
1181            todo!()
1182        }
1183        fn calculated_account_state(&self) -> bool {
1184            todo!()
1185        }
1186        fn balance_total(&self, _: Option<Currency>) -> Option<Money> {
1187            todo!()
1188        }
1189        fn balance_free(&self, _: Option<Currency>) -> Option<Money> {
1190            todo!()
1191        }
1192        fn balances_free(&self) -> IndexMap<Currency, Money> {
1193            todo!()
1194        }
1195        fn balance_locked(&self, _: Option<Currency>) -> Option<Money> {
1196            todo!()
1197        }
1198        fn balances_locked(&self) -> IndexMap<Currency, Money> {
1199            todo!()
1200        }
1201        fn last_event(&self) -> Option<AccountState> {
1202            self.events.last().cloned()
1203        }
1204        fn events(&self) -> Vec<AccountState> {
1205            self.events.clone()
1206        }
1207        fn event_count(&self) -> usize {
1208            self.events.len()
1209        }
1210        fn currencies(&self) -> Vec<Currency> {
1211            self.current_balances.keys().copied().collect()
1212        }
1213        fn balances(&self) -> IndexMap<Currency, AccountBalance> {
1214            todo!()
1215        }
1216        fn apply(&mut self, _: AccountState) -> anyhow::Result<()> {
1217            todo!()
1218        }
1219        fn calculate_balance_locked(
1220            &self,
1221            _: &InstrumentAny,
1222            _: OrderSide,
1223            _: Quantity,
1224            _: Price,
1225            _: Option<bool>,
1226        ) -> Result<Money, anyhow::Error> {
1227            todo!()
1228        }
1229        fn calculate_pnls(
1230            &self,
1231            _: &InstrumentAny,
1232            _: &OrderFilled,
1233            _: Option<Position>,
1234        ) -> Result<Vec<Money>, anyhow::Error> {
1235            todo!()
1236        }
1237        fn calculate_commission(
1238            &self,
1239            _: &InstrumentAny,
1240            _: Quantity,
1241            _: Price,
1242            _: LiquiditySide,
1243            _: MakerTakerFeeRates,
1244            _: Option<bool>,
1245        ) -> Result<Money, anyhow::Error> {
1246            todo!()
1247        }
1248
1249        fn balance(&self, _: Option<Currency>) -> Option<&AccountBalance> {
1250            todo!()
1251        }
1252
1253        fn purge_account_events(&mut self, _: UnixNanos, _: u64) {
1254            // MockAccount doesn't need purging
1255        }
1256    }
1257
1258    fn create_account_state(total: f64, currency: Currency, ts_event: u64) -> AccountState {
1259        AccountState::new(
1260            AccountId::new("test-account"),
1261            AccountType::Cash,
1262            vec![AccountBalance::new(
1263                Money::new(total, currency),
1264                Money::new(0.0, currency),
1265                Money::new(total, currency),
1266            )],
1267            vec![],
1268            true,
1269            UUID4::new(),
1270            UnixNanos::from(ts_event),
1271            UnixNanos::from(ts_event),
1272            Some(currency),
1273        )
1274    }
1275
1276    fn create_portfolio_snapshot(
1277        account_id: AccountId,
1278        equity: Decimal,
1279        currency: Currency,
1280        ts_event: u64,
1281    ) -> PortfolioSnapshot {
1282        let equity = Money::from_decimal(equity, currency).unwrap();
1283
1284        PortfolioSnapshot::new(
1285            account_id,
1286            AccountType::Cash,
1287            Some(currency),
1288            vec![],
1289            vec![],
1290            vec![],
1291            vec![],
1292            vec![equity],
1293            Some(equity),
1294            false,
1295            vec![],
1296            vec![],
1297            vec![],
1298            UUID4::new(),
1299            UnixNanos::from(ts_event),
1300            UnixNanos::from(ts_event),
1301        )
1302    }
1303
1304    #[rstest]
1305    fn test_calculate_snapshot_returns_tracks_daily_mark_to_market_equity() {
1306        let account_id = AccountId::new("SIM-001");
1307        let currency = Currency::USD();
1308        let snapshots = [
1309            create_portfolio_snapshot(
1310                account_id,
1311                Decimal::from(10_000),
1312                currency,
1313                NANOSECONDS_IN_DAY + NANOSECONDS_IN_DAY / 2,
1314            ),
1315            create_portfolio_snapshot(
1316                account_id,
1317                Decimal::from(10_500),
1318                currency,
1319                NANOSECONDS_IN_DAY + 3 * NANOSECONDS_IN_DAY / 4,
1320            ),
1321            create_portfolio_snapshot(
1322                account_id,
1323                Decimal::from(11_000),
1324                currency,
1325                2 * NANOSECONDS_IN_DAY,
1326            ),
1327            create_portfolio_snapshot(
1328                account_id,
1329                Decimal::from(12_100),
1330                currency,
1331                3 * NANOSECONDS_IN_DAY,
1332            ),
1333        ];
1334
1335        let returns =
1336            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1337        let values: Vec<f64> = returns.values().copied().collect();
1338        let dates: Vec<UnixNanos> = returns.keys().copied().collect();
1339
1340        assert_eq!(
1341            dates,
1342            vec![
1343                UnixNanos::from(NANOSECONDS_IN_DAY),
1344                UnixNanos::from(2 * NANOSECONDS_IN_DAY),
1345            ]
1346        );
1347        assert_eq!(values.len(), 2);
1348        assert!(approx_eq!(f64, values[0], 0.1, epsilon = 1e-12));
1349        assert!(approx_eq!(f64, values[1], 0.1, epsilon = 1e-12));
1350    }
1351
1352    #[rstest]
1353    fn test_calculate_snapshot_returns_aggregates_accounts_in_one_currency() {
1354        let account_a = AccountId::new("SIM-001");
1355        let account_b = AccountId::new("SIM-002");
1356        let currency = Currency::USD();
1357        let snapshots = [
1358            create_portfolio_snapshot(account_a, Decimal::from(100), currency, NANOSECONDS_IN_DAY),
1359            create_portfolio_snapshot(account_b, Decimal::from(50), currency, NANOSECONDS_IN_DAY),
1360            create_portfolio_snapshot(
1361                account_a,
1362                Decimal::from(110),
1363                currency,
1364                2 * NANOSECONDS_IN_DAY,
1365            ),
1366        ];
1367
1368        let returns = PortfolioAnalyzer::calculate_snapshot_returns(
1369            &[account_a, account_b],
1370            snapshots.iter(),
1371        )
1372        .unwrap();
1373
1374        assert!(approx_eq!(
1375            f64,
1376            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1377            160.0 / 150.0 - 1.0,
1378            epsilon = 1e-12
1379        ));
1380    }
1381
1382    #[rstest]
1383    fn test_calculate_snapshot_returns_uses_single_total_without_base_currency() {
1384        let account_id = AccountId::new("SIM-001");
1385        let currency = Currency::USD();
1386        let mut first =
1387            create_portfolio_snapshot(account_id, Decimal::from(100), currency, NANOSECONDS_IN_DAY);
1388        let mut second = create_portfolio_snapshot(
1389            account_id,
1390            Decimal::from(110),
1391            currency,
1392            2 * NANOSECONDS_IN_DAY,
1393        );
1394        first.base_currency_equity = None;
1395        second.base_currency_equity = None;
1396        let snapshots = [first, second];
1397
1398        let returns =
1399            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1400
1401        assert!(approx_eq!(
1402            f64,
1403            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1404            0.1,
1405            epsilon = 1e-12
1406        ));
1407    }
1408
1409    #[rstest]
1410    fn test_calculate_snapshot_returns_rejects_multi_currency_total_with_base_equity() {
1411        let account_id = AccountId::new("SIM-001");
1412        let mut first = create_portfolio_snapshot(
1413            account_id,
1414            Decimal::from(100),
1415            Currency::USD(),
1416            NANOSECONDS_IN_DAY,
1417        );
1418        let mut second = create_portfolio_snapshot(
1419            account_id,
1420            Decimal::from(110),
1421            Currency::USD(),
1422            2 * NANOSECONDS_IN_DAY,
1423        );
1424        first.total_equity.push(Money::new(50.0, Currency::AUD()));
1425        second.total_equity.push(Money::new(55.0, Currency::AUD()));
1426        let snapshots = [first, second];
1427
1428        let returns =
1429            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter());
1430
1431        assert!(returns.is_none());
1432    }
1433
1434    #[rstest]
1435    fn test_calculate_snapshot_returns_forward_fills_unpriced_dates() {
1436        let account_id = AccountId::new("SIM-001");
1437        let currency = Currency::USD();
1438        let first =
1439            create_portfolio_snapshot(account_id, Decimal::from(100), currency, NANOSECONDS_IN_DAY);
1440        let mut unpriced =
1441            create_portfolio_snapshot(account_id, Decimal::ZERO, currency, 2 * NANOSECONDS_IN_DAY);
1442        unpriced.unpriced_instruments = vec![instrument_id_aud_usd_sim()];
1443        let last = create_portfolio_snapshot(
1444            account_id,
1445            Decimal::from(110),
1446            currency,
1447            3 * NANOSECONDS_IN_DAY,
1448        );
1449        let snapshots = [first, unpriced, last];
1450
1451        let returns =
1452            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1453
1454        assert!(approx_eq!(
1455            f64,
1456            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1457            0.0,
1458            epsilon = 1e-12
1459        ));
1460        assert!(approx_eq!(
1461            f64,
1462            returns[&UnixNanos::from(2 * NANOSECONDS_IN_DAY)],
1463            0.1,
1464            epsilon = 1e-12
1465        ));
1466    }
1467
1468    #[rstest]
1469    fn test_calculate_snapshot_returns_rejects_mixed_account_currencies() {
1470        let account_a = AccountId::new("SIM-001");
1471        let account_b = AccountId::new("SIM-002");
1472        let snapshots = [
1473            create_portfolio_snapshot(
1474                account_a,
1475                Decimal::from(100),
1476                Currency::USD(),
1477                NANOSECONDS_IN_DAY,
1478            ),
1479            create_portfolio_snapshot(
1480                account_b,
1481                Decimal::from(100),
1482                Currency::AUD(),
1483                NANOSECONDS_IN_DAY,
1484            ),
1485        ];
1486
1487        let returns = PortfolioAnalyzer::calculate_snapshot_returns(
1488            &[account_a, account_b],
1489            snapshots.iter(),
1490        );
1491
1492        assert!(returns.is_none());
1493    }
1494
1495    #[rstest]
1496    fn test_register_and_deregister_statistics() {
1497        let mut analyzer = PortfolioAnalyzer::new();
1498        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1499            Arc::new(MockStatistic::new("test_stat"));
1500
1501        // Test registration
1502        analyzer.register_statistic(Arc::clone(&stat));
1503        assert!(analyzer.statistic("test_stat").is_some());
1504
1505        // Test deregistration
1506        analyzer.deregister_statistic(&stat);
1507        assert!(analyzer.statistic("test_stat").is_none());
1508
1509        // Test deregister all
1510        let stat1: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1511            Arc::new(MockStatistic::new("stat1"));
1512        let stat2: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1513            Arc::new(MockStatistic::new("stat2"));
1514        analyzer.register_statistic(Arc::clone(&stat1));
1515        analyzer.register_statistic(Arc::clone(&stat2));
1516        analyzer.deregister_statistics();
1517        assert!(analyzer.statistics.is_empty());
1518    }
1519
1520    #[rstest]
1521    fn test_register_statistic_replaces_matching_name() {
1522        let mut analyzer = PortfolioAnalyzer::new();
1523        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 1.0)));
1524        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 2.0)));
1525
1526        let stats = analyzer.get_performance_stats_general();
1527
1528        assert_eq!(analyzer.statistics.len(), 1);
1529        assert_eq!(stats["Custom"], 2.0);
1530    }
1531
1532    #[rstest]
1533    fn test_pnl_statistics_reject_unresolved_currency() {
1534        // Two currencies and no account balances: the currency cannot be resolved, so
1535        // dispatching on an empty slice would report a result that ignores both trades.
1536        let mut analyzer = PortfolioAnalyzer::new();
1537        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 1.0)));
1538        analyzer.add_trade(
1539            &PositionId::new("P-USD"),
1540            UnixNanos::from(1),
1541            &Money::new(10.0, Currency::USD()),
1542        );
1543        analyzer.add_trade(
1544            &PositionId::new("P-EUR"),
1545            UnixNanos::from(2),
1546            &Money::new(5.0, Currency::EUR()),
1547        );
1548
1549        let result = analyzer.get_performance_stats_pnls(None, None);
1550
1551        assert_eq!(
1552            result,
1553            Err("Currency must be specified for multi-currency portfolio")
1554        );
1555    }
1556
1557    #[rstest]
1558    fn test_pnl_statistics_resolve_single_pnl_currency() {
1559        // One realized-PnL currency and no explicit currency: resolution falls back to that
1560        // currency, so statistics dispatch on its records.
1561        let mut analyzer = PortfolioAnalyzer::new();
1562        analyzer.register_statistic(Arc::new(MockStatistic::new("test_stat")));
1563        let currency = Currency::USD();
1564        let position_id = PositionId::new("P-USD");
1565        analyzer.add_trade(
1566            &position_id,
1567            UnixNanos::from(1),
1568            &Money::new(10.0, currency),
1569        );
1570
1571        let records = analyzer.trade_pnl_records(None).unwrap();
1572        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1573
1574        assert_eq!(records, vec![(position_id, UnixNanos::from(1), 10.0)]);
1575        assert_eq!(stats["test_stat"], 10.0);
1576    }
1577
1578    #[rstest]
1579    fn test_pnl_statistics_prefer_account_balance_currency() {
1580        // A single account-balance currency resolves the query even when the realized-PnL
1581        // records are in another currency: the balance currency wins, has no records, and
1582        // statistics dispatch on an empty slice instead of erroring.
1583        let mut analyzer = PortfolioAnalyzer::new();
1584        analyzer.register_statistic(Arc::new(MockStatistic::new("test_stat")));
1585        let currency = Currency::USD();
1586        analyzer
1587            .account_balances
1588            .insert(currency, Money::new(1000.0, currency));
1589        analyzer.add_trade(
1590            &PositionId::new("P-EUR"),
1591            UnixNanos::from(1),
1592            &Money::new(5.0, Currency::EUR()),
1593        );
1594
1595        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1596
1597        assert!(analyzer.trade_pnl_records(None).is_none());
1598        assert_eq!(stats["test_stat"], 0.0);
1599    }
1600
1601    #[rstest]
1602    fn test_trade_pnl_records_sorted_by_event_time() {
1603        // A recorded PnL at t=1 and an unmatched position-derived PnL at t=2 are merged from
1604        // two sources; without sorting the derived record leads and the sequence reads [t2, t1].
1605        let currency = Currency::USD();
1606        let mut analyzer = PortfolioAnalyzer::new();
1607        analyzer.add_trade(
1608            &PositionId::new("P-LATE"),
1609            UnixNanos::from(2),
1610            &Money::new(5.0, currency),
1611        );
1612        analyzer.record_trade(
1613            &PositionId::new("P-EARLY"),
1614            UnixNanos::from(1),
1615            &Money::new(7.0, currency),
1616        );
1617
1618        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1619
1620        assert_eq!(
1621            records,
1622            vec![
1623                (PositionId::new("P-EARLY"), UnixNanos::from(1), 7.0),
1624                (PositionId::new("P-LATE"), UnixNanos::from(2), 5.0),
1625            ]
1626        );
1627    }
1628
1629    #[rstest]
1630    fn test_pnl_statistics_run_without_any_trades() {
1631        // No realized PnLs at all: registered statistics still receive an empty slice, so a
1632        // statistic defined for empty input reports its value instead of vanishing.
1633        let mut analyzer = PortfolioAnalyzer::new();
1634        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 0.0)));
1635
1636        let stats = analyzer
1637            .get_performance_stats_pnls(Some(&Currency::USD()), None)
1638            .unwrap();
1639
1640        assert_eq!(stats["Custom"], 0.0);
1641        assert_eq!(stats["PnL (total)"], 0.0);
1642    }
1643
1644    #[rstest]
1645    fn test_pnl_statistics_run_without_any_trades_or_currency() {
1646        // No realized PnLs and no explicit currency: with nothing to resolve, statistics
1647        // still receive an empty slice instead of erroring.
1648        let mut analyzer = PortfolioAnalyzer::new();
1649        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 0.0)));
1650
1651        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1652
1653        assert_eq!(stats["Custom"], 0.0);
1654        assert_eq!(stats["PnL (total)"], 0.0);
1655    }
1656
1657    #[rstest]
1658    fn test_reset_retains_registered_statistics() {
1659        let currency = Currency::USD();
1660        let mut analyzer = PortfolioAnalyzer::new();
1661        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 7.5)));
1662        analyzer.add_positions(&[create_mock_position("AUD/USD", 100.0, 0.1, currency)]);
1663
1664        analyzer.reset();
1665
1666        assert!(analyzer.positions.is_empty());
1667        assert_eq!(analyzer.statistics.len(), 1);
1668        assert_eq!(analyzer.get_performance_stats_general()["Custom"], 7.5);
1669    }
1670
1671    #[rstest]
1672    fn test_formatted_general_stats_include_custom_statistic() {
1673        // The post-run analysis log formats from this same method, so a registered
1674        // custom statistic must appear alongside the built-in defaults.
1675        let mut analyzer = PortfolioAnalyzer::new();
1676        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 12.5)));
1677
1678        let lines = analyzer.get_stats_general_formatted();
1679
1680        assert_eq!(lines, vec!["Custom:  12.5".to_string()]);
1681    }
1682
1683    #[rstest]
1684    fn test_replace_statistics_adopts_given_set() {
1685        let mut analyzer = PortfolioAnalyzer::default();
1686        let default_count = analyzer.statistics.len();
1687
1688        let mut replacement: AHashMap<String, Statistic> = AHashMap::new();
1689        replacement.insert(
1690            "Custom".to_string(),
1691            Arc::new(ConstantStatistic::new("Custom", 3.25)),
1692        );
1693        analyzer.replace_statistics(replacement);
1694
1695        let stats = analyzer.get_performance_stats_general();
1696
1697        assert!(default_count > 1);
1698        assert_eq!(analyzer.statistics.len(), 1);
1699        assert_eq!(stats.len(), 1);
1700        assert_eq!(stats["Custom"], 3.25);
1701    }
1702
1703    #[rstest]
1704    fn test_calculate_total_pnl() {
1705        let mut analyzer = PortfolioAnalyzer::new();
1706        let currency = Currency::USD();
1707
1708        // Set up mock account data
1709        let mut starting_balances = AHashMap::new();
1710        starting_balances.insert(currency, Money::new(1000.0, currency));
1711
1712        let mut current_balances = AHashMap::new();
1713        current_balances.insert(currency, Money::new(1500.0, currency));
1714
1715        let account = MockAccount {
1716            starting_balances,
1717            current_balances,
1718            events: vec![],
1719        };
1720
1721        analyzer.calculate_statistics(&account, &[]);
1722
1723        // Test total PnL calculation
1724        let result = analyzer.total_pnl(Some(&currency), None).unwrap();
1725        assert!(approx_eq!(f64, result, 500.0, epsilon = 1e-9));
1726
1727        // Test with unrealized PnL
1728        let unrealized_pnl = Money::new(100.0, currency);
1729        let result = analyzer
1730            .total_pnl(Some(&currency), Some(&unrealized_pnl))
1731            .unwrap();
1732        assert!(approx_eq!(f64, result, 600.0, epsilon = 1e-9));
1733    }
1734
1735    #[rstest]
1736    fn test_calculate_total_pnl_percentage() {
1737        let mut analyzer = PortfolioAnalyzer::new();
1738        let currency = Currency::USD();
1739
1740        // Set up mock account data
1741        let mut starting_balances = AHashMap::new();
1742        starting_balances.insert(currency, Money::new(1000.0, currency));
1743
1744        let mut current_balances = AHashMap::new();
1745        current_balances.insert(currency, Money::new(1500.0, currency));
1746
1747        let account = MockAccount {
1748            starting_balances,
1749            current_balances,
1750            events: vec![],
1751        };
1752
1753        analyzer.calculate_statistics(&account, &[]);
1754
1755        // Test percentage calculation
1756        let result = analyzer
1757            .total_pnl_percentage(Some(&currency), None)
1758            .unwrap();
1759        assert!(approx_eq!(f64, result, 50.0, epsilon = 1e-9)); // (1500 - 1000) / 1000 * 100
1760
1761        // Test with unrealized PnL
1762        let unrealized_pnl = Money::new(500.0, currency);
1763        let result = analyzer
1764            .total_pnl_percentage(Some(&currency), Some(&unrealized_pnl))
1765            .unwrap();
1766        assert!(approx_eq!(f64, result, 100.0, epsilon = 1e-9)); // (2000 - 1000) / 1000 * 100
1767    }
1768
1769    #[rstest]
1770    fn test_add_positions_and_returns() {
1771        let mut analyzer = PortfolioAnalyzer::new();
1772        let currency = Currency::USD();
1773
1774        let positions = vec![
1775            create_mock_position("AUD/USD", 100.0, 0.1, currency),
1776            create_mock_position("AUD/USD", 200.0, 0.2, currency),
1777        ];
1778
1779        analyzer.add_positions(&positions);
1780
1781        // Verify realized PnLs were recorded
1782        let pnls = analyzer.realized_pnls(Some(&currency)).unwrap();
1783        assert_eq!(pnls.len(), 2);
1784        assert!(approx_eq!(f64, pnls[0].2, 100.0, epsilon = 1e-9));
1785        assert!(approx_eq!(f64, pnls[1].2, 200.0, epsilon = 1e-9));
1786
1787        // Verify returns were recorded
1788        let returns = analyzer.returns();
1789        let position_returns = analyzer.position_returns();
1790        assert_eq!(returns.len(), 1);
1791        assert_eq!(position_returns.len(), 1);
1792        assert!(analyzer.portfolio_returns().is_empty());
1793        assert!(approx_eq!(
1794            f64,
1795            *returns.values().next().unwrap(),
1796            0.30000000000000004,
1797            epsilon = 1e-9
1798        ));
1799        assert!(approx_eq!(
1800            f64,
1801            *position_returns.values().next().unwrap(),
1802            0.30000000000000004,
1803            epsilon = 1e-9
1804        ));
1805    }
1806
1807    #[rstest]
1808    fn test_add_positions_skips_position_returns_without_real_close_timestamp() {
1809        let mut analyzer = PortfolioAnalyzer::new();
1810        let currency = Currency::USD();
1811        let mut position = create_mock_position("AUD/USD", 100.0, 0.1, currency);
1812        position.ts_closed = Some(UnixNanos::default());
1813
1814        analyzer.add_positions(&[position]);
1815
1816        assert!(analyzer.position_returns().is_empty());
1817        assert!(analyzer.returns().is_empty());
1818    }
1819
1820    #[rstest]
1821    fn test_add_positions_records_open_position_realized_pnl() {
1822        let mut analyzer = PortfolioAnalyzer::new();
1823        let currency = Currency::USD();
1824        let mut position = create_mock_position("AUD/USD", 100.0, 0.1, currency);
1825        position.ts_closed = None;
1826        // Distinct from ts_opened (default 0) so the record is keyed by the last event time.
1827        position.ts_last = UnixNanos::from(7);
1828        let position_id = position.id;
1829
1830        analyzer.add_positions(&[position]);
1831
1832        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1833        assert_eq!(records.len(), 1);
1834        assert_eq!(records[0], (position_id, UnixNanos::from(7), 100.0));
1835        assert!(analyzer.position_returns().is_empty());
1836    }
1837
1838    #[rstest]
1839    fn test_trade_pnl_records_keeps_unrecorded_native_cycle() {
1840        // A NETTING id with two native cycles where only the later cycle was recorded:
1841        // the earlier native cycle must survive rather than be dropped by position ID.
1842        let mut analyzer = PortfolioAnalyzer::new();
1843        let currency = Currency::USD();
1844        let position_id = PositionId::new("pos1");
1845
1846        analyzer.add_trade(
1847            &position_id,
1848            UnixNanos::from(1),
1849            &Money::new(10.0, currency),
1850        );
1851        analyzer.add_trade(
1852            &position_id,
1853            UnixNanos::from(2),
1854            &Money::new(20.0, currency),
1855        );
1856        analyzer.record_trade(
1857            &position_id,
1858            UnixNanos::from(2),
1859            &Money::new(25.0, currency),
1860        );
1861
1862        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1863
1864        assert_eq!(
1865            records,
1866            vec![
1867                (position_id, UnixNanos::from(1), 10.0),
1868                (position_id, UnixNanos::from(2), 25.0),
1869            ]
1870        );
1871    }
1872
1873    #[rstest]
1874    fn test_trade_pnl_records_drops_recorded_snapshot_alias() {
1875        let mut analyzer = PortfolioAnalyzer::new();
1876        let currency = Currency::USD();
1877        let position_id = PositionId::new("pos1");
1878        let snapshot_id = PositionId::new(format!("{}-{}", position_id.as_str(), UUID4::new()));
1879        let ts_event = UnixNanos::from(1);
1880
1881        analyzer.add_trade(&snapshot_id, ts_event, &Money::new(10.0, currency));
1882        analyzer.record_trade(&position_id, ts_event, &Money::new(10.0, currency));
1883
1884        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1885
1886        assert_eq!(records, vec![(position_id, ts_event, 10.0)]);
1887    }
1888
1889    #[rstest]
1890    fn test_performance_stats_calculation() {
1891        let mut analyzer = PortfolioAnalyzer::new();
1892        let currency = Currency::USD();
1893        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1894            Arc::new(MockStatistic::new("test_stat"));
1895        analyzer.register_statistic(Arc::clone(&stat));
1896
1897        // Add some positions
1898        let positions = vec![
1899            create_mock_position("AUD/USD", 100.0, 0.1, currency),
1900            create_mock_position("AUD/USD", 200.0, 0.2, currency),
1901        ];
1902
1903        let mut starting_balances = AHashMap::new();
1904        starting_balances.insert(currency, Money::new(1000.0, currency));
1905
1906        let mut current_balances = AHashMap::new();
1907        current_balances.insert(currency, Money::new(1500.0, currency));
1908
1909        let account = MockAccount {
1910            starting_balances,
1911            current_balances,
1912            events: vec![],
1913        };
1914
1915        analyzer.calculate_statistics(&account, &positions);
1916
1917        // Test PnL stats
1918        let pnl_stats = analyzer
1919            .get_performance_stats_pnls(Some(&currency), None)
1920            .unwrap();
1921        assert!(pnl_stats.contains_key("PnL (total)"));
1922        assert!(pnl_stats.contains_key("PnL% (total)"));
1923        assert!(pnl_stats.contains_key("test_stat"));
1924
1925        // Test returns stats
1926        let return_stats = analyzer.get_performance_stats_returns();
1927        assert!(return_stats.contains_key("test_stat"));
1928
1929        // Test general stats
1930        let general_stats = analyzer.get_performance_stats_general();
1931        assert!(general_stats.contains_key("test_stat"));
1932    }
1933
1934    #[rstest]
1935    fn test_calculate_statistics_preserves_recorded_realized_pnls() {
1936        let mut analyzer = PortfolioAnalyzer::new();
1937        let account_currency = Currency::EUR();
1938        let native_currency = Currency::USD();
1939        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1940            Arc::new(MockStatistic::new("test_stat"));
1941        analyzer.register_statistic(Arc::clone(&stat));
1942        analyzer.record_trade(
1943            &PositionId::new("pos1"),
1944            UnixNanos::from(1),
1945            &Money::new(90.0, account_currency),
1946        );
1947
1948        let positions = vec![create_mock_position("pos1", 100.0, 0.1, native_currency)];
1949
1950        let mut starting_balances = AHashMap::new();
1951        starting_balances.insert(account_currency, Money::new(1000.0, account_currency));
1952
1953        let mut current_balances = AHashMap::new();
1954        current_balances.insert(account_currency, Money::new(1100.0, account_currency));
1955
1956        let account = MockAccount {
1957            starting_balances,
1958            current_balances,
1959            events: vec![],
1960        };
1961
1962        analyzer.calculate_statistics(&account, &positions);
1963
1964        let native_pnls = analyzer.realized_pnls(Some(&native_currency)).unwrap();
1965        let recorded_pnls = analyzer.realized_pnls(Some(&account_currency)).unwrap();
1966        let pnl_stats = analyzer
1967            .get_performance_stats_pnls(Some(&account_currency), None)
1968            .unwrap();
1969
1970        assert_eq!(native_pnls[0].2, 100.0);
1971        assert_eq!(recorded_pnls[0].2, 90.0);
1972        assert_eq!(*pnl_stats.get("test_stat").unwrap(), 90.0);
1973    }
1974
1975    #[rstest]
1976    fn test_record_trade_preserves_duplicate_position_ids() {
1977        let mut analyzer = PortfolioAnalyzer::new();
1978        let account_currency = Currency::EUR();
1979        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1980            Arc::new(MockStatistic::new("test_stat"));
1981        let position_id = PositionId::new("pos1");
1982
1983        analyzer.register_statistic(Arc::clone(&stat));
1984        analyzer.record_trade(
1985            &position_id,
1986            UnixNanos::from(1),
1987            &Money::new(90.0, account_currency),
1988        );
1989        analyzer.record_trade(
1990            &position_id,
1991            UnixNanos::from(2),
1992            &Money::new(-45.0, account_currency),
1993        );
1994
1995        let records = analyzer.trade_pnl_records(Some(&account_currency)).unwrap();
1996        let recorded_pnls = analyzer.realized_pnls(Some(&account_currency)).unwrap();
1997        let pnl_stats = analyzer
1998            .get_performance_stats_pnls(Some(&account_currency), None)
1999            .unwrap();
2000
2001        assert_eq!(records[0], (position_id, UnixNanos::from(1), 90.0));
2002        assert_eq!(records[1], (position_id, UnixNanos::from(2), -45.0));
2003        assert_eq!(
2004            recorded_pnls,
2005            vec![
2006                (position_id, UnixNanos::from(1), 90.0),
2007                (position_id, UnixNanos::from(2), -45.0),
2008            ]
2009        );
2010        assert_eq!(*pnl_stats.get("test_stat").unwrap(), 45.0);
2011    }
2012    #[rstest]
2013    fn test_formatted_output() {
2014        let mut analyzer = PortfolioAnalyzer::new();
2015        let currency = Currency::USD();
2016        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
2017            Arc::new(MockStatistic::new("test_stat"));
2018        analyzer.register_statistic(Arc::clone(&stat));
2019
2020        let positions = vec![
2021            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2022            create_mock_position("AUD/USD", 200.0, 0.2, currency),
2023        ];
2024
2025        let mut starting_balances = AHashMap::new();
2026        starting_balances.insert(currency, Money::new(1000.0, currency));
2027
2028        let mut current_balances = AHashMap::new();
2029        current_balances.insert(currency, Money::new(1500.0, currency));
2030
2031        let account = MockAccount {
2032            starting_balances,
2033            current_balances,
2034            events: vec![],
2035        };
2036
2037        analyzer.calculate_statistics(&account, &positions);
2038
2039        // Test formatted outputs
2040        let pnl_formatted = analyzer
2041            .get_stats_pnls_formatted(Some(&currency), None)
2042            .unwrap();
2043        assert!(!pnl_formatted.is_empty());
2044        assert!(pnl_formatted.iter().all(|s| s.contains(':')));
2045
2046        let returns_formatted = analyzer.get_stats_returns_formatted();
2047        assert!(!returns_formatted.is_empty());
2048        assert!(returns_formatted.iter().all(|s| s.contains(':')));
2049
2050        let general_formatted = analyzer.get_stats_general_formatted();
2051        assert!(!general_formatted.is_empty());
2052        assert!(general_formatted.iter().all(|s| s.contains(':')));
2053    }
2054
2055    #[rstest]
2056    fn test_reset() {
2057        let mut analyzer = PortfolioAnalyzer::new();
2058        let currency = Currency::USD();
2059
2060        let positions = vec![create_mock_position("AUD/USD", 100.0, 0.1, currency)];
2061        let mut starting_balances = AHashMap::new();
2062        starting_balances.insert(currency, Money::new(1000.0, currency));
2063        let mut current_balances = AHashMap::new();
2064        current_balances.insert(currency, Money::new(1500.0, currency));
2065
2066        let account = MockAccount {
2067            starting_balances,
2068            current_balances,
2069            events: vec![],
2070        };
2071
2072        analyzer.calculate_statistics(&account, &positions);
2073
2074        analyzer.reset();
2075
2076        assert!(analyzer.account_balances_starting.is_empty());
2077        assert!(analyzer.account_balances.is_empty());
2078        assert!(analyzer.positions.is_empty());
2079        assert!(analyzer.realized_pnls.is_empty());
2080        assert!(analyzer.recorded_realized_pnls.is_empty());
2081        assert!(analyzer.position_returns.is_empty());
2082        assert!(analyzer.portfolio_returns.is_empty());
2083        assert!(analyzer.returns.is_empty());
2084    }
2085
2086    #[rstest]
2087    fn test_currencies_preserve_account_balance_order() {
2088        // Pin IndexMap iteration on PortfolioAnalyzer::account_balances:
2089        // currencies() drives the per-currency stat computation in
2090        // BacktestEngine::run, so the returned Vec must reflect the
2091        // upstream account balance order across runs.
2092        let mut analyzer = PortfolioAnalyzer::new();
2093        let inserts = [
2094            (Currency::BTC(), Money::new(1.0, Currency::BTC())),
2095            (Currency::USD(), Money::new(2.0, Currency::USD())),
2096            (Currency::ETH(), Money::new(3.0, Currency::ETH())),
2097        ];
2098
2099        for (currency, money) in inserts {
2100            analyzer.account_balances.insert(currency, money);
2101        }
2102
2103        let returned: Vec<Currency> = analyzer.currencies().into_iter().copied().collect();
2104        assert_eq!(
2105            returned,
2106            vec![Currency::BTC(), Currency::USD(), Currency::ETH()],
2107        );
2108    }
2109
2110    #[rstest]
2111    fn test_calculate_statistics_clears_previous_positions() {
2112        let mut analyzer = PortfolioAnalyzer::new();
2113        let currency = Currency::USD();
2114
2115        let positions1 = vec![create_mock_position("pos1", 100.0, 0.1, currency)];
2116        let positions2 = vec![create_mock_position("pos2", 200.0, 0.2, currency)];
2117
2118        let mut starting_balances = AHashMap::new();
2119        starting_balances.insert(currency, Money::new(1000.0, currency));
2120        let mut current_balances = AHashMap::new();
2121        current_balances.insert(currency, Money::new(1500.0, currency));
2122
2123        let account = MockAccount {
2124            starting_balances,
2125            current_balances,
2126            events: vec![],
2127        };
2128
2129        // First calculation
2130        analyzer.calculate_statistics(&account, &positions1);
2131        assert_eq!(analyzer.positions.len(), 1);
2132
2133        // Second calculation should NOT accumulate
2134        analyzer.calculate_statistics(&account, &positions2);
2135        assert_eq!(analyzer.positions.len(), 1);
2136    }
2137
2138    #[rstest]
2139    fn test_calculate_statistics_uses_account_state_returns_when_available() {
2140        let mut analyzer = PortfolioAnalyzer::new();
2141        let currency = Currency::USD();
2142        let positions = vec![
2143            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2144            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2145        ];
2146
2147        let mut starting_balances = AHashMap::new();
2148        starting_balances.insert(currency, Money::new(1000.0, currency));
2149
2150        let mut current_balances = AHashMap::new();
2151        current_balances.insert(currency, Money::new(1100.0, currency));
2152
2153        let account = MockAccount {
2154            starting_balances,
2155            current_balances,
2156            events: vec![
2157                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2158                create_account_state(1050.0, currency, 1_704_844_800_000_000_000),
2159                create_account_state(1100.0, currency, 1_706_659_200_000_000_000),
2160            ],
2161        };
2162
2163        analyzer.calculate_statistics(&account, &positions);
2164
2165        let position_returns = analyzer.position_returns();
2166        let portfolio_returns = analyzer.portfolio_returns();
2167        let returns = analyzer.returns();
2168        assert_eq!(position_returns.len(), 1);
2169        assert_eq!(portfolio_returns.len(), 30);
2170        assert_eq!(returns, portfolio_returns);
2171        assert!(approx_eq!(
2172            f64,
2173            *portfolio_returns
2174                .get(&UnixNanos::from(1_704_153_600_000_000_000))
2175                .unwrap(),
2176            0.0,
2177            epsilon = 1e-9
2178        ));
2179        assert!(approx_eq!(
2180            f64,
2181            *portfolio_returns
2182                .get(&UnixNanos::from(1_704_844_800_000_000_000))
2183                .unwrap(),
2184            0.05,
2185            epsilon = 1e-9
2186        ));
2187        assert!(approx_eq!(
2188            f64,
2189            *portfolio_returns
2190                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2191                .unwrap(),
2192            (1100.0 / 1050.0) - 1.0,
2193            epsilon = 1e-9
2194        ));
2195        assert!(approx_eq!(
2196            f64,
2197            *position_returns.values().next().unwrap(),
2198            0.30000000000000004,
2199            epsilon = 1e-9
2200        ));
2201    }
2202
2203    #[rstest]
2204    fn test_calculate_statistics_skips_empty_balance_events() {
2205        let mut analyzer = PortfolioAnalyzer::new();
2206        let currency = Currency::USD();
2207        let mut starting_balances = AHashMap::new();
2208        starting_balances.insert(currency, Money::new(1000.0, currency));
2209        let mut current_balances = AHashMap::new();
2210        current_balances.insert(currency, Money::new(1050.0, currency));
2211        let empty_event = AccountState::new(
2212            AccountId::new("test-account"),
2213            AccountType::Cash,
2214            vec![],
2215            vec![],
2216            true,
2217            UUID4::new(),
2218            UnixNanos::from(1_705_276_800_000_000_000),
2219            UnixNanos::from(1_705_276_800_000_000_000),
2220            Some(currency),
2221        );
2222        let account = MockAccount {
2223            starting_balances,
2224            current_balances,
2225            events: vec![
2226                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2227                empty_event,
2228                create_account_state(1050.0, currency, 1_706_659_200_000_000_000),
2229            ],
2230        };
2231
2232        analyzer.calculate_statistics(&account, &[]);
2233
2234        let portfolio_returns = analyzer.portfolio_returns();
2235        assert_eq!(portfolio_returns.len(), 30);
2236        assert_eq!(analyzer.returns(), portfolio_returns);
2237        assert!(approx_eq!(
2238            f64,
2239            *portfolio_returns
2240                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2241                .unwrap(),
2242            0.05,
2243            epsilon = 1e-9
2244        ));
2245    }
2246
2247    #[rstest]
2248    fn test_calculate_statistics_skips_non_finite_account_returns() {
2249        let mut analyzer = PortfolioAnalyzer::new();
2250        let currency = Currency::USD();
2251
2252        let mut starting_balances = AHashMap::new();
2253        starting_balances.insert(currency, Money::new(0.0, currency));
2254
2255        let mut current_balances = AHashMap::new();
2256        current_balances.insert(currency, Money::new(1050.0, currency));
2257
2258        let account = MockAccount {
2259            starting_balances,
2260            current_balances,
2261            events: vec![
2262                create_account_state(0.0, currency, 1_704_067_200_000_000_000),
2263                create_account_state(1000.0, currency, 1_704_844_800_000_000_000),
2264                create_account_state(1050.0, currency, 1_706_659_200_000_000_000),
2265            ],
2266        };
2267
2268        analyzer.calculate_statistics(&account, &[]);
2269
2270        let returns = analyzer.returns();
2271        assert!(returns.values().all(|value| value.is_finite()));
2272        assert!(approx_eq!(
2273            f64,
2274            *returns
2275                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2276                .unwrap(),
2277            0.05,
2278            epsilon = 1e-9
2279        ));
2280    }
2281
2282    #[rstest]
2283    fn test_calculate_statistics_falls_back_to_position_returns_without_account_events() {
2284        let mut analyzer = PortfolioAnalyzer::new();
2285        let currency = Currency::USD();
2286        let positions = vec![
2287            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2288            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2289        ];
2290
2291        let mut starting_balances = AHashMap::new();
2292        starting_balances.insert(currency, Money::new(1000.0, currency));
2293
2294        let mut current_balances = AHashMap::new();
2295        current_balances.insert(currency, Money::new(1100.0, currency));
2296
2297        let account = MockAccount {
2298            starting_balances,
2299            current_balances,
2300            events: vec![],
2301        };
2302
2303        analyzer.calculate_statistics(&account, &positions);
2304
2305        let returns = analyzer.returns();
2306        assert!(analyzer.portfolio_returns().is_empty());
2307        assert_eq!(returns, analyzer.position_returns());
2308        assert_eq!(returns.len(), 1);
2309        assert!(approx_eq!(
2310            f64,
2311            *returns.values().next().unwrap(),
2312            0.30000000000000004,
2313            epsilon = 1e-9
2314        ));
2315    }
2316
2317    #[rstest]
2318    fn test_get_performance_stats_returns_prefers_portfolio_returns() {
2319        let mut analyzer = PortfolioAnalyzer::new();
2320        let currency = Currency::USD();
2321        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
2322            Arc::new(MockStatistic::new("test_stat"));
2323        analyzer.register_statistic(Arc::clone(&stat));
2324
2325        let positions = vec![
2326            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2327            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2328        ];
2329
2330        let mut starting_balances = AHashMap::new();
2331        starting_balances.insert(currency, Money::new(1000.0, currency));
2332
2333        let mut current_balances = AHashMap::new();
2334        current_balances.insert(currency, Money::new(1100.0, currency));
2335
2336        let account = MockAccount {
2337            starting_balances,
2338            current_balances,
2339            events: vec![
2340                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2341                create_account_state(1050.0, currency, 1_704_844_800_000_000_000),
2342                create_account_state(1100.0, currency, 1_706_659_200_000_000_000),
2343            ],
2344        };
2345
2346        analyzer.calculate_statistics(&account, &positions);
2347
2348        let position_stats = analyzer.get_performance_stats_position_returns();
2349        let portfolio_stats = analyzer.get_performance_stats_portfolio_returns();
2350        let returns_stats = analyzer.get_performance_stats_returns();
2351
2352        assert!(approx_eq!(
2353            f64,
2354            *position_stats.get("test_stat").unwrap(),
2355            0.30000000000000004,
2356            epsilon = 1e-9
2357        ));
2358        assert_eq!(returns_stats, portfolio_stats);
2359    }
2360
2361    #[rstest]
2362    fn test_from_accounts_aggregates_balances_and_positions() {
2363        let currency = Currency::USD();
2364        let positions = vec![
2365            create_mock_position("pos1", 100.0, 0.1, currency),
2366            create_mock_position("pos2", 200.0, 0.2, currency),
2367        ];
2368
2369        let analyzer = PortfolioAnalyzer::from_accounts(
2370            &[AccountAny::Cash(CashAccount::default())],
2371            &positions,
2372            &[],
2373            AHashMap::new(),
2374        );
2375
2376        assert_eq!(analyzer.positions.len(), positions.len());
2377        assert!(!analyzer.account_balances.is_empty());
2378    }
2379
2380    #[rstest]
2381    fn test_from_accounts_sums_balances_across_accounts() {
2382        let usd = Currency::USD();
2383        let one = PortfolioAnalyzer::from_accounts(
2384            &[AccountAny::Cash(CashAccount::default())],
2385            &[],
2386            &[],
2387            AHashMap::new(),
2388        );
2389        let two = PortfolioAnalyzer::from_accounts(
2390            &[
2391                AccountAny::Cash(CashAccount::default()),
2392                AccountAny::Cash(CashAccount::default()),
2393            ],
2394            &[],
2395            &[],
2396            AHashMap::new(),
2397        );
2398
2399        let single = one.account_balances.get(&usd).unwrap().as_decimal();
2400        let summed = two.account_balances.get(&usd).unwrap().as_decimal();
2401        let single_start = one
2402            .account_balances_starting
2403            .get(&usd)
2404            .unwrap()
2405            .as_decimal();
2406        let summed_start = two
2407            .account_balances_starting
2408            .get(&usd)
2409            .unwrap()
2410            .as_decimal();
2411
2412        assert_eq!(summed, single + single);
2413        assert_eq!(summed_start, single_start + single_start);
2414        assert_ne!(summed, single);
2415    }
2416
2417    #[rstest]
2418    fn test_statistics_snapshot_matches_getters() {
2419        let currency = Currency::USD();
2420        let positions = vec![
2421            create_mock_position("pos1", 100.0, 0.1, currency),
2422            create_mock_position("pos2", 200.0, 0.2, currency),
2423        ];
2424
2425        let analyzer = PortfolioAnalyzer::from_accounts(
2426            &[AccountAny::Cash(CashAccount::default())],
2427            &positions,
2428            &[],
2429            AHashMap::new(),
2430        );
2431
2432        let snapshot = analyzer.statistics();
2433        assert!(maps_equal_nan_aware(
2434            &snapshot.returns,
2435            &analyzer.get_performance_stats_returns()
2436        ));
2437        assert!(maps_equal_nan_aware(
2438            &snapshot.general,
2439            &analyzer.get_performance_stats_general()
2440        ));
2441        assert_eq!(&snapshot.returns_series, analyzer.returns());
2442
2443        for currency in analyzer.currencies() {
2444            let expected = analyzer
2445                .get_performance_stats_pnls(Some(currency), None)
2446                .unwrap();
2447            let actual = snapshot.pnls.get(&currency.code.to_string()).unwrap();
2448            assert!(maps_equal_nan_aware(actual, &expected));
2449        }
2450    }
2451
2452    fn maps_equal_nan_aware(a: &AHashMap<String, f64>, b: &AHashMap<String, f64>) -> bool {
2453        if a.len() != b.len() {
2454            return false;
2455        }
2456        a.iter().all(|(k, v)| {
2457            b.get(k)
2458                .is_some_and(|bv| (v.is_nan() && bv.is_nan()) || (v == bv))
2459        })
2460    }
2461
2462    #[rstest]
2463    fn test_get_performance_stats_returns_vs_benchmark() {
2464        let mut analyzer = PortfolioAnalyzer::new();
2465        analyzer.register_statistic(Arc::new(BetaRatio::new()));
2466        analyzer.register_statistic(Arc::new(SharpeRatio::new(None)));
2467
2468        let one_day = 86_400_000_000_000_u64;
2469        let start = 1_600_000_000_000_000_000_u64;
2470        for (i, value) in [0.03, -0.01, 0.02, 0.04].iter().enumerate() {
2471            analyzer.add_return(UnixNanos::from(start + i as u64 * one_day), *value);
2472        }
2473
2474        let mut benchmark: Returns = BTreeMap::new();
2475        for (i, value) in [0.01, 0.005, 0.005, 0.01].iter().enumerate() {
2476            benchmark.insert(UnixNanos::from(start + i as u64 * one_day), *value);
2477        }
2478
2479        let stats = analyzer.get_performance_stats_returns_vs_benchmark(&benchmark);
2480
2481        // r = [0.03, -0.01, 0.02, 0.04], b = [0.01, 0.005, 0.005, 0.01]:
2482        //   mean_r = 0.02, mean_b = 0.0075
2483        //   Cov = 1.5e-4 / 3 = 5e-5, Var(b) = 2.5e-5 / 3 -> beta = 6.0
2484        // Only the benchmark-relative statistic contributes; SharpeRatio
2485        // returns None from the default and is skipped.
2486        assert_eq!(stats.len(), 1);
2487        assert!(approx_eq!(
2488            f64,
2489            *stats.get("Beta").unwrap(),
2490            6.0,
2491            epsilon = 1e-9
2492        ));
2493        assert!(!stats.contains_key("Sharpe Ratio (252 days)"));
2494    }
2495}