Skip to main content
Version: nightly

Analysis

The analysis subpackage groups components relating to trading performance statistics and analysis.

class CAGR

Bases: object

Calculates the Compound Annual Growth Rate (CAGR) for returns.

CAGR represents the mean annual growth rate of an investment over a specified period, assuming the profits were reinvested at the end of each period.

Formula: CAGR = (Ending Value / Beginning Value)^(Period/Days) - 1

For returns: CAGR = ((1 + Total Return)^(Period/Days)) - 1

calculate_from_returns(raw_returns)

name

class AvgLoser

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class AvgWinner

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class CalmarRatio

Bases: object

Calculates the Calmar Ratio for returns.

The Calmar Ratio is a function of the fund’s average compounded annual rate of return versus its maximum drawdown. The higher the Calmar ratio, the better it performed on a risk-adjusted basis during the given time frame.

Formula: Calmar Ratio = CAGR /

|Max Drawdown|

Reference: Young, T. W. (1991). “Calmar Ratio: A Smoother Tool”. Futures, 20(1).

calculate_from_returns(raw_returns)

name

class Expectancy

Bases: object

Calculates the expectancy of a trading strategy based on realized PnLs.

Expectancy is defined as: (Average Win × Win Rate) + (Average Loss × Loss Rate) This metric provides insight into the expected profitability per trade and helps evaluate the overall edge of a trading strategy.

A positive expectancy indicates a profitable system over time, while a negative expectancy suggests losses.

References

  • Tharp, V. K. (1998). Trade Your Way to Financial Freedom. McGraw-Hill.
  • Elder, A. (1993). Trading for a Living. John Wiley & Sons.
  • Vince, R. (1992). The Mathematics of Money Management. John Wiley & Sons.

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class GridLayout

Bases: Struct

Grid layout specification for tearsheet subplots.

  • Parameters:
    • rows (int , default 4) – Number of rows in the grid.
    • cols (int , default 2) – Number of columns in the grid.
    • heights (list *[*float ] , default *[*0.50 , 0.22 , 0.16 , 0.12 ]) – Relative heights for each row (must sum to 1.0 or be proportional).
    • vertical_spacing (float , default 0.10) – Vertical spacing between subplots (0.0 to 1.0).
    • horizontal_spacing (float , default 0.10) – Horizontal spacing between subplots (0.0 to 1.0).

cols : int

heights : list[float]

horizontal_spacing : float

rows : int

vertical_spacing : float

class LongRatio

Bases: object

