pybroker.portfolio 模块

包含与投资组合相关的功能,例如投资组合指标和下单。

class Entry(id: int, date: ~numpy.datetime64, symbol: str, shares: ~decimal.Decimal, price: ~decimal.Decimal, type: ~typing.Literal['long', 'short'], bars: int = 0, sym_bars: int = 0, stops: list[~pybroker.portfolio.Stop] = <factory>, mae: ~decimal.Decimal = <factory>, mfe: ~decimal.Decimal = <factory>)[源代码]

基类:object

包含 Position 一次入场的相关信息。

id

唯一标识符。

类型:

int

date

该次入场的日期。

类型:

numpy.datetime64

symbol

该次入场的品种代码。

类型:

str

shares

股数。

类型:

decimal.Decimal

price

该次入场的股价。

类型:

decimal.Decimal

type

Position 的类型,为 longshort

类型:

Literal['long', 'short']

bars

自入场以来经过的当前 K 线数,按投资组合的时钟计算:即回测的每一根 K 线,无论 symbol 在该根 K 线上是否交易。用于 Trade.barspnl_per_bar,衡量已经过的持仓时间。

类型:

int

sym_bars

自入场以来 symbol 自身 K 线的当前数量。仅在 symbol 存在 K 线的日期才递增,因此与 pybroker.context.ExecContext.bars 所报告的一致。pybroker.common.StopType.BAR 止损正是以此计数:当各品种的交易日历参差不齐时,bars 会使 hold_bars 止损在该品种自身 K 线数少于调用方所要求的数量时就已到期。

类型:

int

stops

设置在该次入场上的止损。

类型:

list[pybroker.portfolio.Stop]

mae

最大不利变动(Maximum Adverse Excursion,MAE)。

类型:

decimal.Decimal

mfe

最大有利变动(Maximum Favorable Excursion,MFE)。

类型:

decimal.Decimal

class Order(id: int, type: Literal['buy', 'sell'], symbol: str, date: datetime64, created: datetime64 | None, order_type: Literal['market', 'limit', 'stop_bar', 'stop_loss', 'stop_profit', 'stop_trailing'], intent: Literal['buy_to_open', 'buy_to_close', 'sell_to_open', 'sell_to_close'], shares: Decimal, limit_price: Decimal | None, market_price: Decimal, fill_price: Decimal, fees: Decimal)[源代码]

基类:NamedTuple

保存已成交订单的相关信息。

id

唯一标识符。

类型:

int

type

订单类型,为 buysell

类型:

Literal['buy', 'sell']

symbol

该订单的股票代码。

类型:

str

date

订单成交的日期。

类型:

numpy.datetime64

created

订单信号生成的日期;对于由止损触发的订单则为 None

类型:

numpy.datetime64 | None

order_type

订单的来源,为 marketlimitstop_barstop_lossstop_profitstop_trailing 之一。

类型:

Literal['market', 'limit', 'stop_bar', 'stop_loss', 'stop_profit', 'stop_trailing']

intent

仓位意图,为 buy_to_openbuy_to_closesell_to_opensell_to_close 之一。

类型:

Literal['buy_to_open', 'buy_to_close', 'sell_to_open', 'sell_to_close']

shares

买入或卖出的股数。

类型:

decimal.Decimal

limit_price

该订单使用的限价。

类型:

decimal.Decimal | None

market_price

订单成交时的现行市场价格,未经过任何成交时滑点调整。当未设置滑点模型时等于 fill_price

类型:

decimal.Decimal

fill_price

该订单的成交价格。

类型:

decimal.Decimal

fees

该订单的经纪商手续费。

类型:

decimal.Decimal

class Portfolio(cash: float, fee_mode: FeeMode | Callable[[FeeInfo], Decimal] | None = None, fee_amount: float | None = None, enable_fractional_shares: bool = False, position_mode: PositionMode = PositionMode.DEFAULT, max_long_positions: int | None = None, max_short_positions: int | None = None, record_stops: bool | None = False, leverage: float = 1.0, interest_rate: float = 0.0, bars_per_year: int | None = None, record_portfolio_bars: bool = False, record_position_bars: bool = False)[源代码]

基类:object

表示持仓投资组合的类。该投资组合包含未平仓头寸和余额的相关信息,也用于下达买入和卖出订单。

参数:
  • cash -- 起始现金余额。

  • fee_mode -- 经纪商手续费模式。

  • fee_amount -- 经纪商手续费金额。

  • enable_fractional_shares -- 是否启用碎股(fractional shares)交易。

  • position_mode -- Portfolio 的仓位模式。

  • max_long_positions -- 同一时间可持有的最大多头 Position数量。如果为 None,则不限。

  • max_short_positions -- 同一时间可持有的最大空头 Position数量。如果为 None,则不限。

  • record_stops -- 是否按 K 线记录止损数据。

cash

当前现金余额。

equity

当前权益金额,定义为净现金余额加上所有未平仓多头仓位的市值,再加上所有未平仓空头仓位所占用的抵押品。空头仓位按成本计价,因此不包含其未实现盈亏。

market_value

当前市值。市值定义为 equity 加上所有未平仓空头仓位的未实现盈亏。

fees

当前经纪商手续费。

fee_amount

经纪商手续费金额。

enable_fractional_shares

是否启用碎股(fractional shares)交易。

orders

所有已成交订单组成的 deque,按时间先后升序排列。

margin

未平仓空头仓位按市值计算的名义敞口。

margin_loan

用于多头和空头杠杆仓位的借入资金。

pnl

已实现盈亏(PnL)。

long_positions

将股票代码映射到未平仓多头 Positiondict

short_positions

将股票代码映射到未平仓空头 Positiondict

symbols

当前所有未平仓头寸的股票代码。

bars

每根 K 线上 Portfolio 状态快照组成的 deque,按时间先后升序排列。

position_bars

每根 K 线上 Position 状态快照组成的 deque,按时间先后升序排列。

win_rate

交易的滚动胜率。

loss_rate

交易的滚动败率。

buy(date: datetime64, symbol: str, shares: Decimal, fill_price: Decimal, limit_price: Decimal | None = None, stops: Iterable[Stop] | None = None, created: datetime64 | None = None, order_type: OrderType = OrderType.MARKET, market_price: Decimal | None = None) Order | None[源代码]

下达一笔买入订单。

参数:
  • date -- Order 下达的日期。

  • symbol -- 要买入的股票代码。

  • shares -- 要买入的股数。

  • fill_price -- 如果成交,用于成交该 Order 的价格。

  • limit_price -- Order 的限价。

  • stops -- 如果成交,要在由该 Order 创建的 Entry 上设置的 Stop

  • created -- 订单信号生成的日期。

  • order_type -- 订单的来源。

  • market_price -- 成交时的市场价格,未经过成交时滑点调整。默认为 fill_price

返回:

如果订单已成交则为 Order,否则为 None

capture_bar(date: datetime64, col_scope: ColumnScope, sym_end_index: Mapping[str, int], price_scope: PriceScope | None = None)[源代码]

捕获当前 K 线的投资组合状态。

check_stops(date: datetime64, price_scope: PriceScope, col_scope: ColumnScope | None = None, sym_end_index: Mapping[str, int] | None = None, ind_scope: IndicatorScope | None = None, slippage_model: SlippageModel | None = None)[源代码]

检查止损是否被触发。

同一入场上的价格止损按 Stop.id 升序进行评估,第一个触发的止损会平掉该入场。这些 id 是在 pybroker.context.ExecContext.to_result() 构建止损时按固定顺序分配的 —— 依次为止损、止盈、移动止损 —— 而不是按属性在上下文中被赋值的顺序,因此优先级是确定的,但不受调用方控制。

