投资组合
We are currently working on this concept 指南.
The 投资组合 serves as the central hub for managing and tracking all 头寸 across active 策略 for the trading 节点 or backtest. It consolidates position 数据 from multiple 金融工具, providing a unified view of your holdings, risk exposure, and overall 性能. Explore this section to understand how NautilusTrader aggregates and updates 投资组合 state to 支持 effective trading and 风险管理.
投资组合 Statistics
There are a variety of built-in portfolio statistics which are used to analyse a trading portfolios 性能 for both backtests and 实时交易.
The statistics are generally categorized as follows.
- PnLs based statistics (per currency)
- Returns based statistics
- 头寸 based statistics
- 订单 based statistics
It's also possible to call a traders PortfolioAnalyzer
and calculate statistics at any arbitrary
time, including during a backtest, or 实时交易 session.
Custom Statistics
Custom 投资组合 statistics can be defined by inheriting from the PortfolioStatistic
base class, and implementing any of the calculate_
methods.
For example, the following is the 实现 for the built-in WinRate
statistic:
import pandas as pd
from typing import Any
from nautilus_trader.analysis.statistic import PortfolioStatistic
class WinRate(PortfolioStatistic):
"""
Calculates the win rate from a realized PnLs series.
"""
def calculate_from_realized_pnls(self, realized_pnls: pd.Series) -> Any | None:
# Preconditions
if realized_pnls is None or realized_pnls.empty:
return 0.0
# Calculate statistic
winners = [x for x in realized_pnls if x > 0.0]
losers = [x for x in realized_pnls if x <= 0.0]
return len(winners) / float(max(1, (len(winners) + len(losers))))
These statistics can then be registered with a traders PortfolioAnalyzer
.
stat = WinRate()
# Register with the portfolio analyzer
engine.portfolio.analyzer.register_statistic(stat)
:::info
See the `PortfolioAnalyzer` [API Reference](../api_reference/analysis.md#class-portfolioanalyzer) for details on available methods.
:::
Ensure your statistic is robust to degenerate inputs such as None
, empty series, or insufficient 数据.
The expectation is that you would then return None
, NaN or a reasonable default.
Backtest Analysis
Following a backtest run, a 性能 analysis will be carried out by passing realized PnLs, returns, 头寸 and 订单 数据 to each registered
statistic in turn, calculating their values (with a default 配置). Any output is then displayed in the tear sheet
under the 投资组合 性能
heading, grouped as.
- Realized PnL statistics (per currency)
- Returns statistics (for the entire 投资组合)
- General statistics derived from position and order 数据 (for the entire 投资组合)