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: list[~pybroker.portfolio.Stop] = <factory>, mae: ~decimal.Decimal = <factory>, mfe: ~decimal.Decimal = <factory>)[source]
Bases:
object
Contains information about an entry into a
Position
.- date
Date of the entry.
- Type:
Number of shares.
- Type:
- price
Share price of the entry.
- Type:
- stops
Stops set on the entry.
- Type:
- mae
Maximum adverse excursion (MAE).
- Type:
- mfe
Maximum favorable excursion (MFE).
- Type:
- 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.
- type
Type of order, either
buy
orsell
.- Type:
Literal[‘buy’, ‘sell’]
- date
Date the order was filled.
- Type:
Number of shares bought or sold.
- Type:
- limit_price
Limit price that was used for the order.
- Type:
decimal.Decimal | None
- fill_price
Price that the order was filled at.
- Type:
- fees
Brokerage fees for order.
- Type:
- 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, record_stops: bool | None = False)[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.
subtract_fees – Whether to subtract fees from the cash balance after an order is filled.
enable_fractional_shares – Whether to enable trading fractional shares.
max_long_positions – Maximum number of long
Position
s that can be held at a time. IfNone
, then unlimited.max_short_positions – Maximum number of short
Position
s that can be held at a time. IfNone
, then unlimited.record_stops – Whether to record stop data per-bar.
- 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.
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).
- symbols
Ticker symbols of all currently open positions.
- position_bars
deque
of snapshots ofPosition
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:
- Returns:
Order
if the order was filled, otherwiseNone
.
- capture_bar(date: datetime64, df: DataFrame)[source]
Captures portfolio state of the current bar.
- Parameters:
date – Date of current bar.
df –
pandas.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
atbuy_fill_price
andsell_fill_price
.
- remove_stops(val: str | Position | Entry, stop_type: StopType | None = None)[source]
Removes
Stop
s.- Parameters:
val – Ticker symbol,
Position
, orEntry
for which to cancel stops.stop_type –
pybroker.common.StopType
.
- 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:
- fees
Brokerage fees.
- Type:
- 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
.Number of shares.
- Type:
- type
Type of position, either
long
orshort
.- Type:
Literal[‘long’, ‘short’]
- close
Last close price of
symbol
.- Type:
- equity
Equity in the position.
- Type:
- market_value
Market value of position.
- Type:
- margin
Amount of margin in position.
- Type:
- pnl
Unrealized profit and loss (PnL).
- Type:
- 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.- date
Date of bar.
- Type:
Number of shares long in
Position
.- Type:
Number of shares short in
Position
.- Type:
- close
Last close price of
symbol
.- Type:
- 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
.- stop_type
-
- Type:
- percent
Percent from entry price.
- Type:
decimal.Decimal | None
- points
Cash amount from entry price.
- Type:
decimal.Decimal | 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 theexit_price
and exits at theexit_price
when triggered.- Type:
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)[source]
Bases:
NamedTuple
Records per-bar data about a stop.
- date
Date of the bar.
- Type:
- curr_value
Current value of the stop.
- Type:
decimal.Decimal | None
- percent
Percent from entry price.
- Type:
decimal.Decimal | None
- points
Cash amount from entry price.
- Type:
decimal.Decimal | None
- fill_price
Price that the stop will be filled at.
- Type:
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 theexit_price
and exits at theexit_price
when triggered.- Type:
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)[source]
Bases:
NamedTuple
Holds information about a completed trade (entry and exit).
- type
Type of trade, either
long
orshort
.- Type:
Literal[‘long’, ‘short’]
- entry_date
Entry date.
- Type:
- exit_date
Exit date.
- Type:
- entry
Entry price.
- Type:
- exit
Exit price.
- Type:
Number of shares.
- Type:
- pnl
Profit and loss (PnL).
- Type:
- return_pct
Return measured in percentage.
- Type:
- agg_pnl
Aggregate profit and loss (PnL) of the strategy after the trade.
- Type:
- pnl_per_bar
Profit and loss (PnL) per bar held.
- Type:
- stop
Type of stop that was triggered, if any.
- Type:
Literal[‘bar’, ‘loss’, ‘profit’, ‘trailing’] | None
- mae
Maximum adverse excursion (MAE).
- Type:
- mfe
Maximum favorable excursion (MFE).
- Type: