position

Attributes

portfolio_schema

positions_schema

Classes

PortfolioStats

!!! abstract "Usage Documentation"

PositionType

str(object='') -> str

PositionEncoder

Extensible JSON <https://json.org> encoder for Python data structures.

Position

Represents a position in the portfolio, backed by a numpy array.

PositionManager

LivePositionManager

Position Manager derived class for implementing wrapper functionality to the underlying logic of the PositionManager.

Functions

PositionDecoder(dct)

Module Contents

position.portfolio_schema
class position.PortfolioStats(/, **data)

Bases: pydantic.BaseModel

!!! abstract “Usage Documentation”

[Models](../concepts/models.md)

A base class for creating Pydantic models.

Parameters:

data (Any)

__class_vars__

The names of the class variables defined on the model.

__private_attributes__

Metadata about the private attributes of the model.

__signature__

The synthesized __init__ [Signature][inspect.Signature] of the model.

__pydantic_complete__

Whether model building is completed, or if there are still undefined fields.

__pydantic_core_schema__

The core schema of the model.

__pydantic_custom_init__

Whether the model has a custom __init__ function.

__pydantic_decorators__

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_generic_metadata__

Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__

The name of the post-init method for the model, if defined.

__pydantic_root_model__

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_validator__

The pydantic-core SchemaValidator used to validate instances of the model.

__pydantic_fields__

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects.

__pydantic_computed_fields__

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_extra__

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to ‘allow’.

__pydantic_fields_set__

The names of fields explicitly set during instantiation.

__pydantic_private__

Values of private attributes set on the model instance.

COLS: ClassVar[list[str]] = ['net_value', 'cash', 'pnl', 'pnl_pct', 'date', 'rolling_pnl', 'rolling_pnl_pct']
net_value: float = 0.0
cash: float = 0.0
pnl: float = 0.0
pnl_pct: float = 0.0
rolling_pnl: float = 0.0
rolling_pnl_pct: float = 0.0
date: datetime.datetime
__iter__()

So dict(model) works.

to_row()
Return type:

list

class position.PositionType

Bases: str, enum.Enum

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

LONG = 'long'
SHORT = 'short'
class position.PositionEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: json.JSONEncoder

Extensible JSON <https://json.org> encoder for Python data structures.

Supports the following objects and types by default:

Python

JSON

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

To extend this to recognize other objects, subclass and implement a .default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

default(obj)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
position.PositionDecoder(dct)
position.positions_schema
class position.Position(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

Bases: numpy.ndarray

Represents a position in the portfolio, backed by a numpy array. TODO swap out in favor of alpacas Position type, if possible, however speed of np.ndarray is preferred.

COLS = ['symbol', 'lot_size', 'enter_date', 'enter_price', 'exit_date', 'exit_price', 'exit_size',...
IDX_SYMBOL = 0
IDX_LOT_SIZE = 1
IDX_ENTER_DATE = 2
IDX_ENTER_PRICE = 3
IDX_EXIT_DATE = 4
IDX_EXIT_PRICE = 5
IDX_EXIT_SIZE = 6
IDX_POSITION_TYPE = 7
to_row()

This method is for completeness and consistency, as it derives from np.ndarray, it is alread a list-like object.

Parameters:

self – Description

Returns:

Description

Return type:

list[Any]

classmethod from_alpaca_position(alpaca_position)
Parameters:

alpaca_position (alpaca.trading.models.Position)

Return type:

Position

property symbol: str
Return type:

str

property lot_size: float
Return type:

float

property enter_price: float
Return type:

float

property exit_price: float | None
Return type:

float | None

property enter_date: pandas.Timestamp | None
Return type:

pandas.Timestamp | None

property exit_date: pandas.Timestamp | None
Return type:

pandas.Timestamp | None

property exit_size: float | None
Return type:

float | None

property position_type: PositionType
Return type:

PositionType

exit(exit_date, price, exit_size=None)
Parameters:
  • exit_date (pandas.Timestamp)

  • price (float)

  • exit_size (float | None)

profit()
Return type:

float

__iter__()
__str__()
__repr__()
class position.PositionManager(symbols, max_lots=None, maintain_history=True, initial_cash=0.0, df=None, positions=None, cash=None)
Parameters:
  • symbols (list[str])

  • max_lots (int | None)

  • maintain_history (bool)

  • initial_cash (float)

  • df (pandas.DataFrame | None)

  • positions (dict[str, collections.deque[Position]] | None)

  • cash (float | None)

symbols
max_lots: int | None = None
_initial_cash
_cash
closed_positions: list[Position] = []
maintain_history = True
__getitem__(key)

Allow access to the internal DataFrame using the [] accessor.

to_csv(path)

Save the positions to a CSV file.

Parameters:

path (str)

reset()

Reset the position manager.

classmethod from_client(trading_client, symbols, max_lots=None, maintain_history=True, initial_cash=0.0, initial_prices=None)
Parameters:
  • trading_client (trading.src.trade.trade_clients.TradingClient)

  • symbols (list[str])

  • max_lots (int | None)

  • maintain_history (bool)

  • initial_cash (float)

  • initial_prices (numpy.ndarray | None)

Return type:

PositionManager

to_df(client_positions, df)

Populate this PositionManager from a mapping of positions (e.g. from a TradingClient).

Parameters:
  • client_positions (dict[str, collections.deque[Position]])

  • df (pandas.DataFrame)

Return type:

None

_append(df)
Parameters:

df (pandas.DataFrame)

_exit_positions(df)

Exit positions based on the provided DataFrame. ! Removing the whole lots thing would reduce complexity and speed. AKA single “position” per symbol with size attribute.

Parameters:

df (pandas.DataFrame)

Return type:

pandas.DataFrame

step(df)

Step through the position manager. Return a set indicating if a position was exited and the profit from that position.

Parameters:

df (pandas.DataFrame)

Return type:

tuple[pandas.DataFrame, float, list[alpaca.broker.requests.MarketOrderRequest]]

available_cash()

Return the available cash of the portfolio.

Return type:

float

initial_cash()

Return the initial cash of the portfolio.

Return type:

float

nav(prices=None)

Calculate the net asset value (NAV) of the portfolio.

Parameters:

prices (pandas.Series | None)

Return type:

float

net_value(prices=None)
Parameters:

prices (pandas.Series | None)

Return type:

float

class position.LivePositionManager(trading_client, symbols, max_lots=None, maintain_history=True, initial_cash=0, initial_prices=None)

Bases: PositionManager

Position Manager derived class for implementing wrapper functionality to the underlying logic of the PositionManager. Additional logic to convert actual live portfolio positions into the PositionManager format, and thus perform that logic on the live data. Additionally Position Manager can be derived to perform other wrapper functionality on the underlying actions taken by the Position Manager logic.

Parameters:
  • trading_client (trading.src.trade.trade_clients.TradingClient)

  • symbols (list[str])

  • max_lots (int | None)

  • maintain_history (bool)

  • initial_cash (float)

  • initial_prices (numpy.ndarray | None)

pf_history: list[PortfolioStats] = []
trading_client
__del__()
reset()

Reset the position manager.

step(df)

Step through the position manager. Return a set indicating if a position was exited and the profit from that position.

Parameters:

df (pandas.DataFrame)

Return type:

tuple[pandas.DataFrame, float, list[alpaca.broker.requests.MarketOrderRequest]]