Skip to main content

PortfolioAnalyzer

Struct PortfolioAnalyzer 

Source
#[repr(C)]
pub struct PortfolioAnalyzer { pub statistics: AHashMap<String, Statistic>, pub account_balances_starting: IndexMap<Currency, Money>, pub account_balances: IndexMap<Currency, Money>, pub positions: Vec<Position>, pub realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>, pub recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>, pub position_returns: Returns, pub portfolio_returns: Returns, pub returns: Returns, }
Expand description

Analyzes portfolio performance and calculates various statistics.

The PortfolioAnalyzer tracks account balances, positions, and realized PnLs to provide portfolio analysis including returns, PnL calculations, and customizable statistics.

Fields§

§statistics: AHashMap<String, Statistic>§account_balances_starting: IndexMap<Currency, Money>§account_balances: IndexMap<Currency, Money>§positions: Vec<Position>§realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>§recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>§position_returns: Returns§portfolio_returns: Returns§returns: Returns

Alias for the primary returns source.

Contains portfolio returns when available, otherwise position returns. Kept as a public field for API stability; prefer the returns() accessor.

Implementations§

Source§

impl PortfolioAnalyzer

Source

pub fn new() -> Self

Creates a new PortfolioAnalyzer instance.

Starts with empty state.

Source

pub fn register_statistic(&mut self, statistic: Statistic)

Registers a new portfolio statistic for calculation.

Source

pub fn deregister_statistic(&mut self, statistic: &Statistic)

Removes a specific statistic from calculation.

Source

pub fn deregister_statistics(&mut self)

Removes all registered statistics.

Source

pub fn reset(&mut self)

Resets all analysis data to initial state.

Source

pub fn currencies(&self) -> Vec<&Currency>

Returns all tracked currencies.

Source

pub fn statistic(&self, name: &str) -> Option<&Statistic>

Retrieves a specific statistic by name.

Source

pub const fn returns(&self) -> &Returns

Returns the primary calculated returns.

This returns portfolio returns when available, otherwise it falls back to position returns for backward compatibility.

Source

pub const fn position_returns(&self) -> &Returns

Returns the per-position calculated returns.

Source

pub const fn portfolio_returns(&self) -> &Returns

Returns the portfolio calculated returns.

Source

pub fn calculate_statistics( &mut self, account: &dyn Account, positions: &[Position], )

Calculates statistics based on account and position data.

This clears calculated state before calculating, while preserving close-time PnLs recorded during portfolio processing.

Source

pub fn from_accounts( accounts: &[AccountAny], positions: &[Position], snapshots: &[Position], recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>, ) -> Self

Builds a populated analyzer from venue accounts and positions.

Aggregates starting and total balances across all accounts, adds positions and snapshots, and seeds recorded_realized_pnls (close-time PnLs observed during the run).

Source

pub fn from_accounts_with_snapshots<'a>( accounts: &[AccountAny], positions: &[Position], position_snapshots: &[Position], portfolio_snapshots: impl IntoIterator<Item = &'a PortfolioSnapshot>, recorded_realized_pnls: AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>>, ) -> Self

Builds a populated analyzer from accounts, positions, and portfolio snapshots.

Portfolio returns use daily mark-to-market equity when at least two UTC dates are available and every account resolves to one common currency. Otherwise the primary returns source falls back to position returns.

Source

pub fn set_portfolio_returns_from_snapshots<'a>( &mut self, account_ids: &[AccountId], snapshots: impl IntoIterator<Item = &'a PortfolioSnapshot>, )

Replaces the primary returns source with snapshot-backed portfolio returns when resolvable.

Source

pub fn statistics(&self) -> PortfolioStatistics

Collects an owned PortfolioStatistics snapshot from the current analyzer state.

Source

pub fn add_positions(&mut self, positions: &[Position])

Adds new positions for analysis.

Source

pub fn add_trade( &mut self, position_id: &PositionId, ts_event: UnixNanos, pnl: &Money, )

Records a trade’s PnL realized at ts_event.

Source

pub fn record_trade( &mut self, position_id: &PositionId, ts_event: UnixNanos, pnl: &Money, )

Records a trade’s PnL realized at ts_event, observed during portfolio processing.

Source

pub fn add_position_return(&mut self, timestamp: UnixNanos, value: f64)

Records a position return at a specific timestamp.

Source

