pybroker.portfolio module

Contains portfolio related functionality, such as portfolio metrics and placing orders.

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

Bases: object

Contains information about an entry into a Position.

id

Unique identifier.

Type:

int

date

Date of the entry.

Type:

numpy.datetime64

symbol

Symbol of the entry.

Type:

str

shares

Number of shares.

Type:

decimal.Decimal

price

Share price of the entry.

Type:

decimal.Decimal

type

Type of Position, either long or short.

Type:

Literal[‘long’, ‘short’]

bars

Current number of bars since entry.

Type:

int

stops

Stops set on the entry.

Type:

set[pybroker.portfolio.Stop]

mae

Maximum adverse excursion (MAE).

Type:

decimal.Decimal

mfe

Maximum favorable excursion (MFE).

Type:

decimal.Decimal

mae: Decimal
mfe: Decimal
class Order(id: int, type: Literal['buy', 'sell'], symbol: str, date: datetime64, shares: Decimal, limit_price: Decimal | None, fill_price: Decimal, fees: Decimal)[source]

Bases: NamedTuple

Holds information about a filled order.

id

Unique identifier.

Type:

int

type

Type of order, either buy or sell.

Type:

Literal[‘buy’, ‘sell’]

symbol

Ticker symbol of the order.

Type:

str

date

Date the order was filled.

Type:

numpy.datetime64

shares

Number of shares bought or sold.

Type:

decimal.Decimal

limit_price

Limit price that was used for the order.

Type:

decimal.Decimal | None

fill_price

Price that the order was filled at.

Type:

decimal.Decimal

fees

Brokerage fees for order.

Type:

decimal.Decimal

class Portfolio(cash: float, fee_mode: FeeMode | Callable[[FeeInfo], Decimal] | None = None, fee_amount: float | None = None, subtract_fees: bool = False, enable_fractional_shares: bool = False, max_long_positions: int | None = None, max_short_positions: int | None = None)[source]

Bases: object

Class representing a portfolio of holdings. The portfolio contains information about open positions and balances, and is also used to place buy and sell orders.

Parameters:
  • cash – Starting cash balance.

  • fee_mode – Brokerage fee mode.

  • fee_amount – Brokerage fee amount.

  • max_long_positions – Maximum number of long Positions that can be held at a time. If None, then unlimited.

  • max_short_positions – Maximum number of short Positions that can be held at a time. If None, then unlimited.

cash

Current cash balance.

equity

Current amount of equity.

market_value

Current market value. The market value is defined as the amount of equity held in cash and long positions added together with the unrealized PnL of all open short positions.

fees

Current brokerage fees.

fee_amount

Brokerage fee amount.

subtract_fees

Whether to subtract fees from the cash balance.

enable_fractional_shares

Whether to enable trading fractional shares.

orders

deque of all filled orders, sorted in ascending chronological order.

margin

Current amount of margin held in open positions.

pnl

Realized profit and loss (PnL).

long_positions

dict mapping ticker symbols to open long Positions.

short_positions

dict mapping ticker symbols to open short Positions.

symbols

Ticker symbols of all currently open positions.

bars

deque of snapshots of Portfolio state on every bar, sorted in ascending chronological order.

position_bars

deque of snapshots of Position states on every bar, sorted in ascending chronological order.

win_rate

Running win rate of trades.

loss_rate

Running loss rate of trades.

buy(date: datetime64, symbol: str, shares: Decimal, fill_price: Decimal, limit_price: Decimal | None = None, stops: Iterable[Stop] | None = None) Order | None[source]

Places a buy order.

Parameters:
  • date – Date when the Order is placed.

  • symbol – Ticker symbol to buy.

  • shares – Number of shares to buy.

  • fill_price – If filled, the price used to fill the Order.

  • limit_price – Limit price of the Order.

  • stopsStops to set on the Entry created from the Order, if filled.

Returns:

Order if the order was filled, otherwise None.

capture_bar(date: datetime64, df: DataFrame)[source]

Captures portfolio state of the current bar.

Parameters:
  • date – Date of current bar.

  • dfpandas.DataFrame containing close prices.

check_stops(date: datetime64, price_scope: PriceScope)[source]

Checks whether stops are triggered.

exit_position(date: datetime64, symbol: str, buy_fill_price: Decimal, sell_fill_price: Decimal)[source]

Exits any long and short positions for symbol at buy_fill_price and sell_fill_price.

incr_bars()[source]

Increments the number of bars held by every trade entry.

remove_stop(stop_id: int) bool[source]

Removes a Stop with stop_id.

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

Removes Stops.

Parameters:
sell(date: datetime64, symbol: str, shares: Decimal, fill_price: Decimal, limit_price: Decimal | None = None, stops: Iterable[Stop] | None = None) Order | None[source]

Places a sell order.