pybroker.common.StopType.BAR 止损会在价格止损之后评估,无论其 id 为何,因为 K 线计数离场和价格离场若落在同一根 K 线上,二者并无真正的先后顺序:这取决于该 K 线内部的价格走势,而这里并未对此建模。

当设置了 slippage_model 时,被触发的止损会以调整后的价格成交。滑点绝不会影响止损是否触发,且股数调整会被忽略,因为止损会全部平掉该次入场。

exit_position(date: datetime64, symbol: str, buy_fill_price: Decimal, sell_fill_price: Decimal, col_scope: ColumnScope | None = None, ind_scope: IndicatorScope | None = None, sym_end_index: Mapping[str, int] | None = None, slippage_model: SlippageModel | None = None)[源代码]

buy_fill_pricesell_fill_price 平掉 symbol 的所有多头和空头仓位。

当设置了 slippage_model 时,两笔成交都会经过该模型调整。股数调整会被忽略,因为仓位是全部平掉的。未经调整的价格会作为 market_price 记录在生成的 Order上。

incr_bars(date: datetime64 | None = None, price_scope: PriceScope | None = None)[源代码]

为每一笔交易入场的持仓 K 线数递增。

Entry.bars 会在回测的每根 K 线上递增。当提供了 dateprice_scope 时,Entry.sym_bars 只会在该入场品种自身存在 K 线的日期上递增,这正是 pybroker.common.StopType.BAR 止损所依据的计数。若未提供这两个参数,两个计数器会一同递增,相当于假设每个品种在每根 K 线上都有交易。

remove_stop(stop_id: int) bool[源代码]

移除 stop_id 对应的 Stop

remove_stops(val: str | Position | Entry, stop_type: StopType | None = None)[源代码]

移除 Stop

参数:
sell(date: datetime64, symbol: str, shares: Decimal, fill_price: Decimal, limit_price: Decimal | None = None, stops: Iterable[Stop] | None = None, created: datetime64 | None = None, order_type: OrderType = OrderType.MARKET, market_price: Decimal | None = None) Order | None[源代码]

下达一笔卖出订单。

参数:
  • date -- Order 下达的日期。

  • symbol -- 要卖出的股票代码。

  • shares -- 要卖出的股数。

  • fill_price -- 如果成交,用于成交该 Order 的价格。

  • limit_price -- Order 的限价。

  • stops -- 如果成交,要在由该 Order 创建的 Entry 上设置的 Stop

  • created -- 订单信号生成的日期。

  • order_type -- 订单的来源。

  • market_price -- 成交时的市场价格,未经过成交时滑点调整。默认为 fill_price

返回:

如果订单已成交则为 Order,否则为 None

class PortfolioBar(date: datetime64, cash: Decimal, equity: Decimal, notional: Decimal, margin: Decimal, margin_loan: Decimal, net_cash_balance: Decimal, market_value: Decimal, pnl: Decimal, unrealized_pnl: Decimal, fees: Decimal)[源代码]

基类:NamedTuple

按 K 线捕获的 Portfolio 状态快照。

date

K 线的日期。

类型:

numpy.datetime64

cash

Portfolio 中的可用现金。

类型:

decimal.Decimal

equity

Portfolio 中的权益金额。未平仓空头仓位按成本计价,因此不包含其未实现盈亏。

类型:

decimal.Decimal

notional

所有未平仓头寸按市值计算的名义敞口:未平仓多头仓位的市值加上未平仓空头仓位的 margin

类型:

decimal.Decimal

margin

未平仓空头仓位按市值计算的名义敞口。

类型:

decimal.Decimal

margin_loan

用于多头和空头杠杆仓位的借入资金。

类型:

decimal.Decimal

net_cash_balance

cash - margin_loan

类型:

decimal.Decimal

market_value

Portfolio 的市值,等于 equity 加上所有未平仓空头仓位的未实现盈亏。

