pybroker.common module

Contains common classes and utilities.

class BarData(date: ndarray[Any, dtype[datetime64]], open: ndarray[Any, dtype[float64]], high: ndarray[Any, dtype[float64]], low: ndarray[Any, dtype[float64]], close: ndarray[Any, dtype[float64]], volume: ndarray[Any, dtype[float64]] | None, vwap: ndarray[Any, dtype[float64]] | None, **kwargs)[source]

Bases: object

Contains data for a series of bars. Each field is a numpy.ndarray that contains bar values in the series. The values are sorted in ascending chronological order.

Parameters:
  • date – Timestamps of each bar.

  • open – Open prices.

  • high – High prices.

  • low – Low prices.

  • close – Close prices.

  • volume – Trading volumes.

  • vwap – Volume-weighted average prices (VWAP).

  • **kwargs – Custom data fields.

class DataCol(value)[source]

Bases: Enum

Default data column names.

CLOSE = 'close'
DATE = 'date'
HIGH = 'high'
LOW = 'low'
OPEN = 'open'
SYMBOL = 'symbol'
VOLUME = 'volume'
VWAP = 'vwap'
class Day(value)[source]

Bases: Enum

Enumeration of days.

FRI = 4
MON = 0
SAT = 5
SUN = 6
THURS = 3
TUES = 1
WEDS = 2
class FeeInfo(symbol: str, shares: Decimal, fill_price: Decimal, order_type: Literal['buy', 'sell'])[source]

Bases: NamedTuple

Contains info for custom fee calculations.

symbol

Trading symbol.

Type:

str

shares

Number of shares in order.

Type:

decimal.Decimal

fill_price

Fill price of order.

Type:

decimal.Decimal

order_type

Type of order, either “buy” or “sell”.

Type:

Literal[‘buy’, ‘sell’]

class FeeMode(value)[source]

Bases: Enum

Brokerage fee mode to use for backtesting.

ORDER_PERCENT

Fee is a percentage of order amount, where order amount is fill_price * shares.

PER_ORDER

Fee is a constant amount per order.

PER_SHARE

Fee is a constant amount per share in order.

ORDER_PERCENT = 'order_percent'
PER_ORDER = 'per_order'
PER_SHARE = 'per_share'
class IndicatorSymbol(ind_name: str, symbol: str)[source]

Bases: NamedTuple

pybroker.indicator.Indicator/symbol identifier.

ind_name

Indicator name.

Type:

str

symbol

Ticker symbol.

Type:

str

class ModelSymbol(model_name: str, symbol: str)[source]

Bases: NamedTuple

pybroker.model.ModelSource/symbol identifier.

model_name

Model name.

Type:

str

symbol

Ticker symbol.

Type:

str

class PriceType(value)[source]

Bases: Enum

Enumeration of price types used to specify fill price with pybroker.context.ExecContext.

OPEN

Open price of the current bar.

LOW

Low price of the current bar.

HIGH

High price of the current bar.

CLOSE

Close price of the current bar.

MIDDLE

Midpoint between low price and high price of the current bar.

AVERAGE

Average of open, low, high, and close prices of the current bar.

AVERAGE = 'average'
CLOSE = 'close'
HIGH = 'high'
LOW = 'low'
MIDDLE = 'middle'
OPEN = 'open'
class StopType(value)[source]

Bases: Enum

Stop types.

BAR

Stop that triggers after n bars.

LOSS

Stop loss.

PROFIT

Take profit.

TRAILING

Trailing stop loss.

BAR = 'bar'
LOSS = 'loss'
PROFIT = 'profit'
TRAILING = 'trailing'
class TrainedModel(name: str, instance: Any, predict_fn: Callable[[Any, DataFrame], ndarray[Any, dtype[_ScalarType_co]]] | None, input_cols: tuple[str] | None)[source]

Bases: NamedTuple

Trained model/symbol identifier.

name

Trained model name.

Type:

str

instance

Trained model instance.

Type:

Any

predict_fn

Callable that overrides calling the model’s default predict function.

Type:

Callable[[Any, pandas.core.frame.DataFrame], numpy.ndarray[Any, numpy.dtype[numpy._typing._array_like._ScalarType_co]]] | None

input_cols

Names of the columns to be used as input for the model when making predictions.

Type:

tuple[str] | None

input_cols: tuple[str] | None

Alias for field number 3

default_parallel() Parallel[source]

Returns a joblib.Parallel instance with n_jobs equal to the number of CPUs on the host machine.

get_unique_sorted_dates(col: Series) Sequence[datetime64][source]

Returns sorted unique values from a DataFrame column of dates. Guarantees compatability between Pandas 1 and 2.

parse_timeframe(timeframe: str) list[tuple[int, str]][source]

Parses timeframe string with the following units:

  • "s"/"sec": seconds

  • "m"/"min": minutes

  • "h"/"hour": hours

  • "d"/"day": days

  • "w"/"week": weeks

An example timeframe string is 1h 30m.

Returns:

list of tuple[int, str], where each tuple contains an int value and str unit of one of the following: sec, min, hour, day, week.

quantize(df: DataFrame, col: str, round: bool) Series[source]

Quantizes a pandas.DataFrame column by rounding values to the nearest cent.

Returns:

The quantized column converted to float values.

to_datetime(date: str | datetime | datetime64 | Timestamp) datetime[source]

Converts date to datetime.

to_decimal(value: int | float | Decimal) Decimal[source]

Converts value to Decimal.

to_seconds(timeframe: str | None) int[source]

Converts a timeframe string to seconds, where timeframe supports the following units:

  • "s"/"sec": seconds

  • "m"/"min": minutes

  • "h"/"hour": hours

  • "d"/"day": days

  • "w"/"week": weeks

An example timeframe string is 1h 30m.

Returns:

The converted number of seconds.

verify_data_source_columns(df: DataFrame)[source]

Verifies that a pandas.DataFrame contains all of the columns required by a pybroker.data.DataSource.

verify_date_range(start_date: datetime, end_date: datetime)[source]

Verifies date range bounds.