Parameters:
  • date – Date when the Order is placed.

  • symbol – Ticker symbol to sell.

  • shares – Number of shares to sell.

  • fill_price – If filled, the price used to fill the Order.

  • limit_price – Limit price of the Order.

  • stopsStops to set on the Entry created from the Order, if filled.

Returns:

Order if the order was filled, otherwise None.

class PortfolioBar(date: datetime64, cash: Decimal, equity: Decimal, margin: Decimal, market_value: Decimal, pnl: Decimal, unrealized_pnl: Decimal, fees: Decimal)[source]

Bases: NamedTuple

Snapshot of Portfolio state, captured per bar.

date

Date of bar.

Type:

numpy.datetime64

cash

Amount of cash in Portfolio.

Type:

decimal.Decimal

equity

Amount of equity in Portfolio.

Type:

decimal.Decimal

margin

Amount of margin in Portfolio.

Type:

decimal.Decimal

market_value

Market value of Portfolio.

Type:

decimal.Decimal

pnl

Realized profit and loss (PnL) of Portfolio.

Type:

decimal.Decimal

unrealized_pnl

Unrealized profit and loss (PnL) of Portfolio.

Type:

decimal.Decimal

fees

Brokerage fees.

Type:

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)[source]

Bases: object

Contains information about an open position in symbol.

symbol

Ticker symbol of the position.

Type:

str

shares

Number of shares.

Type:

decimal.Decimal

type

Type of position, either long or short.

Type:

Literal[‘long’, ‘short’]

close

Last close price of symbol.

Type:

decimal.Decimal

equity

Equity in the position.

Type:

decimal.Decimal

market_value

Market value of position.

Type:

decimal.Decimal

margin

Amount of margin in position.

Type:

decimal.Decimal

pnl

Unrealized profit and loss (PnL).

Type:

decimal.Decimal

entries

deque of position Entrys sorted in ascending chronological order.

Type:

collections.deque[pybroker.portfolio.Entry]

bars

Current number of bars since entry.

Type:

int

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

Bases: NamedTuple

Snapshot of an open Position‘s state, captured per bar.

symbol

Ticker symbol of Position.

Type:

str

date

Date of bar.

Type:

numpy.datetime64

long_shares

Number of shares long in Position.

Type:

decimal.Decimal

short_shares

Number of shares short in Position.

Type:

decimal.Decimal

close

Last close price of symbol.

Type:

decimal.Decimal

equity

Amount of equity in Position.

Type:

decimal.Decimal

market_value

Market value of Position.

Type:

decimal.Decimal

margin

Amount of margin in Position.

Type:

decimal.Decimal

unrealized_pnl

Unrealized profit and loss (PnL) of Position.

Type:

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)[source]

Bases: NamedTuple

Contains information about a stop set on Entry.

id

Unique identifier.

Type:

int

symbol

Symbol of the stop.

Type:

str

stop_type

StopType.

Type:

pybroker.common.StopType

pos_type

Type of Position, either long or short.

Type:

Literal[‘long’, ‘short’]

percent

Percent from entry price.

Type:

decimal.Decimal | None

points

Cash amount from entry price.

Type:

decimal.Decimal | None

bars

Number of bars after which to trigger the stop.

Type:

int | None

fill_price

Price that the stop will be filled at.

Type:

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

limit_price

Limit price to use for the stop.

Type:

decimal.Decimal | None

exit_price

Exit pybroker.common.PriceType to use for the stop exit. If set, the stop is checked against the exit_price and exits at the exit_price when triggered.

Type:

pybroker.common.PriceType | None

exit_price: PriceType | None

Alias for field number 9

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)[source]

Bases: NamedTuple

Holds information about a completed trade (entry and exit).

id

Unique identifier.

Type:

int

type

Type of trade, either long or short.

Type:

Literal[‘long’, ‘short’]

symbol

Ticker symbol of the trade.

Type:

str

entry_date

Entry date.

Type:

numpy.datetime64

exit_date

Exit date.

Type:

numpy.datetime64

entry

Entry price.

Type:

decimal.Decimal

exit

Exit price.

Type:

decimal.Decimal

shares

Number of shares.

Type:

decimal.Decimal

pnl

Profit and loss (PnL).

Type:

decimal.Decimal

return_pct

Return measured in percentage.

Type:

decimal.Decimal

agg_pnl

Aggregate profit and loss (PnL) of the strategy after the trade.

Type:

decimal.Decimal

bars

Number of bars the trade was held.

Type:

int

pnl_per_bar

Profit and loss (PnL) per bar held.

Type:

decimal.Decimal

stop

Type of stop that was triggered, if any.

Type:

Literal[‘bar’, ‘loss’, ‘profit’, ‘trailing’] | None

mae

Maximum adverse excursion (MAE).

Type:

decimal.Decimal

mfe

Maximum favorable excursion (MFE).

Type:

decimal.Decimal

mae: Decimal

Alias for field number 14

mfe: Decimal

Alias for field number 15