类型:

decimal.Decimal

pnl

Portfolio 的已实现盈亏(PnL)。

类型:

decimal.Decimal

unrealized_pnl

Portfolio 的未实现盈亏(PnL),等于 market_value - equity

类型:

decimal.Decimal

fees

经纪商手续费。

类型:

decimal.Decimal

class Position(symbol: str, shares: ~decimal.Decimal, type: ~typing.Literal['long', 'short'], close: ~decimal.Decimal = <factory>, equity: ~decimal.Decimal = <factory>, market_value: ~decimal.Decimal = <factory>, margin: ~decimal.Decimal = <factory>, pnl: ~decimal.Decimal = <factory>, entries: ~collections.deque[~pybroker.portfolio.Entry] = <factory>, bars: int = 0, entry_notional: ~decimal.Decimal = <factory>, unmarked_shares: ~decimal.Decimal = <factory>, unmarked_notional: ~decimal.Decimal = <factory>)[源代码]

基类:object

包含 symbol 未平仓头寸的相关信息。

symbol

该头寸的股票代码。

类型:

str

shares

股数。

类型:

decimal.Decimal

type

头寸类型,为 longshort

类型:

Literal['long', 'short']

close

symbol 的最新收盘价。

类型:

decimal.Decimal

equity

该头寸的权益。

类型:

decimal.Decimal

market_value

该头寸的市值。

类型:

decimal.Decimal

margin

该头寸的保证金金额。

类型:

decimal.Decimal

pnl

未实现盈亏(PnL)。

类型:

decimal.Decimal

entries

该头寸的 Entry组成的 deque,按时间先后升序排列。

类型:

collections.deque[pybroker.portfolio.Entry]

bars

按投资组合时钟计算的、自入场以来的当前 K 线数。

类型:

int

entry_notional

该头寸未平仓入场的总成本基础。

类型:

decimal.Decimal

unmarked_shares

自上次估值以来新获取的股份。若按 close 对其估值,会以买入之前的某次估值来定价,因此在下一次估值之前,这些股份按成本计价。

类型:

decimal.Decimal

unmarked_notional

按成交价计算的 unmarked_shares 成本。

类型:

decimal.Decimal

class PositionBar(symbol: str, date: datetime64, long_shares: Decimal, short_shares: Decimal, close: Decimal, equity: Decimal, market_value: Decimal, margin: Decimal, unrealized_pnl: Decimal)[源代码]

基类:NamedTuple

按 K 线捕获的未平仓 Position状态快照。

symbol

Position 的股票代码。

类型:

str

date

K 线的日期。

类型:

numpy.datetime64

long_shares

Position 中的多头股数。

类型:

decimal.Decimal

short_shares

Position 中的空头股数。

类型:

decimal.Decimal

close

symbol 的最新收盘价。

类型:

decimal.Decimal

equity

Position 中的权益金额。

类型:

decimal.Decimal

market_value

Position 的市值。

类型:

decimal.Decimal

margin

Position 中的保证金金额。

类型:

decimal.Decimal

unrealized_pnl

Position 的未实现盈亏(PnL)。

类型:

decimal.Decimal

class Stop(id: int, symbol: str, stop_type: StopType, pos_type: Literal['long', 'short'], percent: Decimal | None, points: Decimal | None, bars: int | None, fill_price: int | float | floating | Decimal | PriceType | Callable[[str, BarData], int | float | Decimal] | None, limit_price: Decimal | None, exit_price: PriceType | None)[源代码]

基类:NamedTuple

包含设置在 Entry 上的止损相关信息。

id

唯一标识符。

类型:

int

symbol

该止损对应的品种代码。

类型:

str

stop_type

StopType

类型:

pybroker.common.StopType

pos_type

Position 的类型,为 longshort

类型:

Literal['long', 'short']

percent

距入场价格的百分比。

