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        }
1152    }
1153
1154    struct MockAccount {
1155        starting_balances: AHashMap<Currency, Money>,
1156        current_balances: AHashMap<Currency, Money>,
1157        events: Vec<AccountState>,
1158    }
1159
1160    impl Account for MockAccount {
1161        fn starting_balances(&self) -> IndexMap<Currency, Money> {
1162            self.starting_balances.clone().into_iter().collect()
1163        }
1164        fn balances_total(&self) -> IndexMap<Currency, Money> {
1165            self.current_balances.clone().into_iter().collect()
1166        }
1167        fn id(&self) -> AccountId {
1168            todo!()
1169        }
1170        fn account_type(&self) -> AccountType {
1171            todo!()
1172        }
1173        fn base_currency(&self) -> Option<Currency> {
1174            todo!()
1175        }
1176        fn is_cash_account(&self) -> bool {
1177            todo!()
1178        }
1179        fn is_margin_account(&self) -> bool {
1180            todo!()
1181        }
1182        fn calculated_account_state(&self) -> bool {
1183            todo!()
1184        }
1185        fn balance_total(&self, _: Option<Currency>) -> Option<Money> {
1186            todo!()
1187        }
1188        fn balance_free(&self, _: Option<Currency>) -> Option<Money> {
1189            todo!()
1190        }
1191        fn balances_free(&self) -> IndexMap<Currency, Money> {
1192            todo!()
1193        }
1194        fn balance_locked(&self, _: Option<Currency>) -> Option<Money> {
1195            todo!()
1196        }
1197        fn balances_locked(&self) -> IndexMap<Currency, Money> {
1198            todo!()
1199        }
1200        fn last_event(&self) -> Option<AccountState> {
1201            self.events.last().cloned()
1202        }
1203        fn events(&self) -> Vec<AccountState> {
1204            self.events.clone()
1205        }
1206        fn event_count(&self) -> usize {
1207            self.events.len()
1208        }
1209        fn currencies(&self) -> Vec<Currency> {
1210            self.current_balances.keys().copied().collect()
1211        }
1212        fn balances(&self) -> IndexMap<Currency, AccountBalance> {
1213            todo!()
1214        }
1215        fn apply(&mut self, _: AccountState) -> anyhow::Result<()> {
1216            todo!()
1217        }
1218        fn calculate_balance_locked(
1219            &self,
1220            _: &InstrumentAny,
1221            _: OrderSide,
1222            _: Quantity,
1223            _: Price,
1224            _: Option<bool>,
1225        ) -> Result<Money, anyhow::Error> {
1226            todo!()
1227        }
1228        fn calculate_pnls(
1229            &self,
1230            _: &InstrumentAny,
1231            _: &OrderFilled,
1232            _: Option<Position>,
1233        ) -> Result<Vec<Money>, anyhow::Error> {
1234            todo!()
1235        }
1236        fn calculate_commission(
1237            &self,
1238            _: &InstrumentAny,
1239            _: Quantity,
1240            _: Price,
1241            _: LiquiditySide,
1242            _: MakerTakerFeeRates,
1243            _: Option<bool>,
1244        ) -> Result<Money, anyhow::Error> {
1245            todo!()
1246        }
1247
1248        fn balance(&self, _: Option<Currency>) -> Option<&AccountBalance> {
1249            todo!()
1250        }
1251
1252        fn purge_account_events(&mut self, _: UnixNanos, _: u64) {
1253            // MockAccount doesn't need purging
1254        }
1255    }
1256
1257    fn create_account_state(total: f64, currency: Currency, ts_event: u64) -> AccountState {
1258        AccountState::new(
1259            AccountId::new("test-account"),
1260            AccountType::Cash,
1261            vec![AccountBalance::new(
1262                Money::new(total, currency),
1263                Money::new(0.0, currency),
1264                Money::new(total, currency),
1265            )],
1266            vec![],
1267            true,
1268            UUID4::new(),
1269            UnixNanos::from(ts_event),
1270            UnixNanos::from(ts_event),
1271            Some(currency),
1272        )
1273    }
1274
1275    fn create_portfolio_snapshot(
1276        account_id: AccountId,
1277        equity: Decimal,
1278        currency: Currency,
1279        ts_event: u64,
1280    ) -> PortfolioSnapshot {
1281        let equity = Money::from_decimal(equity, currency).unwrap();
1282
1283        PortfolioSnapshot::new(
1284            account_id,
1285            AccountType::Cash,
1286            Some(currency),
1287            vec![],
1288            vec![],
1289            vec![],
1290            vec![],
1291            vec![equity],
1292            Some(equity),
1293            false,
1294            vec![],
1295            vec![],
1296            vec![],
1297            UUID4::new(),
1298            UnixNanos::from(ts_event),
1299            UnixNanos::from(ts_event),
1300        )
1301    }
1302
1303    #[rstest]
1304    fn test_calculate_snapshot_returns_tracks_daily_mark_to_market_equity() {
1305        let account_id = AccountId::new("SIM-001");
1306        let currency = Currency::USD();
1307        let snapshots = [
1308            create_portfolio_snapshot(
1309                account_id,
1310                Decimal::from(10_000),
1311                currency,
1312                NANOSECONDS_IN_DAY + NANOSECONDS_IN_DAY / 2,
1313            ),
1314            create_portfolio_snapshot(
1315                account_id,
1316                Decimal::from(10_500),
1317                currency,
1318                NANOSECONDS_IN_DAY + 3 * NANOSECONDS_IN_DAY / 4,
1319            ),
1320            create_portfolio_snapshot(
1321                account_id,
1322                Decimal::from(11_000),
1323                currency,
1324                2 * NANOSECONDS_IN_DAY,
1325            ),
1326            create_portfolio_snapshot(
1327                account_id,
1328                Decimal::from(12_100),
1329                currency,
1330                3 * NANOSECONDS_IN_DAY,
1331            ),
1332        ];
1333
1334        let returns =
1335            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1336        let values: Vec<f64> = returns.values().copied().collect();
1337        let dates: Vec<UnixNanos> = returns.keys().copied().collect();
1338
1339        assert_eq!(
1340            dates,
1341            vec![
1342                UnixNanos::from(NANOSECONDS_IN_DAY),
1343                UnixNanos::from(2 * NANOSECONDS_IN_DAY),
1344            ]
1345        );
1346        assert_eq!(values.len(), 2);
1347        assert!(approx_eq!(f64, values[0], 0.1, epsilon = 1e-12));
1348        assert!(approx_eq!(f64, values[1], 0.1, epsilon = 1e-12));
1349    }
1350
1351    #[rstest]
1352    fn test_calculate_snapshot_returns_aggregates_accounts_in_one_currency() {
1353        let account_a = AccountId::new("SIM-001");
1354        let account_b = AccountId::new("SIM-002");
1355        let currency = Currency::USD();
1356        let snapshots = [
1357            create_portfolio_snapshot(account_a, Decimal::from(100), currency, NANOSECONDS_IN_DAY),
1358            create_portfolio_snapshot(account_b, Decimal::from(50), currency, NANOSECONDS_IN_DAY),
1359            create_portfolio_snapshot(
1360                account_a,
1361                Decimal::from(110),
1362                currency,
1363                2 * NANOSECONDS_IN_DAY,
1364            ),
1365        ];
1366
1367        let returns = PortfolioAnalyzer::calculate_snapshot_returns(
1368            &[account_a, account_b],
1369            snapshots.iter(),
1370        )
1371        .unwrap();
1372
1373        assert!(approx_eq!(
1374            f64,
1375            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1376            160.0 / 150.0 - 1.0,
1377            epsilon = 1e-12
1378        ));
1379    }
1380
1381    #[rstest]
1382    fn test_calculate_snapshot_returns_uses_single_total_without_base_currency() {
1383        let account_id = AccountId::new("SIM-001");
1384        let currency = Currency::USD();
1385        let mut first =
1386            create_portfolio_snapshot(account_id, Decimal::from(100), currency, NANOSECONDS_IN_DAY);
1387        let mut second = create_portfolio_snapshot(
1388            account_id,
1389            Decimal::from(110),
1390            currency,
1391            2 * NANOSECONDS_IN_DAY,
1392        );
1393        first.base_currency_equity = None;
1394        second.base_currency_equity = None;
1395        let snapshots = [first, second];
1396
1397        let returns =
1398            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1399
1400        assert!(approx_eq!(
1401            f64,
1402            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1403            0.1,
1404            epsilon = 1e-12
1405        ));
1406    }
1407
1408    #[rstest]
1409    fn test_calculate_snapshot_returns_rejects_multi_currency_total_with_base_equity() {
1410        let account_id = AccountId::new("SIM-001");
1411        let mut first = create_portfolio_snapshot(
1412            account_id,
1413            Decimal::from(100),
1414            Currency::USD(),
1415            NANOSECONDS_IN_DAY,
1416        );
1417        let mut second = create_portfolio_snapshot(
1418            account_id,
1419            Decimal::from(110),
1420            Currency::USD(),
1421            2 * NANOSECONDS_IN_DAY,
1422        );
1423        first.total_equity.push(Money::new(50.0, Currency::AUD()));
1424        second.total_equity.push(Money::new(55.0, Currency::AUD()));
1425        let snapshots = [first, second];
1426
1427        let returns =
1428            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter());
1429
1430        assert!(returns.is_none());
1431    }
1432
1433    #[rstest]
1434    fn test_calculate_snapshot_returns_forward_fills_unpriced_dates() {
1435        let account_id = AccountId::new("SIM-001");
1436        let currency = Currency::USD();
1437        let first =
1438            create_portfolio_snapshot(account_id, Decimal::from(100), currency, NANOSECONDS_IN_DAY);
1439        let mut unpriced =
1440            create_portfolio_snapshot(account_id, Decimal::ZERO, currency, 2 * NANOSECONDS_IN_DAY);
1441        unpriced.unpriced_instruments = vec![instrument_id_aud_usd_sim()];
1442        let last = create_portfolio_snapshot(
1443            account_id,
1444            Decimal::from(110),
1445            currency,
1446            3 * NANOSECONDS_IN_DAY,
1447        );
1448        let snapshots = [first, unpriced, last];
1449
1450        let returns =
1451            PortfolioAnalyzer::calculate_snapshot_returns(&[account_id], snapshots.iter()).unwrap();
1452
1453        assert!(approx_eq!(
1454            f64,
1455            returns[&UnixNanos::from(NANOSECONDS_IN_DAY)],
1456            0.0,
1457            epsilon = 1e-12
1458        ));
1459        assert!(approx_eq!(
1460            f64,
1461            returns[&UnixNanos::from(2 * NANOSECONDS_IN_DAY)],
1462            0.1,
1463            epsilon = 1e-12
1464        ));
1465    }
1466
1467    #[rstest]
1468    fn test_calculate_snapshot_returns_rejects_mixed_account_currencies() {
1469        let account_a = AccountId::new("SIM-001");
1470        let account_b = AccountId::new("SIM-002");
1471        let snapshots = [
1472            create_portfolio_snapshot(
1473                account_a,
1474                Decimal::from(100),
1475                Currency::USD(),
1476                NANOSECONDS_IN_DAY,
1477            ),
1478            create_portfolio_snapshot(
1479                account_b,
1480                Decimal::from(100),
1481                Currency::AUD(),
1482                NANOSECONDS_IN_DAY,
1483            ),
1484        ];
1485
1486        let returns = PortfolioAnalyzer::calculate_snapshot_returns(
1487            &[account_a, account_b],
1488            snapshots.iter(),
1489        );
1490
1491        assert!(returns.is_none());
1492    }
1493
1494    #[rstest]
1495    fn test_register_and_deregister_statistics() {
1496        let mut analyzer = PortfolioAnalyzer::new();
1497        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1498            Arc::new(MockStatistic::new("test_stat"));
1499
1500        // Test registration
1501        analyzer.register_statistic(Arc::clone(&stat));
1502        assert!(analyzer.statistic("test_stat").is_some());
1503
1504        // Test deregistration
1505        analyzer.deregister_statistic(&stat);
1506        assert!(analyzer.statistic("test_stat").is_none());
1507
1508        // Test deregister all
1509        let stat1: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1510            Arc::new(MockStatistic::new("stat1"));
1511        let stat2: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1512            Arc::new(MockStatistic::new("stat2"));
1513        analyzer.register_statistic(Arc::clone(&stat1));
1514        analyzer.register_statistic(Arc::clone(&stat2));
1515        analyzer.deregister_statistics();
1516        assert!(analyzer.statistics.is_empty());
1517    }
1518
1519    #[rstest]
1520    fn test_register_statistic_replaces_matching_name() {
1521        let mut analyzer = PortfolioAnalyzer::new();
1522        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 1.0)));
1523        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 2.0)));
1524
1525        let stats = analyzer.get_performance_stats_general();
1526
1527        assert_eq!(analyzer.statistics.len(), 1);
1528        assert_eq!(stats["Custom"], 2.0);
1529    }
1530
1531    #[rstest]
1532    fn test_pnl_statistics_reject_unresolved_currency() {
1533        // Two currencies and no account balances: the currency cannot be resolved, so
1534        // dispatching on an empty slice would report a result that ignores both trades.
1535        let mut analyzer = PortfolioAnalyzer::new();
1536        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 1.0)));
1537        analyzer.add_trade(
1538            &PositionId::new("P-USD"),
1539            UnixNanos::from(1),
1540            &Money::new(10.0, Currency::USD()),
1541        );
1542        analyzer.add_trade(
1543            &PositionId::new("P-EUR"),
1544            UnixNanos::from(2),
1545            &Money::new(5.0, Currency::EUR()),
1546        );
1547
1548        let result = analyzer.get_performance_stats_pnls(None, None);
1549
1550        assert_eq!(
1551            result,
1552            Err("Currency must be specified for multi-currency portfolio")
1553        );
1554    }
1555
1556    #[rstest]
1557    fn test_pnl_statistics_resolve_single_pnl_currency() {
1558        // One realized-PnL currency and no explicit currency: resolution falls back to that
1559        // currency, so statistics dispatch on its records.
1560        let mut analyzer = PortfolioAnalyzer::new();
1561        analyzer.register_statistic(Arc::new(MockStatistic::new("test_stat")));
1562        let currency = Currency::USD();
1563        let position_id = PositionId::new("P-USD");
1564        analyzer.add_trade(
1565            &position_id,
1566            UnixNanos::from(1),
1567            &Money::new(10.0, currency),
1568        );
1569
1570        let records = analyzer.trade_pnl_records(None).unwrap();
1571        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1572
1573        assert_eq!(records, vec![(position_id, UnixNanos::from(1), 10.0)]);
1574        assert_eq!(stats["test_stat"], 10.0);
1575    }
1576
1577    #[rstest]
1578    fn test_pnl_statistics_prefer_account_balance_currency() {
1579        // A single account-balance currency resolves the query even when the realized-PnL
1580        // records are in another currency: the balance currency wins, has no records, and
1581        // statistics dispatch on an empty slice instead of erroring.
1582        let mut analyzer = PortfolioAnalyzer::new();
1583        analyzer.register_statistic(Arc::new(MockStatistic::new("test_stat")));
1584        let currency = Currency::USD();
1585        analyzer
1586            .account_balances
1587            .insert(currency, Money::new(1000.0, currency));
1588        analyzer.add_trade(
1589            &PositionId::new("P-EUR"),
1590            UnixNanos::from(1),
1591            &Money::new(5.0, Currency::EUR()),
1592        );
1593
1594        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1595
1596        assert!(analyzer.trade_pnl_records(None).is_none());
1597        assert_eq!(stats["test_stat"], 0.0);
1598    }
1599
1600    #[rstest]
1601    fn test_trade_pnl_records_sorted_by_event_time() {
1602        // A recorded PnL at t=1 and an unmatched position-derived PnL at t=2 are merged from
1603        // two sources; without sorting the derived record leads and the sequence reads [t2, t1].
1604        let currency = Currency::USD();
1605        let mut analyzer = PortfolioAnalyzer::new();
1606        analyzer.add_trade(
1607            &PositionId::new("P-LATE"),
1608            UnixNanos::from(2),
1609            &Money::new(5.0, currency),
1610        );
1611        analyzer.record_trade(
1612            &PositionId::new("P-EARLY"),
1613            UnixNanos::from(1),
1614            &Money::new(7.0, currency),
1615        );
1616
1617        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1618
1619        assert_eq!(
1620            records,
1621            vec![
1622                (PositionId::new("P-EARLY"), UnixNanos::from(1), 7.0),
1623                (PositionId::new("P-LATE"), UnixNanos::from(2), 5.0),
1624            ]
1625        );
1626    }
1627
1628    #[rstest]
1629    fn test_pnl_statistics_run_without_any_trades() {
1630        // No realized PnLs at all: registered statistics still receive an empty slice, so a
1631        // statistic defined for empty input reports its value instead of vanishing.
1632        let mut analyzer = PortfolioAnalyzer::new();
1633        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 0.0)));
1634
1635        let stats = analyzer
1636            .get_performance_stats_pnls(Some(&Currency::USD()), None)
1637            .unwrap();
1638
1639        assert_eq!(stats["Custom"], 0.0);
1640        assert_eq!(stats["PnL (total)"], 0.0);
1641    }
1642
1643    #[rstest]
1644    fn test_pnl_statistics_run_without_any_trades_or_currency() {
1645        // No realized PnLs and no explicit currency: with nothing to resolve, statistics
1646        // still receive an empty slice instead of erroring.
1647        let mut analyzer = PortfolioAnalyzer::new();
1648        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 0.0)));
1649
1650        let stats = analyzer.get_performance_stats_pnls(None, None).unwrap();
1651
1652        assert_eq!(stats["Custom"], 0.0);
1653        assert_eq!(stats["PnL (total)"], 0.0);
1654    }
1655
1656    #[rstest]
1657    fn test_reset_retains_registered_statistics() {
1658        let currency = Currency::USD();
1659        let mut analyzer = PortfolioAnalyzer::new();
1660        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 7.5)));
1661        analyzer.add_positions(&[create_mock_position("AUD/USD", 100.0, 0.1, currency)]);
1662
1663        analyzer.reset();
1664
1665        assert!(analyzer.positions.is_empty());
1666        assert_eq!(analyzer.statistics.len(), 1);
1667        assert_eq!(analyzer.get_performance_stats_general()["Custom"], 7.5);
1668    }
1669
1670    #[rstest]
1671    fn test_formatted_general_stats_include_custom_statistic() {
1672        // The post-run analysis log formats from this same method, so a registered
1673        // custom statistic must appear alongside the built-in defaults.
1674        let mut analyzer = PortfolioAnalyzer::new();
1675        analyzer.register_statistic(Arc::new(ConstantStatistic::new("Custom", 12.5)));
1676
1677        let lines = analyzer.get_stats_general_formatted();
1678
1679        assert_eq!(lines, vec!["Custom:  12.5".to_string()]);
1680    }
1681
1682    #[rstest]
1683    fn test_replace_statistics_adopts_given_set() {
1684        let mut analyzer = PortfolioAnalyzer::default();
1685        let default_count = analyzer.statistics.len();
1686
1687        let mut replacement: AHashMap<String, Statistic> = AHashMap::new();
1688        replacement.insert(
1689            "Custom".to_string(),
1690            Arc::new(ConstantStatistic::new("Custom", 3.25)),
1691        );
1692        analyzer.replace_statistics(replacement);
1693
1694        let stats = analyzer.get_performance_stats_general();
1695
1696        assert!(default_count > 1);
1697        assert_eq!(analyzer.statistics.len(), 1);
1698        assert_eq!(stats.len(), 1);
1699        assert_eq!(stats["Custom"], 3.25);
1700    }
1701
1702    #[rstest]
1703    fn test_calculate_total_pnl() {
1704        let mut analyzer = PortfolioAnalyzer::new();
1705        let currency = Currency::USD();
1706
1707        // Set up mock account data
1708        let mut starting_balances = AHashMap::new();
1709        starting_balances.insert(currency, Money::new(1000.0, currency));
1710
1711        let mut current_balances = AHashMap::new();
1712        current_balances.insert(currency, Money::new(1500.0, currency));
1713
1714        let account = MockAccount {
1715            starting_balances,
1716            current_balances,
1717            events: vec![],
1718        };
1719
1720        analyzer.calculate_statistics(&account, &[]);
1721
1722        // Test total PnL calculation
1723        let result = analyzer.total_pnl(Some(&currency), None).unwrap();
1724        assert!(approx_eq!(f64, result, 500.0, epsilon = 1e-9));
1725
1726        // Test with unrealized PnL
1727        let unrealized_pnl = Money::new(100.0, currency);
1728        let result = analyzer
1729            .total_pnl(Some(&currency), Some(&unrealized_pnl))
1730            .unwrap();
1731        assert!(approx_eq!(f64, result, 600.0, epsilon = 1e-9));
1732    }
1733
1734    #[rstest]
1735    fn test_calculate_total_pnl_percentage() {
1736        let mut analyzer = PortfolioAnalyzer::new();
1737        let currency = Currency::USD();
1738
1739        // Set up mock account data
1740        let mut starting_balances = AHashMap::new();
1741        starting_balances.insert(currency, Money::new(1000.0, currency));
1742
1743        let mut current_balances = AHashMap::new();
1744        current_balances.insert(currency, Money::new(1500.0, currency));
1745
1746        let account = MockAccount {
1747            starting_balances,
1748            current_balances,
1749            events: vec![],
1750        };
1751
1752        analyzer.calculate_statistics(&account, &[]);
1753
1754        // Test percentage calculation
1755        let result = analyzer
1756            .total_pnl_percentage(Some(&currency), None)
1757            .unwrap();
1758        assert!(approx_eq!(f64, result, 50.0, epsilon = 1e-9)); // (1500 - 1000) / 1000 * 100
1759
1760        // Test with unrealized PnL
1761        let unrealized_pnl = Money::new(500.0, currency);
1762        let result = analyzer
1763            .total_pnl_percentage(Some(&currency), Some(&unrealized_pnl))
1764            .unwrap();
1765        assert!(approx_eq!(f64, result, 100.0, epsilon = 1e-9)); // (2000 - 1000) / 1000 * 100
1766    }
1767
1768    #[rstest]
1769    fn test_add_positions_and_returns() {
1770        let mut analyzer = PortfolioAnalyzer::new();
1771        let currency = Currency::USD();
1772
1773        let positions = vec![
1774            create_mock_position("AUD/USD", 100.0, 0.1, currency),
1775            create_mock_position("AUD/USD", 200.0, 0.2, currency),
1776        ];
1777
1778        analyzer.add_positions(&positions);
1779
1780        // Verify realized PnLs were recorded
1781        let pnls = analyzer.realized_pnls(Some(&currency)).unwrap();
1782        assert_eq!(pnls.len(), 2);
1783        assert!(approx_eq!(f64, pnls[0].2, 100.0, epsilon = 1e-9));
1784        assert!(approx_eq!(f64, pnls[1].2, 200.0, epsilon = 1e-9));
1785
1786        // Verify returns were recorded
1787        let returns = analyzer.returns();
1788        let position_returns = analyzer.position_returns();
1789        assert_eq!(returns.len(), 1);
1790        assert_eq!(position_returns.len(), 1);
1791        assert!(analyzer.portfolio_returns().is_empty());
1792        assert!(approx_eq!(
1793            f64,
1794            *returns.values().next().unwrap(),
1795            0.30000000000000004,
1796            epsilon = 1e-9
1797        ));
1798        assert!(approx_eq!(
1799            f64,
1800            *position_returns.values().next().unwrap(),
1801            0.30000000000000004,
1802            epsilon = 1e-9
1803        ));
1804    }
1805
1806    #[rstest]
1807    fn test_add_positions_skips_position_returns_without_real_close_timestamp() {
1808        let mut analyzer = PortfolioAnalyzer::new();
1809        let currency = Currency::USD();
1810        let mut position = create_mock_position("AUD/USD", 100.0, 0.1, currency);
1811        position.ts_closed = Some(UnixNanos::default());
1812
1813        analyzer.add_positions(&[position]);
1814
1815        assert!(analyzer.position_returns().is_empty());
1816        assert!(analyzer.returns().is_empty());
1817    }
1818
1819    #[rstest]
1820    fn test_add_positions_records_open_position_realized_pnl() {
1821        let mut analyzer = PortfolioAnalyzer::new();
1822        let currency = Currency::USD();
1823        let mut position = create_mock_position("AUD/USD", 100.0, 0.1, currency);
1824        position.ts_closed = None;
1825        // Distinct from ts_opened (default 0) so the record is keyed by the last event time.
1826        position.ts_last = UnixNanos::from(7);
1827        let position_id = position.id;
1828
1829        analyzer.add_positions(&[position]);
1830
1831        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1832        assert_eq!(records.len(), 1);
1833        assert_eq!(records[0], (position_id, UnixNanos::from(7), 100.0));
1834        assert!(analyzer.position_returns().is_empty());
1835    }
1836
1837    #[rstest]
1838    fn test_trade_pnl_records_keeps_unrecorded_native_cycle() {
1839        // A NETTING id with two native cycles where only the later cycle was recorded:
1840        // the earlier native cycle must survive rather than be dropped by position ID.
1841        let mut analyzer = PortfolioAnalyzer::new();
1842        let currency = Currency::USD();
1843        let position_id = PositionId::new("pos1");
1844
1845        analyzer.add_trade(
1846            &position_id,
1847            UnixNanos::from(1),
1848            &Money::new(10.0, currency),
1849        );
1850        analyzer.add_trade(
1851            &position_id,
1852            UnixNanos::from(2),
1853            &Money::new(20.0, currency),
1854        );
1855        analyzer.record_trade(
1856            &position_id,
1857            UnixNanos::from(2),
1858            &Money::new(25.0, currency),
1859        );
1860
1861        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1862
1863        assert_eq!(
1864            records,
1865            vec![
1866                (position_id, UnixNanos::from(1), 10.0),
1867                (position_id, UnixNanos::from(2), 25.0),
1868            ]
1869        );
1870    }
1871
1872    #[rstest]
1873    fn test_trade_pnl_records_drops_recorded_snapshot_alias() {
1874        let mut analyzer = PortfolioAnalyzer::new();
1875        let currency = Currency::USD();
1876        let position_id = PositionId::new("pos1");
1877        let snapshot_id = PositionId::new(format!("{}-{}", position_id.as_str(), UUID4::new()));
1878        let ts_event = UnixNanos::from(1);
1879
1880        analyzer.add_trade(&snapshot_id, ts_event, &Money::new(10.0, currency));
1881        analyzer.record_trade(&position_id, ts_event, &Money::new(10.0, currency));
1882
1883        let records = analyzer.trade_pnl_records(Some(&currency)).unwrap();
1884
1885        assert_eq!(records, vec![(position_id, ts_event, 10.0)]);
1886    }
1887
1888    #[rstest]
1889    fn test_performance_stats_calculation() {
1890        let mut analyzer = PortfolioAnalyzer::new();
1891        let currency = Currency::USD();
1892        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1893            Arc::new(MockStatistic::new("test_stat"));
1894        analyzer.register_statistic(Arc::clone(&stat));
1895
1896        // Add some positions
1897        let positions = vec![
1898            create_mock_position("AUD/USD", 100.0, 0.1, currency),
1899            create_mock_position("AUD/USD", 200.0, 0.2, currency),
1900        ];
1901
1902        let mut starting_balances = AHashMap::new();
1903        starting_balances.insert(currency, Money::new(1000.0, currency));
1904
1905        let mut current_balances = AHashMap::new();
1906        current_balances.insert(currency, Money::new(1500.0, currency));
1907
1908        let account = MockAccount {
1909            starting_balances,
1910            current_balances,
1911            events: vec![],
1912        };
1913
1914        analyzer.calculate_statistics(&account, &positions);
1915
1916        // Test PnL stats
1917        let pnl_stats = analyzer
1918            .get_performance_stats_pnls(Some(&currency), None)
1919            .unwrap();
1920        assert!(pnl_stats.contains_key("PnL (total)"));
1921        assert!(pnl_stats.contains_key("PnL% (total)"));
1922        assert!(pnl_stats.contains_key("test_stat"));
1923
1924        // Test returns stats
1925        let return_stats = analyzer.get_performance_stats_returns();
1926        assert!(return_stats.contains_key("test_stat"));
1927
1928        // Test general stats
1929        let general_stats = analyzer.get_performance_stats_general();
1930        assert!(general_stats.contains_key("test_stat"));
1931    }
1932
1933    #[rstest]
1934    fn test_calculate_statistics_preserves_recorded_realized_pnls() {
1935        let mut analyzer = PortfolioAnalyzer::new();
1936        let account_currency = Currency::EUR();
1937        let native_currency = Currency::USD();
1938        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1939            Arc::new(MockStatistic::new("test_stat"));
1940        analyzer.register_statistic(Arc::clone(&stat));
1941        analyzer.record_trade(
1942            &PositionId::new("pos1"),
1943            UnixNanos::from(1),
1944            &Money::new(90.0, account_currency),
1945        );
1946
1947        let positions = vec![create_mock_position("pos1", 100.0, 0.1, native_currency)];
1948
1949        let mut starting_balances = AHashMap::new();
1950        starting_balances.insert(account_currency, Money::new(1000.0, account_currency));
1951
1952        let mut current_balances = AHashMap::new();
1953        current_balances.insert(account_currency, Money::new(1100.0, account_currency));
1954
1955        let account = MockAccount {
1956            starting_balances,
1957            current_balances,
1958            events: vec![],
1959        };
1960
1961        analyzer.calculate_statistics(&account, &positions);
1962
1963        let native_pnls = analyzer.realized_pnls(Some(&native_currency)).unwrap();
1964        let recorded_pnls = analyzer.realized_pnls(Some(&account_currency)).unwrap();
1965        let pnl_stats = analyzer
1966            .get_performance_stats_pnls(Some(&account_currency), None)
1967            .unwrap();
1968
1969        assert_eq!(native_pnls[0].2, 100.0);
1970        assert_eq!(recorded_pnls[0].2, 90.0);
1971        assert_eq!(*pnl_stats.get("test_stat").unwrap(), 90.0);
1972    }
1973
1974    #[rstest]
1975    fn test_record_trade_preserves_duplicate_position_ids() {
1976        let mut analyzer = PortfolioAnalyzer::new();
1977        let account_currency = Currency::EUR();
1978        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
1979            Arc::new(MockStatistic::new("test_stat"));
1980        let position_id = PositionId::new("pos1");
1981
1982        analyzer.register_statistic(Arc::clone(&stat));
1983        analyzer.record_trade(
1984            &position_id,
1985            UnixNanos::from(1),
1986            &Money::new(90.0, account_currency),
1987        );
1988        analyzer.record_trade(
1989            &position_id,
1990            UnixNanos::from(2),
1991            &Money::new(-45.0, account_currency),
1992        );
1993
1994        let records = analyzer.trade_pnl_records(Some(&account_currency)).unwrap();
1995        let recorded_pnls = analyzer.realized_pnls(Some(&account_currency)).unwrap();
1996        let pnl_stats = analyzer
1997            .get_performance_stats_pnls(Some(&account_currency), None)
1998            .unwrap();
1999
2000        assert_eq!(records[0], (position_id, UnixNanos::from(1), 90.0));
2001        assert_eq!(records[1], (position_id, UnixNanos::from(2), -45.0));
2002        assert_eq!(
2003            recorded_pnls,
2004            vec![
2005                (position_id, UnixNanos::from(1), 90.0),
2006                (position_id, UnixNanos::from(2), -45.0),
2007            ]
2008        );
2009        assert_eq!(*pnl_stats.get("test_stat").unwrap(), 45.0);
2010    }
2011    #[rstest]
2012    fn test_formatted_output() {
2013        let mut analyzer = PortfolioAnalyzer::new();
2014        let currency = Currency::USD();
2015        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
2016            Arc::new(MockStatistic::new("test_stat"));
2017        analyzer.register_statistic(Arc::clone(&stat));
2018
2019        let positions = vec![
2020            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2021            create_mock_position("AUD/USD", 200.0, 0.2, currency),
2022        ];
2023
2024        let mut starting_balances = AHashMap::new();
2025        starting_balances.insert(currency, Money::new(1000.0, currency));
2026
2027        let mut current_balances = AHashMap::new();
2028        current_balances.insert(currency, Money::new(1500.0, currency));
2029
2030        let account = MockAccount {
2031            starting_balances,
2032            current_balances,
2033            events: vec![],
2034        };
2035
2036        analyzer.calculate_statistics(&account, &positions);
2037
2038        // Test formatted outputs
2039        let pnl_formatted = analyzer
2040            .get_stats_pnls_formatted(Some(&currency), None)
2041            .unwrap();
2042        assert!(!pnl_formatted.is_empty());
2043        assert!(pnl_formatted.iter().all(|s| s.contains(':')));
2044
2045        let returns_formatted = analyzer.get_stats_returns_formatted();
2046        assert!(!returns_formatted.is_empty());
2047        assert!(returns_formatted.iter().all(|s| s.contains(':')));
2048
2049        let general_formatted = analyzer.get_stats_general_formatted();
2050        assert!(!general_formatted.is_empty());
2051        assert!(general_formatted.iter().all(|s| s.contains(':')));
2052    }
2053
2054    #[rstest]
2055    fn test_reset() {
2056        let mut analyzer = PortfolioAnalyzer::new();
2057        let currency = Currency::USD();
2058
2059        let positions = vec![create_mock_position("AUD/USD", 100.0, 0.1, currency)];
2060        let mut starting_balances = AHashMap::new();
2061        starting_balances.insert(currency, Money::new(1000.0, currency));
2062        let mut current_balances = AHashMap::new();
2063        current_balances.insert(currency, Money::new(1500.0, currency));
2064
2065        let account = MockAccount {
2066            starting_balances,
2067            current_balances,
2068            events: vec![],
2069        };
2070
2071        analyzer.calculate_statistics(&account, &positions);
2072
2073        analyzer.reset();
2074
2075        assert!(analyzer.account_balances_starting.is_empty());
2076        assert!(analyzer.account_balances.is_empty());
2077        assert!(analyzer.positions.is_empty());
2078        assert!(analyzer.realized_pnls.is_empty());
2079        assert!(analyzer.recorded_realized_pnls.is_empty());
2080        assert!(analyzer.position_returns.is_empty());
2081        assert!(analyzer.portfolio_returns.is_empty());
2082        assert!(analyzer.returns.is_empty());
2083    }
2084
2085    #[rstest]
2086    fn test_currencies_preserve_account_balance_order() {
2087        // Pin IndexMap iteration on PortfolioAnalyzer::account_balances:
2088        // currencies() drives the per-currency stat computation in
2089        // BacktestEngine::run, so the returned Vec must reflect the
2090        // upstream account balance order across runs.
2091        let mut analyzer = PortfolioAnalyzer::new();
2092        let inserts = [
2093            (Currency::BTC(), Money::new(1.0, Currency::BTC())),
2094            (Currency::USD(), Money::new(2.0, Currency::USD())),
2095            (Currency::ETH(), Money::new(3.0, Currency::ETH())),
2096        ];
2097
2098        for (currency, money) in inserts {
2099            analyzer.account_balances.insert(currency, money);
2100        }
2101
2102        let returned: Vec<Currency> = analyzer.currencies().into_iter().copied().collect();
2103        assert_eq!(
2104            returned,
2105            vec![Currency::BTC(), Currency::USD(), Currency::ETH()],
2106        );
2107    }
2108
2109    #[rstest]
2110    fn test_calculate_statistics_clears_previous_positions() {
2111        let mut analyzer = PortfolioAnalyzer::new();
2112        let currency = Currency::USD();
2113
2114        let positions1 = vec![create_mock_position("pos1", 100.0, 0.1, currency)];
2115        let positions2 = vec![create_mock_position("pos2", 200.0, 0.2, currency)];
2116
2117        let mut starting_balances = AHashMap::new();
2118        starting_balances.insert(currency, Money::new(1000.0, currency));
2119        let mut current_balances = AHashMap::new();
2120        current_balances.insert(currency, Money::new(1500.0, currency));
2121
2122        let account = MockAccount {
2123            starting_balances,
2124            current_balances,
2125            events: vec![],
2126        };
2127
2128        // First calculation
2129        analyzer.calculate_statistics(&account, &positions1);
2130        assert_eq!(analyzer.positions.len(), 1);
2131
2132        // Second calculation should NOT accumulate
2133        analyzer.calculate_statistics(&account, &positions2);
2134        assert_eq!(analyzer.positions.len(), 1);
2135    }
2136
2137    #[rstest]
2138    fn test_calculate_statistics_uses_account_state_returns_when_available() {
2139        let mut analyzer = PortfolioAnalyzer::new();
2140        let currency = Currency::USD();
2141        let positions = vec![
2142            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2143            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2144        ];
2145
2146        let mut starting_balances = AHashMap::new();
2147        starting_balances.insert(currency, Money::new(1000.0, currency));
2148
2149        let mut current_balances = AHashMap::new();
2150        current_balances.insert(currency, Money::new(1100.0, currency));
2151
2152        let account = MockAccount {
2153            starting_balances,
2154            current_balances,
2155            events: vec![
2156                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2157                create_account_state(1050.0, currency, 1_704_844_800_000_000_000),
2158                create_account_state(1100.0, currency, 1_706_659_200_000_000_000),
2159            ],
2160        };
2161
2162        analyzer.calculate_statistics(&account, &positions);
2163
2164        let position_returns = analyzer.position_returns();
2165        let portfolio_returns = analyzer.portfolio_returns();
2166        let returns = analyzer.returns();
2167        assert_eq!(position_returns.len(), 1);
2168        assert_eq!(portfolio_returns.len(), 30);
2169        assert_eq!(returns, portfolio_returns);
2170        assert!(approx_eq!(
2171            f64,
2172            *portfolio_returns
2173                .get(&UnixNanos::from(1_704_153_600_000_000_000))
2174                .unwrap(),
2175            0.0,
2176            epsilon = 1e-9
2177        ));
2178        assert!(approx_eq!(
2179            f64,
2180            *portfolio_returns
2181                .get(&UnixNanos::from(1_704_844_800_000_000_000))
2182                .unwrap(),
2183            0.05,
2184            epsilon = 1e-9
2185        ));
2186        assert!(approx_eq!(
2187            f64,
2188            *portfolio_returns
2189                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2190                .unwrap(),
2191            (1100.0 / 1050.0) - 1.0,
2192            epsilon = 1e-9
2193        ));
2194        assert!(approx_eq!(
2195            f64,
2196            *position_returns.values().next().unwrap(),
2197            0.30000000000000004,
2198            epsilon = 1e-9
2199        ));
2200    }
2201
2202    #[rstest]
2203    fn test_calculate_statistics_skips_empty_balance_events() {
2204        let mut analyzer = PortfolioAnalyzer::new();
2205        let currency = Currency::USD();
2206        let mut starting_balances = AHashMap::new();
2207        starting_balances.insert(currency, Money::new(1000.0, currency));
2208        let mut current_balances = AHashMap::new();
2209        current_balances.insert(currency, Money::new(1050.0, currency));
2210        let empty_event = AccountState::new(
2211            AccountId::new("test-account"),
2212            AccountType::Cash,
2213            vec![],
2214            vec![],
2215            true,
2216            UUID4::new(),
2217            UnixNanos::from(1_705_276_800_000_000_000),
2218            UnixNanos::from(1_705_276_800_000_000_000),
2219            Some(currency),
2220        );
2221        let account = MockAccount {
2222            starting_balances,
2223            current_balances,
2224            events: vec![
2225                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2226                empty_event,
2227                create_account_state(1050.0, currency, 1_706_659_200_000_000_000),
2228            ],
2229        };
2230
2231        analyzer.calculate_statistics(&account, &[]);
2232
2233        let portfolio_returns = analyzer.portfolio_returns();
2234        assert_eq!(portfolio_returns.len(), 30);
2235        assert_eq!(analyzer.returns(), portfolio_returns);
2236        assert!(approx_eq!(
2237            f64,
2238            *portfolio_returns
2239                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2240                .unwrap(),
2241            0.05,
2242            epsilon = 1e-9
2243        ));
2244    }
2245
2246    #[rstest]
2247    fn test_calculate_statistics_skips_non_finite_account_returns() {
2248        let mut analyzer = PortfolioAnalyzer::new();
2249        let currency = Currency::USD();
2250
2251        let mut starting_balances = AHashMap::new();
2252        starting_balances.insert(currency, Money::new(0.0, currency));
2253
2254        let mut current_balances = AHashMap::new();
2255        current_balances.insert(currency, Money::new(1050.0, currency));
2256
2257        let account = MockAccount {
2258            starting_balances,
2259            current_balances,
2260            events: vec![
2261                create_account_state(0.0, currency, 1_704_067_200_000_000_000),
2262                create_account_state(1000.0, currency, 1_704_844_800_000_000_000),
2263                create_account_state(1050.0, currency, 1_706_659_200_000_000_000),
2264            ],
2265        };
2266
2267        analyzer.calculate_statistics(&account, &[]);
2268
2269        let returns = analyzer.returns();
2270        assert!(returns.values().all(|value| value.is_finite()));
2271        assert!(approx_eq!(
2272            f64,
2273            *returns
2274                .get(&UnixNanos::from(1_706_659_200_000_000_000))
2275                .unwrap(),
2276            0.05,
2277            epsilon = 1e-9
2278        ));
2279    }
2280
2281    #[rstest]
2282    fn test_calculate_statistics_falls_back_to_position_returns_without_account_events() {
2283        let mut analyzer = PortfolioAnalyzer::new();
2284        let currency = Currency::USD();
2285        let positions = vec![
2286            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2287            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2288        ];
2289
2290        let mut starting_balances = AHashMap::new();
2291        starting_balances.insert(currency, Money::new(1000.0, currency));
2292
2293        let mut current_balances = AHashMap::new();
2294        current_balances.insert(currency, Money::new(1100.0, currency));
2295
2296        let account = MockAccount {
2297            starting_balances,
2298            current_balances,
2299            events: vec![],
2300        };
2301
2302        analyzer.calculate_statistics(&account, &positions);
2303
2304        let returns = analyzer.returns();
2305        assert!(analyzer.portfolio_returns().is_empty());
2306        assert_eq!(returns, analyzer.position_returns());
2307        assert_eq!(returns.len(), 1);
2308        assert!(approx_eq!(
2309            f64,
2310            *returns.values().next().unwrap(),
2311            0.30000000000000004,
2312            epsilon = 1e-9
2313        ));
2314    }
2315
2316    #[rstest]
2317    fn test_get_performance_stats_returns_prefers_portfolio_returns() {
2318        let mut analyzer = PortfolioAnalyzer::new();
2319        let currency = Currency::USD();
2320        let stat: Arc<dyn PortfolioStatistic<Item = f64> + Send + Sync> =
2321            Arc::new(MockStatistic::new("test_stat"));
2322        analyzer.register_statistic(Arc::clone(&stat));
2323
2324        let positions = vec![
2325            create_mock_position("AUD/USD", 100.0, 0.1, currency),
2326            create_mock_position("EUR/USD", 200.0, 0.2, currency),
2327        ];
2328
2329        let mut starting_balances = AHashMap::new();
2330        starting_balances.insert(currency, Money::new(1000.0, currency));
2331
2332        let mut current_balances = AHashMap::new();
2333        current_balances.insert(currency, Money::new(1100.0, currency));
2334
2335        let account = MockAccount {
2336            starting_balances,
2337            current_balances,
2338            events: vec![
2339                create_account_state(1000.0, currency, 1_704_067_200_000_000_000),
2340                create_account_state(1050.0, currency, 1_704_844_800_000_000_000),
2341                create_account_state(1100.0, currency, 1_706_659_200_000_000_000),
2342            ],
2343        };
2344
2345        analyzer.calculate_statistics(&account, &positions);
2346
2347        let position_stats = analyzer.get_performance_stats_position_returns();
2348        let portfolio_stats = analyzer.get_performance_stats_portfolio_returns();
2349        let returns_stats = analyzer.get_performance_stats_returns();
2350
2351        assert!(approx_eq!(
2352            f64,
2353            *position_stats.get("test_stat").unwrap(),
2354            0.30000000000000004,
2355            epsilon = 1e-9
2356        ));
2357        assert_eq!(returns_stats, portfolio_stats);
2358    }
2359
2360    #[rstest]
2361    fn test_from_accounts_aggregates_balances_and_positions() {
2362        let currency = Currency::USD();
2363        let positions = vec![
2364            create_mock_position("pos1", 100.0, 0.1, currency),
2365            create_mock_position("pos2", 200.0, 0.2, currency),
2366        ];
2367
2368        let analyzer = PortfolioAnalyzer::from_accounts(
2369            &[AccountAny::Cash(CashAccount::default())],
2370            &positions,
2371            &[],
2372            AHashMap::new(),
2373        );
2374
2375        assert_eq!(analyzer.positions.len(), positions.len());
2376        assert!(!analyzer.account_balances.is_empty());
2377    }
2378
2379    #[rstest]
2380    fn test_from_accounts_sums_balances_across_accounts() {
2381        let usd = Currency::USD();
2382        let one = PortfolioAnalyzer::from_accounts(
2383            &[AccountAny::Cash(CashAccount::default())],
2384            &[],
2385            &[],
2386            AHashMap::new(),
2387        );
2388        let two = PortfolioAnalyzer::from_accounts(
2389            &[
2390                AccountAny::Cash(CashAccount::default()),
2391                AccountAny::Cash(CashAccount::default()),
2392            ],
2393            &[],
2394            &[],
2395            AHashMap::new(),
2396        );
2397
2398        let single = one.account_balances.get(&usd).unwrap().as_decimal();
2399        let summed = two.account_balances.get(&usd).unwrap().as_decimal();
2400        let single_start = one
2401            .account_balances_starting
2402            .get(&usd)
2403            .unwrap()
2404            .as_decimal();
2405        let summed_start = two
2406            .account_balances_starting
2407            .get(&usd)
2408            .unwrap()
2409            .as_decimal();
2410
2411        assert_eq!(summed, single + single);
2412        assert_eq!(summed_start, single_start + single_start);
2413        assert_ne!(summed, single);
2414    }
2415
2416    #[rstest]
2417    fn test_statistics_snapshot_matches_getters() {
2418        let currency = Currency::USD();
2419        let positions = vec![
2420            create_mock_position("pos1", 100.0, 0.1, currency),
2421            create_mock_position("pos2", 200.0, 0.2, currency),
2422        ];
2423
2424        let analyzer = PortfolioAnalyzer::from_accounts(
2425            &[AccountAny::Cash(CashAccount::default())],
2426            &positions,
2427            &[],
2428            AHashMap::new(),
2429        );
2430
2431        let snapshot = analyzer.statistics();
2432        assert!(maps_equal_nan_aware(
2433            &snapshot.returns,
2434            &analyzer.get_performance_stats_returns()
2435        ));
2436        assert!(maps_equal_nan_aware(
2437            &snapshot.general,
2438            &analyzer.get_performance_stats_general()
2439        ));
2440        assert_eq!(&snapshot.returns_series, analyzer.returns());
2441
2442        for currency in analyzer.currencies() {
2443            let expected = analyzer
2444                .get_performance_stats_pnls(Some(currency), None)
2445                .unwrap();
2446            let actual = snapshot.pnls.get(&currency.code.to_string()).unwrap();
2447            assert!(maps_equal_nan_aware(actual, &expected));
2448        }
2449    }
2450
2451    fn maps_equal_nan_aware(a: &AHashMap<String, f64>, b: &AHashMap<String, f64>) -> bool {
2452        if a.len() != b.len() {
2453            return false;
2454        }
2455        a.iter().all(|(k, v)| {
2456            b.get(k)
2457                .is_some_and(|bv| (v.is_nan() && bv.is_nan()) || (v == bv))
2458        })
2459    }
2460
2461    #[rstest]
2462    fn test_get_performance_stats_returns_vs_benchmark() {
2463        let mut analyzer = PortfolioAnalyzer::new();
2464        analyzer.register_statistic(Arc::new(BetaRatio::new()));
2465        analyzer.register_statistic(Arc::new(SharpeRatio::new(None)));
2466
2467        let one_day = 86_400_000_000_000_u64;
2468        let start = 1_600_000_000_000_000_000_u64;
2469        for (i, value) in [0.03, -0.01, 0.02, 0.04].iter().enumerate() {
2470            analyzer.add_return(UnixNanos::from(start + i as u64 * one_day), *value);
2471        }
2472
2473        let mut benchmark: Returns = BTreeMap::new();
2474        for (i, value) in [0.01, 0.005, 0.005, 0.01].iter().enumerate() {
2475            benchmark.insert(UnixNanos::from(start + i as u64 * one_day), *value);
2476        }
2477
2478        let stats = analyzer.get_performance_stats_returns_vs_benchmark(&benchmark);
2479
2480        // r = [0.03, -0.01, 0.02, 0.04], b = [0.01, 0.005, 0.005, 0.01]:
2481        //   mean_r = 0.02, mean_b = 0.0075
2482        //   Cov = 1.5e-4 / 3 = 5e-5, Var(b) = 2.5e-5 / 3 -> beta = 6.0
2483        // Only the benchmark-relative statistic contributes; SharpeRatio
2484        // returns None from the default and is skipped.
2485        assert_eq!(stats.len(), 1);
2486        assert!(approx_eq!(
2487            f64,
2488            *stats.get("Beta").unwrap(),
2489            6.0,
2490            epsilon = 1e-9
2491        ));
2492        assert!(!stats.contains_key("Sharpe Ratio (252 days)"));
2493    }
2494}