pub fn add_return(&mut self, timestamp: UnixNanos, value: f64)

Records a return at a specific timestamp.

This is a backward-compatible alias for Self::add_position_return.

Source

pub fn trade_pnl_records( &self, currency: Option<&Currency>, ) -> Option<Vec<(PositionId, UnixNanos, f64)>>

Retrieves trade PnL records for a specific currency.

Each record is (position_id, ts_event, realized_pnl), where ts_event is the position’s last event time (the close time for closed cycles). Duplicate position IDs are preserved for NETTING position cycles.

Native PnLs (derived from analyzed positions) and PnLs recorded live during portfolio processing are merged per cycle: a native record is excluded only when a recorded record shares its (position_id, ts_event). Recorded values therefore take precedence for the cycles they cover, while native cycles that were never recorded are retained rather than dropped by position ID.

Returns None if no PnLs exist, or if multiple currencies exist without an explicit currency specified.

Source

pub fn realized_pnls( &self, currency: Option<&Currency>, ) -> Option<Vec<(PositionId, UnixNanos, f64)>>

Retrieves realized PnLs for a specific currency.

Each record is (position_id, ts_event, realized_pnl). Returns None if no PnLs exist, or if multiple currencies exist without an explicit currency specified.

Source

pub fn total_pnl( &self, currency: Option<&Currency>, unrealized_pnl: Option<&Money>, ) -> Result<f64, &'static str>

Calculates total PnL including unrealized PnL if provided.

§Errors

Returns an error if:

  • No currency is specified in a multi-currency portfolio.
  • The specified currency is not found in account balances.
  • The unrealized PnL currency does not match the specified currency.
Source

pub fn total_pnl_percentage( &self, currency: Option<&Currency>, unrealized_pnl: Option<&Money>, ) -> Result<f64, &'static str>

Calculates total PnL as a percentage of starting balance.

§Errors

Returns an error if:

  • No currency is specified in a multi-currency portfolio.
  • The specified currency is not found in account balances.
  • The unrealized PnL currency does not match the specified currency.
Source

pub fn get_performance_stats_pnls( &self, currency: Option<&Currency>, unrealized_pnl: Option<&Money>, ) -> Result<AHashMap<String, f64>, &'static str>

Gets all PnL-related performance statistics.

§Errors

Returns an error if PnL calculations fail, for example due to:

  • No currency specified for a multi-currency portfolio.
  • Unrealized PnL currency not matching the specified currency.
  • Specified currency not found in account balances.
Source

pub fn get_performance_stats_returns(&self) -> AHashMap<String, f64>

Gets all return-based performance statistics.

Source

pub fn get_performance_stats_position_returns(&self) -> AHashMap<String, f64>

Gets all position-return-based performance statistics.

Source

pub fn get_performance_stats_portfolio_returns(&self) -> AHashMap<String, f64>

Gets all portfolio-return-based performance statistics.

Source

pub fn get_performance_stats_returns_vs_benchmark( &self, benchmark: &Returns, ) -> AHashMap<String, f64>

Gets all benchmark-relative return statistics for the primary returns.

This is stateless: the benchmark series is supplied by the caller rather than stored on the analyzer. Only statistics that override PortfolioStatistic::calculate_from_returns_with_benchmark (the benchmark-relative statistics) contribute values; all others return None and are skipped.

Source

pub fn get_performance_stats_general(&self) -> AHashMap<String, f64>

Gets general portfolio statistics.

Source

pub fn get_stats_pnls_formatted( &self, currency: Option<&Currency>, unrealized_pnl: Option<&Money>, ) -> Result<Vec<String>, String>

Gets formatted PnL statistics as strings.

§Errors

Returns an error if PnL statistics calculation fails.

Source

pub fn get_stats_returns_formatted(&self) -> Vec<String>

Gets formatted return statistics as strings.

Source

pub fn get_stats_position_returns_formatted(&self) -> Vec<String>

Gets formatted position-return statistics as strings.

Source

pub fn get_stats_portfolio_returns_formatted(&self) -> Vec<String>

Gets formatted portfolio-return statistics as strings.

Source

pub fn get_stats_general_formatted(&self) -> Vec<String>

Gets formatted general statistics as strings.

Trait Implementations§

Source§

impl Debug for PortfolioAnalyzer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for PortfolioAnalyzer

Source§

fn default() -> Self

Creates a new default PortfolioAnalyzer instance.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.