Analysis
The analysis subpackage groups components relating to trading performance statistics and analysis.
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 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 LongRatio
Bases: object
calculate_from_positions(positions)
calculate_from_realized_pnls(_realized_pnls)
calculate_from_returns(_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
None
when 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
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.
- 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
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.
- 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
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 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
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.
- Parameters: statistic (PortfolioStatistic) – The statistic to register.
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.
- Return type: list[Currency]
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:
- 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.
- 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
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.
- ValueError – If currency is
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_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:
- 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:
- 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