类型:

decimal.Decimal | None

points

距入场价格的现金金额。

类型:

decimal.Decimal | None

bars

触发止损前需要经过的 K 线数。

类型:

int | None

fill_price

该止损将以之成交的价格。

类型:

int | float | numpy.floating | decimal.Decimal | pybroker.common.PriceType | Callable[[str, pybroker.common.BarData], int | float | decimal.Decimal] | None

limit_price

该止损使用的限价。

类型:

decimal.Decimal | None

exit_price

止损离场时使用的离场 pybroker.common.PriceType。如果设置了该值,止损会依据 exit_price 进行判定,并在触发时以 exit_price 离场。

类型:

pybroker.common.PriceType | None

class StopRecord(date: datetime64, symbol: str, stop_id: int, stop_type: str, pos_type: Literal['long', 'short'], curr_value: Decimal | None, curr_bars: int | None, percent: Decimal | None, points: Decimal | None, bars: int | None, fill_price: Decimal | None, limit_price: Decimal | None, exit_price: PriceType | None)[源代码]

基类:NamedTuple

按 K 线记录止损的相关数据。

date

该 K 线的日期。

类型:

numpy.datetime64

symbol

该止损对应的品种代码。

类型:

str

stop_id

唯一标识符。

类型:

int

stop_type

StopType

类型:

str

pos_type

Position 的类型,为 longshort

类型:

Literal['long', 'short']

curr_value

该止损的当前值。

类型:

decimal.Decimal | None

curr_bars

该止损的当前 K 线数。

类型:

int | None

percent

距入场价格的百分比。

类型:

decimal.Decimal | None

points

距入场价格的现金金额。

类型:

decimal.Decimal | None

bars

触发止损前需要经过的 K 线数。

类型:

int | None

fill_price

该止损将以之成交的价格。

类型:

decimal.Decimal | None

limit_price

该止损使用的限价。

类型:

decimal.Decimal | None

exit_price

止损离场时使用的离场 pybroker.common.PriceType。如果设置了该值,止损会依据 exit_price 进行判定,并在触发时以 exit_price 离场。

类型:

pybroker.common.PriceType | None

class Trade(id: int, type: Literal['long', 'short'], symbol: str, entry_date: datetime64, exit_date: datetime64, entry: Decimal, exit: Decimal, shares: Decimal, pnl: Decimal, return_pct: Decimal, agg_pnl: Decimal, bars: int, pnl_per_bar: Decimal, stop: Literal['bar', 'loss', 'profit', 'trailing'] | None, mae: Decimal, mfe: Decimal)[源代码]

基类:NamedTuple

保存一笔已完成交易(入场和离场)的相关信息。

id

唯一标识符。

类型:

int

type

交易类型,为 longshort

类型:

Literal['long', 'short']

symbol

该笔交易的股票代码。

类型:

str

entry_date

入场日期。

类型:

numpy.datetime64

exit_date

离场日期。

类型:

numpy.datetime64

entry

入场价格。

类型:

decimal.Decimal

exit

离场价格。

类型:

decimal.Decimal

shares

股数。

类型:

decimal.Decimal

pnl

盈亏(PnL)。

类型:

decimal.Decimal

return_pct

以百分比衡量的收益率。

类型:

decimal.Decimal

agg_pnl

该笔交易之后策略的累计盈亏(PnL)。

类型:

decimal.Decimal

bars

该笔交易的持仓 K 线数。

类型:

int

pnl_per_bar

每根持仓 K 线的盈亏(PnL)。

类型:

decimal.Decimal

stop

被触发的止损类型(如有)。

类型:

Literal['bar', 'loss', 'profit', 'trailing'] | None

mae

最大不利变动(Maximum Adverse Excursion,MAE)。

类型:

decimal.Decimal

mfe

最大有利变动(Maximum Favorable Excursion,MFE)。

类型:

decimal.Decimal