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.
- Return type: list[Currency]
 
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:
 - 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:
 - 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 
Nonewhen analyzing multi-currency portfolios. 
register_statistic(statistic: PortfolioStatistic) → None
Register the given statistic with the analyzer.
- Parameters: statistic (PortfolioStatistic) – The statistic to register.
 
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:
 - Return type: float
 - Raises:
- ValueError – If currency is 
Nonewhen analyzing multi-currency portfolios. - ValueError – If currency is not contained in the tracked account balances.
 - ValueError – If unrealized_pnl is not 
Noneand currency is not equal to the given currency. 
 - ValueError – If currency is 
 
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:
 - Return type: float
 - Raises:
- ValueError – If currency is 
Nonewhen analyzing multi-currency portfolios. - ValueError – If currency is not contained in the tracked account balances.
 - ValueError – If unrealized_pnl is not 
Noneand currency is not equal to the given currency. 
 - ValueError – If currency is 
 
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:
 - 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