calculate_from_positions(positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(_returns)

name

class MaxDrawdown

Bases: object

Calculates the Maximum Drawdown for returns.

Maximum Drawdown is the maximum observed loss from a peak to a trough, before a new peak is attained. It is an indicator of downside risk over a specified time period.

Formula: Max((Peak - Trough) / Peak) for all peak-trough sequences

calculate_from_returns(raw_returns)

name

class MaxLoser

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class MaxWinner

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(returns)

name

class MinLoser

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class MinWinner

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

class PortfolioAnalyzer

Bases: object

Provides a portfolio performance analyzer for tracking and generating performance metrics and statistics.

add_positions(positions: list[Position]) → None

Add positions data to the analyzer.

  • Parameters: positions (list [Position ]) – The positions for analysis.

add_return(timestamp: datetime, value: float) → None

Add return data to the analyzer.

  • Parameters:
    • timestamp (datetime) – The timestamp for the returns entry.
    • value (double) – The return value to add.

add_trade(position_id: PositionId, realized_pnl: Money) → None

Add trade data to the analyzer.

  • Parameters:
    • position_id (PositionId) – The position ID for the trade.
    • realized_pnl (Money) – The realized PnL for the trade.

calculate_statistics(account: Account, positions: list[Position]) → None

Calculate performance metrics from the given data.

  • Parameters:
    • account (Account) – The account for the calculations.
    • positions (list [Position ]) – The positions for the calculations.

property currencies : list[Currency]

Return the analyzed currencies.

deregister_statistic(statistic: PortfolioStatistic) → None

Deregister a statistic from the analyzer.

deregister_statistics() → None

Deregister all statistics from the analyzer.

get_performance_stats_general() → dict[str, Any]

Return the general performance statistics.

  • Return type: dict[str, Any]

get_performance_stats_pnls(currency: Currency | None = None, unrealized_pnl: Money | None = None) → dict[str, float]

Return the ‘PnL’ (profit and loss) performance statistics, optionally includes the unrealized PnL.

Money objects are converted to floats.

  • Parameters:
    • currency (Currency) – The currency for the performance.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the performance.
  • Return type: dict[str, Any]

get_performance_stats_returns() → dict[str, Any]

Return the return performance statistics values.

  • Return type: dict[str, Any]

get_stats_general_formatted() → list[str]

Return the performance statistics for returns from the last backtest run formatted for printing in the backtest run footer.

  • Return type: list[str]

get_stats_pnls_formatted(currency: Currency | None = None, unrealized_pnl: Money | None = None) → list[str]

Return the performance statistics from the last backtest run formatted for printing in the backtest run footer.

  • Parameters:
    • currency (Currency) – The currency for the performance.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the performance.
  • Return type: list[str]

get_stats_returns_formatted() → list[str]

Return the performance statistics for returns from the last backtest run formatted for printing in the backtest run footer.

  • Return type: list[str]

realized_pnls(currency: Currency | None = None) → Series | None

Return the realized PnL for the portfolio.

For multi-currency portfolios, specify the currency for the result.

  • Parameters: currency (Currency , optional) – The currency for the result.
  • Return type: pd.Series or None
  • Raises: ValueError – If currency is None when analyzing multi-currency portfolios.

register_statistic(statistic: PortfolioStatistic) → None

Register the given statistic with the analyzer.

reset() → None

Reset the analyzer.

All stateful fields are reset to their initial value.

returns() → Series

Return raw the returns data.

  • Return type: pd.Series

statistic(name: str) → PortfolioStatistic | None

Return the statistic with the given name (if found).

  • Return type: PortfolioStatistic or None

total_pnl(currency: Currency | None = None, unrealized_pnl: Money | None = None) → float

Return the total PnL for the portfolio.

For multi-currency portfolios, specify the currency for the result.

  • Parameters:
    • currency (Currency , optional) – The currency for the result.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the given currency.
  • Return type: float
  • Raises:
    • ValueError – If currency is None when analyzing multi-currency portfolios.
    • ValueError – If currency is not contained in the tracked account balances.
    • ValueError – If unrealized_pnl is not None and currency is not equal to the given currency.

total_pnl_percentage(currency: Currency | None = None, unrealized_pnl: Money | None = None) → float

Return the percentage change of the total PnL for the portfolio.

For multi-currency accounts, specify the currency for the result.

  • Parameters:
    • currency (Currency , optional) – The currency for the result.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the given currency.
  • Return type: float
  • Raises:
    • ValueError – If currency is None when analyzing multi-currency portfolios.
    • ValueError – If currency is not contained in the tracked account balances.
    • ValueError – If unrealized_pnl is not None and currency is not equal to the given currency.

class PortfolioStatistic

Bases: object

The base class for all portfolio performance statistics.

calculate_from_orders(orders: list[Order]) → Any | None

Calculate the statistic value from the given orders.

  • Parameters: orders (list [Order ]) – The positions to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_positions(positions: list[Position]) → Any | None

Calculate the statistic value from the given positions.

  • Parameters: positions (list [Position ]) – The positions to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_realized_pnls(realized_pnls: Series) → Any | None

Calculate the statistic value from the given raw realized PnLs.

  • Parameters: realized_pnls (pd.Series) – The raw PnLs for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_returns(returns: Series) → Any | None

Calculate the statistic value from the given raw returns.

  • Parameters: returns (pd.Series) – The returns to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

classmethod fully_qualified_name() → str

Return the fully qualified name for the PortfolioStatistic class.

  • Return type: str

property name : str

Return the name for the statistic.

  • Return type: str

class ProfitFactor

Bases: object

Calculates the profit factor based on portfolio returns.

Profit factor is defined as the ratio of gross profits to gross losses: Sum(Positive Returns) / Abs(Sum(Negative Returns))

A profit factor greater than 1.0 indicates a profitable strategy, while a factor less than 1.0 indicates losses exceed gains.

Generally:

  • 1.0-1.5: Modest profitability
  • 1.5-2.0: Good profitability
  • 2.0: Excellent profitability

References

  • Tharp, V. K. (1998). Trade Your Way to Financial Freedom. McGraw-Hill.
  • Kaufman, P. J. (2013). Trading Systems and Methods (5th ed.). Wiley.

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class ReportProvider

Bases: object

Provides various portfolio analysis reports.

static generate_account_report(account: Account) → DataFrame

Generate an account report for the given optional time range.

  • Parameters: account (Account) – The account for the report.
  • Return type: pd.DataFrame

static generate_fills_report(orders: list[Order]) → DataFrame

Generate a fills report.

This report provides a row per individual fill event.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_order_fills_report(orders: list[Order]) → DataFrame

Generate an order fills report.

This report provides a row per order.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_orders_report(orders: list[Order]) → DataFrame

Generate an orders report.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_positions_report(positions: list[Position], snapshots: list[Position] | None = None) → DataFrame

Generate a positions report.

  • Parameters:
    • positions (list [Position ]) – The positions for the report.
    • snapshots (list [Position ] , optional) – The position snapshots to include in the report. These will be marked with an ‘is_snapshot’ column.
  • Returns: The positions report.
  • Return type: pd.DataFrame

class ReturnsAverage

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class ReturnsAverageLoss

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class ReturnsAverageWin

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class ReturnsVolatility

Bases: object

Calculates the annualized volatility (standard deviation) of portfolio returns.

Volatility is calculated as the standard deviation of returns, annualized by multiplying the daily standard deviation by the square root of the period: Standard Deviation * sqrt(period)

Uses Bessel’s correction (ddof=1) for sample standard deviation. This provides a measure of the portfolio’s risk or uncertainty of returns.

References

  • CFA Institute Level I Curriculum: Quantitative Methods
  • Hull, J. C. (2018). Options, Futures, and Other Derivatives (10th ed.). Pearson.
  • Fabozzi, F. J., et al. (2002). The Handbook of Financial Instruments. Wiley.

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class RiskReturnRatio

Bases: object

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class SharpeRatio

Bases: object

Calculates the Sharpe ratio for portfolio returns.

The Sharpe ratio measures risk-adjusted return and is calculated as: (Mean Return - Risk-free Rate) / Standard Deviation of Returns * sqrt(period)

This implementation assumes a risk-free rate of 0 and annualizes the ratio using the square root of the specified period (default: 252 trading days).

References

  • Sharpe, W. F. (1966). “Mutual Fund Performance”. Journal of Business, 39(1), 119-138.
  • Sharpe, W. F. (1994). “The Sharpe Ratio”. Journal of Portfolio Management, 21(1), 49-58.
  • CFA Institute Investment Foundations, 3rd Edition

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class SortinoRatio

Bases: object

Calculates the Sortino ratio for portfolio returns.

The Sortino ratio is a variation of the Sharpe ratio that only penalizes downside volatility, making it more appropriate for strategies with asymmetric return distributions.

Formula: Mean Return / Downside Deviation * sqrt(period)

Where downside deviation is calculated as: sqrt(sum(negative_returns^2) / total_observations)

Note: Uses total observations count (not just negative returns) as per Sortino’s methodology.

References

  • Sortino, F. A., & van der Meer, R. (1991). “Downside Risk”. Journal of Portfolio Management, 17(4), 27-31.
  • Sortino, F. A., & Price, L. N. (1994). “Performance Measurement in a Downside Risk Framework”. Journal of Investing, 3(3), 59-64.

calculate_from_positions(_positions)

calculate_from_realized_pnls(_realized_pnls)

calculate_from_returns(raw_returns)

name

class TearsheetConfig

Bases: NautilusConfig

Configuration for tearsheet generation.

  • Parameters:
    • charts (list *[*str ] , default [ "stats_table" , "equity" , "drawdown" , "monthly_returns" , "distribution" , "rolling_sharpe" , "yearly_returns" ]) – List of chart names to include in the tearsheet. Available charts: “stats_table”, “equity”, “drawdown”, “monthly_returns”, “distribution”, “rolling_sharpe”, “yearly_returns”, “bars_with_fills”.
    • theme (str , default "plotly_white") – Theme name for visualization styling. Built-in themes: “plotly_white”, “plotly_dark”, “nautilus”.
    • layout (GridLayout | None , default None) – Custom grid layout specification. If None, auto-calculated based on charts.
    • title (str , default "NautilusTrader Backtest Results") – Title for the tearsheet.
    • include_benchmark (bool , default True) – Whether to include benchmark comparison in visualizations. Only applies when benchmark_returns data is provided.
    • benchmark_name (str , default "Benchmark") – Display name for the benchmark in visualizations.
    • height (PositiveInt , default 1500) – Total height of the tearsheet in pixels.
    • show_logo (bool , default True) – Whether to display NautilusTrader logo in the tearsheet.
    • chart_args (dict *[*str , dict *[*str , Any ] ] | None , default None) – Optional arguments to pass to specific charts. Keys are chart names, values are dictionaries of arguments for that chart. Example: {“bars_with_fills”: {“bar_type”: “ESM4.XCME-1-MINUTE-LAST-EXTERNAL”}}

benchmark_name : str

chart_args : dict[str, dict[str, Any]] | None

charts : list[str]

height : Annotated[int, msgspec.Meta(gt=0)]

include_benchmark : bool

layout : GridLayout | None

show_logo : bool

theme : str

title : str

class WinRate

Bases: object

Calculates the win rate of a trading strategy based on realized PnLs.

Win rate is the percentage of profitable trades out of total trades: Count(Trades with PnL > 0) / Total Trades

Returns a value between 0.0 and 1.0, where 1.0 represents 100% winning trades.

Note: While a high win rate is desirable, it should be considered alongside average win/loss sizes and profit factor for complete system evaluation.

References

  • Standard trading performance metric across the industry
  • Tharp, V. K. (1998). Trade Your Way to Financial Freedom. McGraw-Hill.
  • Kaufman, P. J. (2013). Trading Systems and Methods (5th ed.). Wiley.

calculate_from_positions(_positions)

calculate_from_realized_pnls(realized_pnls)

calculate_from_returns(_returns)

name

create_drawdown_chart(returns: Series, output_path: str | None = None, title: str = 'Drawdown', theme: str = 'plotly_white') → Figure

Create an interactive drawdown chart.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Drawdown") – Plot title.
    • theme (str , default "plotly_white") – Theme name for styling.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

create_equity_curve(returns: Series, output_path: str | None = None, title: str = 'Equity Curve', benchmark_returns: Series | None = None, benchmark_name: str = 'Benchmark') → Figure

Create an interactive equity curve plot with optional benchmark overlay.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Equity Curve") – Plot title.
    • benchmark_returns (pd.Series , optional) – Benchmark returns series for comparison. If provided, benchmark equity curve will be overlaid on the chart.
    • benchmark_name (str , default "Benchmark") – Display name for the benchmark in the legend.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

create_monthly_returns_heatmap(returns: Series, output_path: str | None = None, title: str = 'Monthly Returns (%)') → Figure

Create an interactive monthly returns heatmap.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Monthly Returns ( % ) ") – Plot title.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

create_returns_distribution(returns: Series, output_path: str | None = None, title: str = 'Returns Distribution') → Figure

Create an interactive returns distribution histogram.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Returns Distribution") – Plot title.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

create_rolling_sharpe(returns: Series, window: int = 60, output_path: str | None = None, title: str = 'Rolling Sharpe Ratio (60-day)') → Figure

Create an interactive rolling Sharpe ratio chart.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • window (int , default 60) – Rolling window size in days.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Rolling Sharpe Ratio *(*60-day ) ") – Plot title.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

create_tearsheet(engine: BacktestEngine, output_path: str | None = 'tearsheet.html', title: str = 'NautilusTrader Backtest Results', currency=None, config=None, benchmark_returns: pd.Series | None = None, benchmark_name: str = 'Benchmark') → str | None

Generate an interactive HTML tearsheet from backtest results.

  • Parameters:
    • engine (BacktestEngine) – The backtest engine with completed run.
    • output_path (str , optional) – Path to save HTML tearsheet. If None, returns HTML string.
    • title (str , default "NautilusTrader Backtest Results") – Title for the tearsheet.
    • currency (Currency , optional) – Currency for PnL statistics. If None, uses first available currency.
    • config (TearsheetConfig , optional) – Configuration for tearsheet customization. If None, uses default configuration.
    • benchmark_returns (pd.Series , optional) – Benchmark returns series for comparison. If provided, benchmark will be overlaid on visualizations.
    • benchmark_name (str , default "Benchmark") – Display name for the benchmark.
  • Returns: HTML string if output_path is None, otherwise None.
  • Return type: str or None
  • Raises: ImportError – If plotly is not installed.

create_tearsheet_from_stats(stats_pnls: dict[str, Any] | dict[str, dict[str, Any]], stats_returns: dict[str, Any], stats_general: dict[str, Any], returns: Series, output_path: str | None = 'tearsheet.html', title: str = 'NautilusTrader Backtest Results', config=None, benchmark_returns: Series | None = None, benchmark_name: str = 'Benchmark', run_info: dict[str, Any] | None = None, account_info: dict[str, Any] | None = None, engine=None) → str | None

Generate an interactive HTML tearsheet from precomputed statistics.

This lower-level API is useful for offline analysis when you have precomputed statistics and don’t want to pass an engine.

  • Parameters:
    • stats_pnls (dict *[*str , Any ]) – PnL-based statistics from analyzer.
    • stats_returns (dict *[*str , Any ]) – Returns-based statistics from analyzer.
    • stats_general (dict *[*str , Any ]) – General statistics from analyzer.
    • returns (pd.Series) – Returns series from analyzer.
    • output_path (str , optional) – Path to save HTML tearsheet. If None, returns HTML string.
    • title (str , default "NautilusTrader Backtest Results") – Title for the tearsheet.
    • config (TearsheetConfig , optional) – Configuration for tearsheet customization. If None, uses default configuration.
    • benchmark_returns (pd.Series , optional) – Benchmark returns series for comparison. If provided, benchmark will be overlaid on visualizations.
    • benchmark_name (str , default "Benchmark") – Display name for the benchmark.
    • run_info (dict *[*str , Any ] , optional) – Run metadata (run ID, timestamps, backtest period, event counts).
    • account_info (dict *[*str , Any ] , optional) – Account information (starting/ending balances per currency).
    • engine (BacktestEngine , optional) – The backtest engine. Required for charts that need engine access (e.g., bars_with_fills).
  • Returns: HTML string if output_path is None, otherwise None.
  • Return type: str or None
  • Raises: ImportError – If plotly is not installed.

create_yearly_returns(returns: Series, output_path: str | None = None, title: str = 'Yearly Returns') → Figure

Create an interactive yearly returns bar chart.

  • Parameters:
    • returns (pd.Series) – Returns series from portfolio analyzer.
    • output_path (str , optional) – Path to save HTML plot. If None, plot is not saved.
    • title (str , default "Yearly Returns") – Plot title.
  • Returns: Plotly figure object.
  • Return type: go.Figure
  • Raises: ImportError – If plotly is not installed.

get_chart(name: str) → Callable

Get registered chart function by name.

  • Parameters: name (str) – The chart name.
  • Returns: The chart function.
  • Return type: Callable
  • Raises: KeyError – If the chart name is not registered.

get_theme(name: str) → dict[str, Any]

Get theme configuration by name.

  • Parameters: name (str) – The theme name. Built-in themes: “plotly_white”, “plotly_dark”, “nautilus”.
  • Returns: Theme configuration dictionary with “template” and “colors” keys.
  • Return type: dict[str, Any]
  • Raises: KeyError – If the theme name is not registered.

list_charts() → list[str]

List all registered chart names.

  • Returns: List of available chart names.
  • Return type: list[str]

list_themes() → list[str]

List all registered theme names.

  • Returns: List of available theme names.
  • Return type: list[str]

register_chart(name: str, func: Callable | None = None) → Callable | None

Register a custom chart function for use in tearsheets.

Can be used as a decorator or called directly.

  • Parameters:
    • name (str) – The chart name for reference in TearsheetConfig.charts list.

    • func (Callable , optional) – Chart function that returns a plotly Figure. Should accept (returns: pd.Series,

      **

      kwargs) as parameters. If None, returns a decorator.

  • Returns: The decorated function if used as a decorator, otherwise None.
  • Return type: Callable or None
  • Raises: ValueError – If name is empty or func is not callable.

register_theme(name: str, template: str, colors: dict[str, str]) → None

Register a custom theme.

  • Parameters:
    • name (str) – The theme name for future reference.
    • template (str) – Plotly template name (e.g., “plotly_white”, “plotly_dark”, “ggplot2”).
    • colors (dict *[*str , str ]) – Color palette dictionary. Expected keys: “primary”, “positive”, “negative”, “neutral”, “background”, “grid”. All values should be hex color codes.
  • Raises: ValueError – If name is empty or colors dict is missing required keys.

class PortfolioAnalyzer

Bases: object

Provides a portfolio performance analyzer for tracking and generating performance metrics and statistics.

register_statistic(statistic: PortfolioStatistic) → None

Register the given statistic with the analyzer.

deregister_statistic(statistic: PortfolioStatistic) → None

Deregister a statistic from the analyzer.

deregister_statistics() → None

Deregister all statistics from the analyzer.

reset() → None

Reset the analyzer.

All stateful fields are reset to their initial value.

property currencies : list[Currency]

Return the analyzed currencies.

statistic(name: str) → PortfolioStatistic | None

Return the statistic with the given name (if found).

  • Return type: PortfolioStatistic or None

returns() → Series

Return raw the returns data.

  • Return type: pd.Series

calculate_statistics(account: Account, positions: list[Position]) → None

Calculate performance metrics from the given data.

  • Parameters:
    • account (Account) – The account for the calculations.
    • positions (list [Position ]) – The positions for the calculations.

add_positions(positions: list[Position]) → None

Add positions data to the analyzer.

  • Parameters: positions (list [Position ]) – The positions for analysis.

add_trade(position_id: PositionId, realized_pnl: Money) → None

Add trade data to the analyzer.

  • Parameters:
    • position_id (PositionId) – The position ID for the trade.
    • realized_pnl (Money) – The realized PnL for the trade.

add_return(timestamp: datetime, value: float) → None

Add return data to the analyzer.

  • Parameters:
    • timestamp (datetime) – The timestamp for the returns entry.
    • value (double) – The return value to add.

realized_pnls(currency: Currency | None = None) → Series | None

Return the realized PnL for the portfolio.

For multi-currency portfolios, specify the currency for the result.

  • Parameters: currency (Currency , optional) – The currency for the result.
  • Return type: pd.Series or None
  • Raises: ValueError – If currency is None when analyzing multi-currency portfolios.

total_pnl(currency: Currency | None = None, unrealized_pnl: Money | None = None) → float

Return the total PnL for the portfolio.

For multi-currency portfolios, specify the currency for the result.

  • Parameters:
    • currency (Currency , optional) – The currency for the result.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the given currency.
  • Return type: float
  • Raises:
    • ValueError – If currency is None when analyzing multi-currency portfolios.
    • ValueError – If currency is not contained in the tracked account balances.
    • ValueError – If unrealized_pnl is not None and currency is not equal to the given currency.

total_pnl_percentage(currency: Currency | None = None, unrealized_pnl: Money | None = None) → float

Return the percentage change of the total PnL for the portfolio.

For multi-currency accounts, specify the currency for the result.

  • Parameters:
    • currency (Currency , optional) – The currency for the result.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the given currency.
  • Return type: float
  • Raises:
    • ValueError – If currency is None when analyzing multi-currency portfolios.
    • ValueError – If currency is not contained in the tracked account balances.
    • ValueError – If unrealized_pnl is not None and currency is not equal to the given currency.

get_performance_stats_pnls(currency: Currency | None = None, unrealized_pnl: Money | None = None) → dict[str, float]

Return the ‘PnL’ (profit and loss) performance statistics, optionally includes the unrealized PnL.

Money objects are converted to floats.

  • Parameters:
    • currency (Currency) – The currency for the performance.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the performance.
  • Return type: dict[str, Any]

get_performance_stats_returns() → dict[str, Any]

Return the return performance statistics values.

  • Return type: dict[str, Any]

get_performance_stats_general() → dict[str, Any]

Return the general performance statistics.

  • Return type: dict[str, Any]

get_stats_pnls_formatted(currency: Currency | None = None, unrealized_pnl: Money | None = None) → list[str]

Return the performance statistics from the last backtest run formatted for printing in the backtest run footer.

  • Parameters:
    • currency (Currency) – The currency for the performance.
    • unrealized_pnl (Money , optional) – The unrealized PnL for the performance.
  • Return type: list[str]

get_stats_returns_formatted() → list[str]

Return the performance statistics for returns from the last backtest run formatted for printing in the backtest run footer.

  • Return type: list[str]

get_stats_general_formatted() → list[str]

Return the performance statistics for returns from the last backtest run formatted for printing in the backtest run footer.

  • Return type: list[str]

class ReportProvider

Bases: object

Provides various portfolio analysis reports.

static generate_orders_report(orders: list[Order]) → DataFrame

Generate an orders report.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_order_fills_report(orders: list[Order]) → DataFrame

Generate an order fills report.

This report provides a row per order.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_fills_report(orders: list[Order]) → DataFrame

Generate a fills report.

This report provides a row per individual fill event.

  • Parameters: orders (list [Order ]) – The orders for the report.
  • Return type: pd.DataFrame

static generate_positions_report(positions: list[Position], snapshots: list[Position] | None = None) → DataFrame

Generate a positions report.

  • Parameters:
    • positions (list [Position ]) – The positions for the report.
    • snapshots (list [Position ] , optional) – The position snapshots to include in the report. These will be marked with an ‘is_snapshot’ column.
  • Returns: The positions report.
  • Return type: pd.DataFrame

static generate_account_report(account: Account) → DataFrame

Generate an account report for the given optional time range.

  • Parameters: account (Account) – The account for the report.
  • Return type: pd.DataFrame

class PortfolioStatistic

Bases: object

The base class for all portfolio performance statistics.

classmethod fully_qualified_name() → str

Return the fully qualified name for the PortfolioStatistic class.

  • Return type: str

property name : str

Return the name for the statistic.

  • Return type: str

calculate_from_returns(returns: Series) → Any | None

Calculate the statistic value from the given raw returns.

  • Parameters: returns (pd.Series) – The returns to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_realized_pnls(realized_pnls: Series) → Any | None

Calculate the statistic value from the given raw realized PnLs.

  • Parameters: realized_pnls (pd.Series) – The raw PnLs for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_orders(orders: list[Order]) → Any | None

Calculate the statistic value from the given orders.

  • Parameters: orders (list [Order ]) – The positions to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None

calculate_from_positions(positions: list[Position]) → Any | None

Calculate the statistic value from the given positions.

  • Parameters: positions (list [Position ]) – The positions to use for the calculation.
  • Returns: A JSON serializable primitive.
  • Return type: Any or None