Skip to content

enums module

Named tuples and enumerated types for portfolio.

Defines enums and other schemas for vectorbtpro.portfolio.


AccumulationMode AccumulationModeT

Accumulation mode.

AccumulationModeT(
    Disabled=0,
    Both=1,
    AddOnly=2,
    RemoveOnly=3
)

Accumulation allows gradually increasing and decreasing positions by a size.

Attributes

Disabled

Disable accumulation.

Can also be provided as False.

Both

Allow both adding to and removing from the position.

Can also be provided as True.

AddOnly
Allow accumulation to only add to the position.
RemoveOnly
Allow accumulation to only remove from the position.

Note

Accumulation acts differently for exits and opposite entries: exits reduce the current position but won't enter the opposite one, while opposite entries reduce the position by the same amount, but as soon as this position is closed, they begin to increase the opposite position.

The behavior for opposite entries can be changed by OppositeEntryMode and for stop orders by StopExitType.


CallSeqType CallSeqTypeT

Call sequence type.

CallSeqTypeT(
    Default=0,
    Reversed=1,
    Random=2,
    Auto=3
)

Attributes

Default
Place calls from left to right.
Reversed
Place calls from right to left.
Random
Place calls randomly.
Auto
Place calls dynamically based on order value.

ConflictMode ConflictModeT

Conflict mode.

ConflictModeT(
    Ignore=0,
    Entry=1,
    Exit=2,
    Adjacent=3,
    Opposite=4
)

What should happen if both an entry signal and an exit signal occur simultaneously?

Attributes

Ignore
Ignore both signals.
Entry
Execute the entry signal.
Exit
Execute the exit signal.
Adjacent

Execute the signal adjacent to the current position.

Takes effect only when in position, otherwise ignores.

Opposite

Execute the signal opposite to the current position.

Takes effect only when in position, otherwise ignores.


DeltaFormat DeltaFormatT

Delta format.

DeltaFormatT(
    Absolute=0,
    Percent=1,
    Percent100=2,
    Target=3
)

In which format a delta is provided?

Attributes

Absolute
Absolute format where 0.1 is the absolute difference between the initial and target value
Percent
Percentage format where 0.1 is 10% applied to the initial value to get the target value
Percent100
Percentage format where 0.1 is 0.1% applied to the initial value to get the target value
Target
Target format where 0.1 is the target value

Direction DirectionT

Position direction.

DirectionT(
    LongOnly=0,
    ShortOnly=1,
    Both=2
)

Attributes

LongOnly
Only long positions.
ShortOnly
Only short positions.
Both
Both long and short positions.

DirectionConflictMode DirectionConflictModeT

Direction conflict mode.

DirectionConflictModeT(
    Ignore=0,
    Long=1,
    Short=2,
    Adjacent=3,
    Opposite=4
)

What should happen if both a long entry signal and a short entry signals occur simultaneously?

Attributes

Ignore
Ignore both entry signals.
Long
Execute the long entry signal.
Short
Execute the short entry signal.
Adjacent

Execute the adjacent entry signal.

Takes effect only when in position, otherwise ignores.

Opposite

Execute the opposite entry signal.

Takes effect only when in position, otherwise ignores.


InitCashMode InitCashModeT

Initial cash mode.

InitCashModeT(
    Auto=-1,
    AutoAlign=-2
)

Attributes

Auto
Initial cash is infinite within simulation, and then set to the total cash spent.
AutoAlign
Initial cash is set to the total cash spent across all columns.

LeverageMode LeverageModeT

Leverage mode.

LeverageModeT(
    Lazy=0,
    Eager=1
)

Attributes

Lazy
Applies leverage only if free cash has been exhausted.
Eager
Applies leverage to each order.

LimitOrderPrice LimitOrderPriceT

Limit order price.

LimitOrderPriceT(
    Limit=-1,
    HardLimit=-2,
    Close=-3
)

Which price to use when executing a limit order?

Attributes

Limit

Limit price.

If the target price is first hit by the opening price, the opening price is used.

HardLimit

Hard limit price.

The stop price is used regardless of whether the target price is first hit by the opening price.

Close
Closing price.

Note

Each flag is negative, thus if a positive value is provided, it's used directly as price.


NoOrder Order

Order that should not be processed.


NoPriceArea PriceArea

No price area.


OppositeEntryMode OppositeEntryModeT

Opposite entry mode.

OppositeEntryModeT(
    Ignore=0,
    Close=1,
    CloseReduce=2,
    Reverse=3,
    ReverseReduce=4
)

What should happen if an entry signal of opposite direction occurs before an exit signal?

Attributes

Ignore
Ignore the opposite entry signal.
Close
Close the current position.
CloseReduce
Close the current position or reduce it if accumulation is enabled.
Reverse
Reverse the current position.
ReverseReduce
Reverse the current position or reduce it if accumulation is enabled.

OrderPriceStatus OrderPriceStatusT

Order price error.

OrderPriceStatusT(
    OK=0,
    AboveHigh=1,
    BelowLow=2,
    Unknown=3
)

Attributes

OK
Order price is within OHLC.
AboveHigh
Order price is above high.
BelowLow
Order price is below low.
Unknown
High and/or low are unknown.

OrderSide OrderSideT

Order side.

OrderSideT(
    Buy=0,
    Sell=1
)

OrderStatus OrderStatusT

Order status.

OrderStatusT(
    Filled=0,
    Ignored=1,
    Rejected=2
)

Attributes

Filled
Order has been filled.
Ignored
Order has been ignored.
Rejected
Order has been rejected.

OrderStatusInfo OrderStatusInfoT

Order status information.

OrderStatusInfoT(
    SizeNaN=0,
    PriceNaN=1,
    ValPriceNaN=2,
    ValueNaN=3,
    ValueZeroNeg=4,
    SizeZero=5,
    NoCash=6,
    NoOpenPosition=7,
    MaxSizeExceeded=8,
    RandomEvent=9,
    CantCoverFees=10,
    MinSizeNotReached=11,
    PartialFill=12
)

OrderType OrderTypeT

Order type.

OrderTypeT(
    Market=0,
    Limit=1
)

PendingConflictMode PendingConflictModeT

Conflict mode for pending signals.

PendingConflictModeT(
    KeepIgnore=0,
    KeepExecute=1,
    CancelIgnore=2,
    CancelExecute=3
)

What should happen if an executable signal occurs during a pending signal?

Attributes

KeepIgnore
Keep the pending signal and cancel the user-defined signal.
KeepExecute
Keep the pending signal and execute the user-defined signal.
CancelIgnore
Cancel the pending signal and ignore the user-defined signal.
CancelExecute
Cancel the pending signal and execute the user-defined signal.

PositionFeature PositionFeatureT

Position feature.

PositionFeatureT(
    EntryPrice=0,
    ExitPrice=1
)

PriceAreaVioMode PriceAreaVioModeT

Price are violation mode.

PriceAreaVioModeT(
    Ignore=0,
    Cap=1,
    Error=2
)

Attributes

Ignore
Ignore any violation.
Cap
Cap price to prevent violation.
Error
Throw an error upon violation.

PriceType PriceTypeT

Price type.

PriceTypeT(
    Open=-np.inf,
    Close=np.inf,
    NextOpen=-1,
    NextClose=-2,
    NextValidOpen=-3,
    NextValidClose=-4
)

Attributes

Open

Opening price.

Will be substituted by -np.inf.

Close

Closing price.

Will be substituted by np.inf.

NextOpen

Next opening price.

Will be substituted by -np.inf and from_ago will be set to 1.

NextClose

Next closing price.

Will be substituted by np.inf and from_ago will be set to 1.

NextValidOpen

Next valid (non-NA) opening price.

Will be substituted by -np.inf and from_ago will be set to the distance to the previous valid value.

NextValidClose

Next valid (non-NA) closing price.

Will be substituted by np.inf and from_ago will be set to the distance to the previous valid value.


SizeType SizeTypeT

Size type.

SizeTypeT(
    Amount=0,
    Value=1,
    Percent=2,
    Percent100=3,
    ValuePercent=4,
    ValuePercent100=5,
    TargetAmount=6,
    TargetValue=7,
    TargetPercent=8,
    TargetPercent100=9
)

Attributes

Amount
Amount of assets to trade.
Value

Asset value to trade.

Gets converted into SizeType.Amount using ExecState.val_price.

Percent

Percentage of available resources to use in either direction (not to be confused with the percentage of position value!) where 0.01 means 1%

Percent100
SizeType.Percent where 1.0 means 1%.
ValuePercent

Percentage of total value.

Uses ExecState.value to get the current total value. Gets converted into SizeType.Value.

ValuePercent100
SizeType.ValuePercent where 1.0 means 1%.
TargetAmount

Target amount of assets to hold (= target position).

Uses ExecState.position to get the current position. Gets converted into SizeType.Amount.

TargetValue

Target asset value.

Uses ExecState.val_price to get the current asset value. Gets converted into SizeType.TargetAmount.

TargetPercent

Target percentage of total value.

Uses ExecState.value_now to get the current total value. Gets converted into SizeType.TargetValue.

TargetPercent100
SizeType.TargetPercent where 1.0 means 1%.

StopEntryPrice StopEntryPriceT

Stop entry price.

StopEntryPriceT(
    ValPrice=-1,
    Open=-2,
    Price=-3,
    FillPrice=-4,
    Close=-5
)

Which price to use as an initial stop price?

Attributes

ValPrice
Asset valuation price.
Open
Opening price.
Price
Order price.
FillPrice
Filled order price (that is, slippage is already applied).
Close
Closing price.

Note

Each flag is negative, thus if a positive value is provided, it's used directly as price.


StopExitPrice StopExitPriceT

Stop exit price.

StopExitPriceT(
    Stop=-1,
    HardStop=-2,
    Close=-3
)

Which price to use when exiting a position upon a stop signal?

Attributes

Stop

Stop price.

If the target price is first hit by the opening price, the opening price is used.

HardStop

Hard stop price.

The stop price is used regardless of whether the target price is first hit by the opening price.

Close
Closing price.

Note

Each flag is negative, thus if a positive value is provided, it's used directly as price.


StopExitType StopExitTypeT

Stop exit type.

StopExitTypeT(
    Close=0,
    CloseReduce=1,
    Reverse=2,
    ReverseReduce=3
)

How to exit the current position upon a stop signal?

Attributes

Close
Close the current position.
CloseReduce
Close the current position or reduce it if accumulation is enabled.
Reverse
Reverse the current position.
ReverseReduce
Reverse the current position or reduce it if accumulation is enabled.

StopLadderMode StopLadderModeT

Stop ladder mode.

StopLadderModeT(
    Disabled=0,
    Uniform=1,
    Weighted=2,
    AdaptUniform=3,
    AdaptWeighted=4,
    Dynamic=5
)

Attributes

Disabled

Disable the stop ladder.

Can also be provided as False.

Uniform

Enable the stop ladder with a uniform exit size.

Can also be provided as True.

Weighted
Enable the stop ladder with a stop-weighted exit size.
AdaptUniform
Enable the stop ladder with a uniform exit size that adapts to the current position.
AdaptWeighted
Enable the stop ladder with a stop-weighted exit size that adapts to the current position.
Dynamic
Enable the stop ladder but do not use stop arrays.

Note

When disabled, make sure that stop arrays broadcast against the target shape.

When enabled, make sure that rows in stop arrays represent steps in the ladder.


StopUpdateMode StopUpdateModeT

Stop update mode.

StopUpdateModeT(
    Keep=0,
    Override=1,
    OverrideNaN=2
)

What to do with the old stop upon a new entry/accumulation?

Attributes

Keep
Keep the old stop.
Override
Override the old stop, but only if the new stop is not NaN.
OverrideNaN
Override the old stop, even if the new stop is NaN.

TimeDeltaFormat TimeDeltaFormatT

Time delta format.

TimeDeltaFormatT(
    Rows=0,
    Index=1
)

In which format a time delta is provided?

Attributes

Rows

Row format where 1 means one row (simulation step) has passed.

Doesn't require the index to be provided.

Index

Index format where 1 means one value in index has passed.

If index is datetime-like, 1 means one nanosecond.

Requires the index to be provided.


TradeDirection TradeDirectionT

Trade direction.

TradeDirectionT(
    Long=0,
    Short=1
)

TradeStatus TradeStatusT

Event status.

TradeStatusT(
    Open=0,
    Closed=1
)

TradesType TradesTypeT

Trades type.

TradesTypeT(
    Trades=0,
    EntryTrades=1,
    ExitTrades=2,
    Positions=3
)

ValPriceType ValPriceTypeT

Asset valuation price type.

ValPriceTypeT(
    Latest=-np.inf,
    Price=np.inf
)

Attributes

Latest
Latest price. Will be substituted by -np.inf.
Price
Order price. Will be substituted by np.inf.

alloc_point_dt VoidDType

np.dtype of allocation point records.

np.dtype([
    ('id', 'int64'),
    ('col', 'int64'),
    ('alloc_idx', 'int64')
])

alloc_point_fields list

Fields for alloc_point_dt.


alloc_range_dt VoidDType

np.dtype of allocation range records.

np.dtype([
    ('id', 'int64'),
    ('col', 'int64'),
    ('start_idx', 'int64'),
    ('end_idx', 'int64'),
    ('alloc_idx', 'int64'),
    ('status', 'int64')
])

alloc_range_fields list

Fields for alloc_range_dt.


fs_order_dt VoidDType

np.dtype of order records generated from signals.

np.dtype([
    ('id', 'int64'),
    ('col', 'int64'),
    ('signal_idx', 'int64'),
    ('creation_idx', 'int64'),
    ('idx', 'int64'),
    ('size', 'float64'),
    ('price', 'float64'),
    ('fees', 'float64'),
    ('side', 'int64'),
    ('type', 'int64'),
    ('stop_type', 'int64')
])

fs_order_fields list

Fields for fs_order_dt.


limit_info_dt VoidDType

np.dtype of limit information records.

np.dtype([
    ('signal_idx', 'int64'),
    ('creation_idx', 'int64'),
    ('init_idx', 'int64'),
    ('init_price', 'float64'),
    ('init_size', 'float64'),
    ('init_size_type', 'int64'),
    ('init_direction', 'int64'),
    ('init_stop_type', 'int64'),
    ('delta', 'float64'),
    ('delta_format', 'int64'),
    ('tif', 'int64'),
    ('expiry', 'int64'),
    ('time_delta_format', 'int64'),
    ('reverse', 'float64'),
    ('order_price', 'float64')
])

Attributes

signal_idx
Signal row.
creation_idx
Limit creation row.
init_idx
Initial row from where order information is taken.
init_price
Initial price.
init_size
Order size.
init_size_type
See SizeType.
init_direction
See Direction.
init_stop_type
See StopType.
delta
Delta from the initial price.
delta_format
See DeltaFormat.
tif
Time in force in integer format. Set to -1 to disable.
expiry
Expiry time in integer format. Set to -1 to disable.
time_delta_format
See TimeDeltaFormat.
reverse
Whether to reverse the price hit detection.
order_price
See LimitOrderPrice.

limit_info_fields list

Fields for limit_info_dt.


log_dt VoidDType

np.dtype of log records.

np.dtype([
    ('id', 'int64'),
    ('group', 'int64'),
    ('col', 'int64'),
    ('idx', 'int64'),
    ('price_area_open', 'float64'),
    ('price_area_high', 'float64'),
    ('price_area_low', 'float64'),
    ('price_area_close', 'float64'),
    ('st0_cash', 'float64'),
    ('st0_position', 'float64'),
    ('st0_debt', 'float64'),
    ('st0_locked_cash', 'float64'),
    ('st0_free_cash', 'float64'),
    ('st0_val_price', 'float64'),
    ('st0_value', 'float64'),
    ('req_size', 'float64'),
    ('req_price', 'float64'),
    ('req_size_type', 'int64'),
    ('req_direction', 'int64'),
    ('req_fees', 'float64'),
    ('req_fixed_fees', 'float64'),
    ('req_slippage', 'float64'),
    ('req_min_size', 'float64'),
    ('req_max_size', 'float64'),
    ('req_size_granularity', 'float64'),
    ('req_leverage', 'float64'),
    ('req_leverage_mode', 'int64'),
    ('req_reject_prob', 'float64'),
    ('req_price_area_vio_mode', 'int64'),
    ('req_allow_partial', 'bool'),
    ('req_raise_reject', 'bool'),
    ('req_log', 'bool'),
    ('res_size', 'float64'),
    ('res_price', 'float64'),
    ('res_fees', 'float64'),
    ('res_side', 'int64'),
    ('res_status', 'int64'),
    ('res_status_info', 'int64'),
    ('st1_cash', 'float64'),
    ('st1_position', 'float64'),
    ('st1_debt', 'float64'),
    ('st1_locked_cash', 'float64'),
    ('st1_free_cash', 'float64'),
    ('st1_val_price', 'float64'),
    ('st1_value', 'float64'),
    ('order_id', 'int64')
])

log_fields list

Fields for log_fields.


main_info_dt VoidDType

np.dtype of main information records.

np.dtype([
    ('bar_zone', 'int64'),
    ('signal_idx', 'int64'),
    ('creation_idx', 'int64'),
    ('idx', 'int64'),
    ('val_price', 'float64'),
    ('price', 'float64'),
    ('size', 'float64'),
    ('size_type', 'int64'),
    ('direction', 'int64'),
    ('type', 'int64'),
    ('stop_type', 'int64')
])

Attributes

bar_zone
See BarZone.
signal_idx
Row where signal was placed.
creation_idx
Row where order was created.
i
Row from where order information was taken.
val_price
Valuation price.
price
Requested price.
size
Order size.
size_type
See SizeType.
direction
See Direction.
type
See OrderType.
stop_type
See StopType.

main_info_fields list

Fields for main_info_dt.


order_dt VoidDType

np.dtype of order records.

np.dtype([
    ('id', 'int64'),
    ('col', 'int64'),
    ('idx', 'int64'),
    ('size', 'float64'),
    ('price', 'float64'),
    ('fees', 'float64'),
    ('side', 'int64')
])

order_fields list

Fields for order_dt.


sl_info_dt VoidDType

np.dtype of SL information records.

np.dtype([
    ('init_idx', 'int64'),
    ('init_price', 'float64'),
    ('init_position', 'float64'),
    ('stop', 'float64'),
    ('exit_price', 'float64'),
    ('exit_size', 'float64'),
    ('exit_size_type', 'int64'),
    ('exit_type', 'int64'),
    ('order_type', 'int64'),
    ('limit_delta', 'float64'),
    ('delta_format', 'int64'),
    ('ladder', 'int64'),
    ('step', 'int64'),
    ('step_idx', 'int64')
])

Attributes

init_idx
Initial row.
init_price
Initial price.
init_position
Initial position.
stop
Latest updated stop value.
exit_price
See StopExitPrice.
exit_size
Order size.
exit_size_type
See SizeType.
exit_type
See StopExitType.
order_type
See OrderType.
limit_delta
Delta from the hit price. Only for StopType.Limit.
delta_format
See DeltaFormat.
ladder
See StopLadderMode.
step
Step in the ladder (i.e., the number of times the stop was executed)
step_idx
Step row.

sl_info_fields list

Fields for sl_info_dt.


status_info_desc list

Order status description.

[
    'Size is NaN',
    'Price is NaN',
    'Asset valuation price is NaN',
    'Asset/group value is NaN',
    'Asset/group value is zero or negative',
    'Size is zero',
    'Not enough cash',
    'No open position to reduce/close',
    'Size is greater than maximum allowed',
    'Random event happened',
    'Not enough cash to cover fees',
    'Final size is less than minimum allowed',
    'Final size is less than requested'
]

time_info_dt VoidDType

np.dtype of time information records.

np.dtype([
    ('init_idx', 'int64'),
    ('init_position', 'float64'),
    ('stop', 'int64'),
    ('exit_price', 'float64'),
    ('exit_size', 'float64'),
    ('exit_size_type', 'int64'),
    ('exit_type', 'int64'),
    ('order_type', 'int64'),
    ('limit_delta', 'float64'),
    ('delta_format', 'int64'),
    ('time_delta_format', 'int64'),
    ('ladder', 'int64'),
    ('step', 'int64'),
    ('step_idx', 'int64')
])

Attributes

init_idx
Initial row.
init_position
Initial position.
stop
Latest updated stop value.
exit_price
See StopExitPrice.
exit_size
Order size.
exit_size_type
See SizeType.
exit_type
See StopExitType.
order_type
See OrderType.
limit_delta
Delta from the hit price. Only for StopType.Limit.
delta_format
See DeltaFormat. Only for StopType.Limit.
time_delta_format
See TimeDeltaFormat.
ladder
See StopLadderMode.
step
Step in the ladder (i.e., the number of times the stop was executed)
step_idx
Step row.

time_info_fields list

Fields for time_info_dt.


tp_info_dt VoidDType

np.dtype of TP information records.

np.dtype([
    ('init_idx', 'int64'),
    ('init_price', 'float64'),
    ('init_position', 'float64'),
    ('stop', 'float64'),
    ('exit_price', 'float64'),
    ('exit_size', 'float64'),
    ('exit_size_type', 'int64'),
    ('exit_type', 'int64'),
    ('order_type', 'int64'),
    ('limit_delta', 'float64'),
    ('delta_format', 'int64'),
    ('ladder', 'int64'),
    ('step', 'int64'),
    ('step_idx', 'int64')
])

Attributes

init_idx
Initial row.
init_price
Initial price.
init_position
Initial position.
stop
Latest updated stop value.
exit_price
See StopExitPrice.
exit_size
Order size.
exit_size_type
See SizeType.
exit_type
See StopExitType.
order_type
See OrderType.
limit_delta
Delta from the hit price. Only for StopType.Limit.
delta_format
See DeltaFormat.
ladder
See StopLadderMode.
step
Step in the ladder (i.e., the number of times the stop was executed)
step_idx
Step row.

tp_info_fields list

Fields for tp_info_dt.


trade_dt VoidDType

np.dtype of trade records.

np.dtype([
    ('id', 'int64'),
    ('col', 'int64'),
    ('size', 'float64'),
    ('entry_order_id', 'int64'),
    ('entry_idx', 'int64'),
    ('entry_price', 'float64'),
    ('entry_fees', 'float64'),
    ('exit_order_id', 'int64'),
    ('exit_idx', 'int64'),
    ('exit_price', 'float64'),
    ('exit_fees', 'float64'),
    ('pnl', 'float64'),
    ('return', 'float64'),
    ('direction', 'int64'),
    ('status', 'int64'),
    ('parent_id', 'int64')
])

trade_fields list

Fields for trade_dt.


tsl_info_dt VoidDType

np.dtype of TSL information records.

np.dtype([
    ('init_idx', 'int64'),
    ('init_price', 'float64'),
    ('init_position', 'float64'),
    ('peak_idx', 'int64'),
    ('peak_price', 'float64'),
    ('stop', 'float64'),
    ('th', 'float64'),
    ('exit_price', 'float64'),
    ('exit_size', 'float64'),
    ('exit_size_type', 'int64'),
    ('exit_type', 'int64'),
    ('order_type', 'int64'),
    ('limit_delta', 'float64'),
    ('delta_format', 'int64'),
    ('ladder', 'int64'),
    ('step', 'int64'),
    ('step_idx', 'int64')
])

Attributes

init_idx
Initial row.
init_price
Initial price.
init_position
Initial position.
peak_idx
Row of the highest/lowest price.
peak_price
Highest/lowest price.
stop
Latest updated stop value.
th
Latest updated threshold value.
exit_price
See StopExitPrice.
exit_size
Order size.
exit_size_type
See SizeType.
exit_type
See StopExitType.
order_type
See OrderType.
limit_delta
Delta from the hit price. Only for StopType.Limit.
delta_format
See DeltaFormat.
ladder
See StopLadderMode.
step
Step in the ladder (i.e., the number of times the stop was executed)
step_idx
Step row.

tsl_info_fields list

Fields for tsl_info_dt.


AccountState class

AccountState(
    cash,
    position,
    debt,
    locked_cash,
    free_cash
)

State of the account.

Superclasses

  • builtins.tuple

cash method-wrapper

Cash.

Per group with cash sharing, otherwise per column.


debt method-wrapper

Debt.

Per column.


free_cash method-wrapper

Free cash.

Per group with cash sharing, otherwise per column.


locked_cash method-wrapper

Locked cash.

Per column.


position method-wrapper

Position.

Per column.


ExecState class

ExecState(
    cash,
    position,
    debt,
    locked_cash,
    free_cash,
    val_price,
    value
)

State before or after order execution.

Superclasses

  • builtins.tuple

cash method-wrapper

See AccountState.cash.


debt method-wrapper

See AccountState.debt.


free_cash method-wrapper

See AccountState.free_cash.


locked_cash method-wrapper

See AccountState.locked_cash.


position method-wrapper

See AccountState.position.


val_price method-wrapper

Valuation price in the current column.


value method-wrapper

Value in the current column (or group with cash sharing).


FOInOutputs class

FOInOutputs(
    cash,
    position,
    debt,
    locked_cash,
    free_cash,
    value,
    returns
)

A named tuple representing the in-outputs for simulation based on orders.

Superclasses

  • builtins.tuple

cash method-wrapper

See AccountState.cash.

Follows groups if cash sharing is enabled, otherwise columns.

Gets filled if save_state is True, otherwise has the shape (0, 0).


debt method-wrapper

See AccountState.debt.

Follows columns.

Gets filled if save_state is True, otherwise has the shape (0, 0).


free_cash method-wrapper

See AccountState.free_cash.

Follows groups if cash sharing is enabled, otherwise columns.

Gets filled if save_state is True, otherwise has the shape (0, 0).


locked_cash method-wrapper

See AccountState.locked_cash.

Follows columns.

Gets filled if save_state is True, otherwise has the shape (0, 0).


position method-wrapper

See AccountState.position.

Follows columns.

Gets filled if save_state is True, otherwise has the shape (0, 0).


returns method-wrapper

Returns.

Follows groups if cash sharing is enabled, otherwise columns.

Gets filled if save_returns is True, otherwise has the shape (0, 0).


value method-wrapper

Value.

Follows groups if cash sharing is enabled, otherwise columns.

Gets filled if fill_value is True, otherwise has the shape (0, 0).


FSInOutputs class

FSInOutputs(
    cash,
    position,
    debt,
    locked_cash,
    free_cash,
    value,
    returns
)

A named tuple representing the in-outputs for simulation based on signals.

Superclasses

  • builtins.tuple

cash method-wrapper

See FOInOutputs.cash.


debt method-wrapper

See FOInOutputs.debt.


free_cash method-wrapper

See FOInOutputs.free_cash.


locked_cash method-wrapper

See FOInOutputs.locked_cash.


position method-wrapper

See FOInOutputs.position.


returns method-wrapper

See FOInOutputs.returns.


value method-wrapper

See FOInOutputs.value.


FlexOrderContext class

FlexOrderContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    call_seq_now,
    call_idx
)

A named tuple representing the context of a flexible order.

Contains all fields from SegmentContext plus the current call index.

Passed to flex_order_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_idx method-wrapper

Index of the current call.


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


call_seq_now method-wrapper

See SegmentContext.call_seq_now.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


freq method-wrapper

See SimulationContext.freq.


from_col method-wrapper

See GroupContext.from_col.


group method-wrapper

See GroupContext.group.


group_len method-wrapper

See GroupContext.group_len.


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


i method-wrapper

See RowContext.i.


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


to_col method-wrapper

See GroupContext.to_col.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


GroupContext class

GroupContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col
)

A named tuple representing the context of a group.

A group is a set of nearby columns that are somehow related (for example, by sharing the same capital). In each row, the columns under the same group are bound to the same segment.

Contains all fields from SimulationContext plus fields describing the current group.

Passed to pre_group_func_nb and post_group_func_nb.

Example

Consider a group of three columns, a group of two columns, and one more column:

group group_len from_col to_col
0 3 0 3
1 2 3 5
2 1 5 6

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


freq method-wrapper

See SimulationContext.freq.


from_col method-wrapper

Index of the first column in the current group.

Has range [0, target_shape[1]).


group method-wrapper

Index of the current group.

Has range [0, group_lens.shape[0]).


group_len method-wrapper

Number of columns in the current group.

Scalar value. Same as group_lens[group].


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


to_col method-wrapper

Index of the last column in the current group plus one.

Has range [1, target_shape[1] + 1).

If columns are not grouped, equals to from_col + 1.

Warning

In the last group, to_col points at a column that doesn't exist.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


Order class

Order(
    size=inf,
    price=inf,
    size_type=0,
    direction=2,
    fees=0.0,
    fixed_fees=0.0,
    slippage=0.0,
    min_size=nan,
    max_size=nan,
    size_granularity=nan,
    leverage=1.0,
    leverage_mode=0,
    reject_prob=0.0,
    price_area_vio_mode=0,
    allow_partial=True,
    raise_reject=False,
    log=False
)

A named tuple representing an order.

Note

Currently, Numba has issues with using defaults when filling named tuples. Use order_nb() to create an order.

Superclasses

  • builtins.tuple

allow_partial method-wrapper

Whether to allow partial fill.

Otherwise, the order gets rejected.

Does not apply when Order.size is np.inf.


direction method-wrapper

See Direction.


fees method-wrapper

Fees in percentage of the order value.

Negative trading fees like -0.05 mean earning 5% per trade instead of paying a fee.

Note

0.01 = 1%.


fixed_fees method-wrapper

Fixed amount of fees to pay for this order.

Similar to Order.fees, can be negative.


leverage method-wrapper

Leverage.


leverage_mode method-wrapper

See LeverageMode.


log method-wrapper

Whether to log this order by filling a log record.

Remember to increase max_log_records.


max_size method-wrapper

Maximum size in both directions.

Depends on Order.size_type. Higher than that will be partly filled.


min_size method-wrapper

Minimum size in both directions.

Depends on Order.size_type. Lower than that will be rejected.


price method-wrapper

Price per unit.

Final price will depend upon slippage.

  • If -np.inf, gets replaced by the current open.
  • If np.inf, gets replaced by the current close.

Note

Make sure to use timestamps that come between (and ideally not including) the current open and close.


price_area_vio_mode method-wrapper

See PriceAreaVioMode.


raise_reject method-wrapper

Whether to raise exception if order has been rejected.

Terminates the simulation.


reject_prob method-wrapper

Probability of rejecting this order to simulate a random rejection event.

Not everything goes smoothly in real life. Use random rejections to test your order management for robustness.


size method-wrapper

Size in units.

Behavior depends upon Order.size_type and Order.direction.

For any fixed size:

  • Set to any number to buy/sell some fixed amount or value.
  • Set to np.inf to buy for all cash, or -np.inf to sell for all free cash. If Order.direction is not Direction.Both, -np.inf will close the position.
  • Set to np.nan or 0 to skip.

For any target size:

  • Set to any number to buy/sell an amount relative to the current position or value.
  • Set to 0 to close the current position.
  • Set to np.nan to skip.

size_granularity method-wrapper

Granularity of the size.

For example, granularity of 1.0 makes the quantity to behave like an integer. Placing an order of 12.5 shares (in any direction) will order exactly 12.0 shares.

Note

The filled size remains a floating number.


size_type method-wrapper

See SizeType.


slippage method-wrapper

Slippage in percentage of Order.price.

Slippage is a penalty applied on the price.

Note

0.01 = 1%.


OrderContext class

OrderContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    call_seq_now,
    col,
    call_idx,
    cash_now,
    position_now,
    debt_now,
    locked_cash_now,
    free_cash_now,
    val_price_now,
    value_now,
    return_now,
    pos_info_now
)

A named tuple representing the context of an order.

Contains all fields from SegmentContext plus fields describing the current state.

Passed to order_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_idx method-wrapper

Index of the current call in SegmentContext.call_seq_now.

Has range [0, group_len).


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


call_seq_now method-wrapper

See SegmentContext.call_seq_now.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_now method-wrapper

SimulationContext.last_cash for the current column/group.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


col method-wrapper

Current column.

Has range [0, target_shape[1]) and is always within [from_col, to_col).


debt_now method-wrapper

SimulationContext.last_debt for the current column.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


free_cash_now method-wrapper

SimulationContext.last_free_cash for the current column/group.


freq method-wrapper

See SimulationContext.freq.


from_col method-wrapper

See GroupContext.from_col.


group method-wrapper

See GroupContext.group.


group_len method-wrapper

See GroupContext.group_len.


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


i method-wrapper

See RowContext.i.


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


locked_cash_now method-wrapper

SimulationContext.last_locked_cash for the current column.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


pos_info_now method-wrapper

SimulationContext.last_pos_info for the current column.


position_now method-wrapper

SimulationContext.last_position for the current column.


return_now method-wrapper

SimulationContext.last_return for the current column/group.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


to_col method-wrapper

See GroupContext.to_col.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


val_price_now method-wrapper

SimulationContext.last_val_price for the current column.


value_now method-wrapper

SimulationContext.last_value for the current column/group.


OrderResult class

OrderResult(
    size,
    price,
    fees,
    side,
    status,
    status_info
)

A named tuple representing an order result.

Superclasses

  • builtins.tuple

fees method-wrapper

Total fees paid for this order.


price method-wrapper

Filled price per unit, adjusted with slippage.


side method-wrapper

See OrderSide.


size method-wrapper

Filled size.


status method-wrapper

See OrderStatus.


status_info method-wrapper

See OrderStatusInfo.


PostOrderContext class

PostOrderContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    call_seq_now,
    col,
    call_idx,
    cash_before,
    position_before,
    debt_before,
    locked_cash_before,
    free_cash_before,
    val_price_before,
    value_before,
    order_result,
    cash_now,
    position_now,
    debt_now,
    locked_cash_now,
    free_cash_now,
    val_price_now,
    value_now,
    return_now,
    pos_info_now
)

A named tuple representing the context after an order has been processed.

Contains all fields from OrderContext plus fields describing the order result and the previous state.

Passed to post_order_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_idx method-wrapper

See OrderContext.call_idx.


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


call_seq_now method-wrapper

See SegmentContext.call_seq_now.


cash_before method-wrapper

OrderContext.cash_now before execution.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_now method-wrapper

OrderContext.cash_now after execution.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


col method-wrapper

See OrderContext.col.


debt_before method-wrapper

OrderContext.debt_now before execution.


debt_now method-wrapper

OrderContext.debt_now after execution.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


free_cash_before method-wrapper

OrderContext.free_cash_now before execution.


free_cash_now method-wrapper

OrderContext.free_cash_now after execution.


freq method-wrapper

See SimulationContext.freq.


from_col method-wrapper

See GroupContext.from_col.


group method-wrapper

See GroupContext.group.


group_len method-wrapper

See GroupContext.group_len.


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


i method-wrapper

See RowContext.i.


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


locked_cash_before method-wrapper

OrderContext.locked_cash_now before execution.


locked_cash_now method-wrapper

OrderContext.locked_cash_now after execution.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


order_result method-wrapper

Order result of type OrderResult.

Can be used to check whether the order has been filled, ignored, or rejected.


pos_info_now method-wrapper

OrderContext.pos_info_now after execution.


position_before method-wrapper

OrderContext.position_now before execution.


position_now method-wrapper

OrderContext.position_now after execution.


return_now method-wrapper

OrderContext.return_now after execution.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


to_col method-wrapper

See GroupContext.to_col.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


val_price_before method-wrapper

OrderContext.val_price_now before execution.


val_price_now method-wrapper

OrderContext.val_price_now after execution.

If SimulationContext.update_value, gets replaced with the fill price, as it becomes the most recently known price. Otherwise, stays the same.


value_before method-wrapper

OrderContext.value_now before execution.


value_now method-wrapper

OrderContext.value_now after execution.

If SimulationContext.update_value, gets updated with the new cash and value of the column. Otherwise, stays the same.


PostSignalContext class

PostSignalContext(
    target_shape,
    group_lens,
    cash_sharing,
    index,
    freq,
    open,
    high,
    low,
    close,
    init_cash,
    init_position,
    init_price,
    order_records,
    order_counts,
    log_records,
    log_counts,
    track_cash_deposits,
    cash_deposits_out,
    track_cash_earnings,
    cash_earnings_out,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    last_limit_info,
    last_sl_info,
    last_tsl_info,
    last_tp_info,
    last_td_info,
    last_dt_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    col,
    cash_before,
    position_before,
    debt_before,
    locked_cash_before,
    free_cash_before,
    val_price_before,
    value_before,
    order_result
)

A named tuple representing the context after an order has been processed in a from-signals simulation.

Contains all fields from SignalContext plus the previous balances and order result.

Passed to post_signal_func_nb.

Superclasses

  • builtins.tuple

cash_before method-wrapper

ExecState.cash before execution.


cash_deposits_out method-wrapper

See SignalContext.cash_deposits_out.


cash_earnings_out method-wrapper

See SignalContext.cash_earnings_out.


cash_sharing method-wrapper

See SignalContext.cash_sharing.


close method-wrapper

See SignalContext.close.


col method-wrapper

See SignalContext.col.


debt_before method-wrapper

ExecState.debt before execution.


free_cash_before method-wrapper

ExecState.val_price before execution.


freq method-wrapper

See SignalContext.freq.


from_col method-wrapper

See SignalContext.from_col.


group method-wrapper

See SignalContext.group.


group_len method-wrapper

See SignalContext.group_len.


group_lens method-wrapper

See SignalContext.group_lens.


high method-wrapper

See SignalContext.high.


i method-wrapper

See SignalContext.i.


in_outputs method-wrapper

See SignalContext.in_outputs.


index method-wrapper

See SignalContext.index.


init_cash method-wrapper

See SignalContext.init_cash.


init_position method-wrapper

See SignalContext.init_position.


init_price method-wrapper

See SignalContext.init_price.


last_cash method-wrapper

See SignalContext.last_cash.


last_debt method-wrapper

See SignalContext.last_debt.


last_dt_info method-wrapper

See SignalContext.last_dt_info.


last_free_cash method-wrapper

See SignalContext.last_free_cash.


last_limit_info method-wrapper

See SignalContext.last_limit_info.


last_locked_cash method-wrapper

See SignalContext.last_locked_cash.


last_pos_info method-wrapper

See SignalContext.last_pos_info.


last_position method-wrapper

See SignalContext.last_position.


last_return method-wrapper

See SignalContext.last_return.


last_sl_info method-wrapper

See SignalContext.last_sl_info.


last_td_info method-wrapper

See SignalContext.last_td_info.


last_tp_info method-wrapper

See SignalContext.last_tp_info.


last_tsl_info method-wrapper

See SignalContext.last_tsl_info.


last_val_price method-wrapper

See SignalContext.last_val_price.


last_value method-wrapper

See SignalContext.last_value.


locked_cash_before method-wrapper

ExecState.free_cash before execution.


log_counts method-wrapper

See SignalContext.log_counts.


log_records method-wrapper

See SignalContext.log_records.


low method-wrapper

See SignalContext.low.


open method-wrapper

See SignalContext.open.


order_counts method-wrapper

See SignalContext.order_counts.


order_records method-wrapper

See SignalContext.order_records.


order_result method-wrapper

PostOrderContext.order_result.


position_before method-wrapper

ExecState.position before execution.


sim_end method-wrapper

See SignalContext.sim_end.


sim_start method-wrapper

See SignalContext.sim_start.


target_shape method-wrapper

See SignalContext.target_shape.


to_col method-wrapper

See SignalContext.to_col.


track_cash_deposits method-wrapper

See SignalContext.track_cash_deposits.


track_cash_earnings method-wrapper

See SignalContext.track_cash_earnings.


val_price_before method-wrapper

ExecState.value before execution.


value_before method-wrapper

Alias for field number 50


PriceArea class

PriceArea(
    open,
    high,
    low,
    close
)

Price area defined by four boundaries.

Used together with PriceAreaVioMode.

Superclasses

  • builtins.tuple

close method-wrapper

Closing price of the time step.

Violation takes place when adjusted price goes beyond this value.


high method-wrapper

Highest price of the time step.

Violation takes place when adjusted price goes above this value.


low method-wrapper

Lowest price of the time step.

Violation takes place when adjusted price goes below this value.


open method-wrapper

Opening price of the time step.


RejectedOrderError class

RejectedOrderError(
    *args,
    **kwargs
)

Rejected order error.

Superclasses

  • builtins.BaseException
  • builtins.Exception

RowContext class

RowContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    i
)

A named tuple representing the context of a row.

A row is a time step in which segments are executed.

Contains all fields from SimulationContext plus fields describing the current row.

Passed to pre_row_func_nb and post_row_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


freq method-wrapper

See SimulationContext.freq.


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


i method-wrapper

Index of the current row.

Has range [0, target_shape[0]).


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


SegmentContext class

SegmentContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    call_seq_now
)

A named tuple representing the context of a segment.

A segment is an intersection between groups and rows. It's an entity that defines how and in which order elements within the same group and row are processed.

Contains all fields from SimulationContext, GroupContext, and RowContext, plus fields describing the current segment.

Passed to pre_segment_func_nb and post_segment_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

See SimulationContext.bm_close.


call_post_segment method-wrapper

See SimulationContext.call_post_segment.


call_pre_segment method-wrapper

See SimulationContext.call_pre_segment.


call_seq method-wrapper

See SimulationContext.call_seq.


call_seq_now method-wrapper

Sequence of calls within the current segment.

Has shape (group_len,).

Each value in this sequence must indicate the position of column in the group to call next. Processing goes always from left to right.

You can use pre_segment_func_nb to override call_seq_now.

Example

[2, 0, 1] would first call column 2, then 0, and finally 1.


cash_deposits method-wrapper

See SimulationContext.cash_deposits.


cash_earnings method-wrapper

See SimulationContext.cash_earnings.


cash_sharing method-wrapper

See SimulationContext.cash_sharing.


close method-wrapper

See SimulationContext.close.


ffill_val_price method-wrapper

See SimulationContext.ffill_val_price.


fill_pos_info method-wrapper

See SimulationContext.fill_pos_info.


freq method-wrapper

See SimulationContext.freq.


from_col method-wrapper

See GroupContext.from_col.


group method-wrapper

See GroupContext.group.


group_len method-wrapper

See GroupContext.group_len.


group_lens method-wrapper

See SimulationContext.group_lens.


high method-wrapper

See SimulationContext.high.


i method-wrapper

See RowContext.i.


in_outputs method-wrapper

See SimulationContext.in_outputs.


index method-wrapper

See SimulationContext.index.


init_cash method-wrapper

See SimulationContext.init_cash.


init_position method-wrapper

See SimulationContext.init_position.


init_price method-wrapper

See SimulationContext.init_price.


last_cash method-wrapper

See SimulationContext.last_cash.


last_debt method-wrapper

See SimulationContext.last_debt.


last_free_cash method-wrapper

See SimulationContext.last_free_cash.


last_locked_cash method-wrapper

See SimulationContext.last_locked_cash.


last_pos_info method-wrapper

See SimulationContext.last_pos_info.


last_position method-wrapper

See SimulationContext.last_position.


last_return method-wrapper

See SimulationContext.last_return.


last_val_price method-wrapper

See SimulationContext.last_val_price.


last_value method-wrapper

See SimulationContext.last_value.


log_counts method-wrapper

See SimulationContext.log_counts.


log_records method-wrapper

See SimulationContext.log_records.


low method-wrapper

See SimulationContext.low.


open method-wrapper

See SimulationContext.open.


order_counts method-wrapper

See SimulationContext.order_counts.


order_records method-wrapper

See SimulationContext.order_records.


segment_mask method-wrapper

See SimulationContext.segment_mask.


sim_end method-wrapper

See SimulationContext.sim_end.


sim_start method-wrapper

See SimulationContext.sim_start.


target_shape method-wrapper

See SimulationContext.target_shape.


to_col method-wrapper

See GroupContext.to_col.


track_value method-wrapper

See SimulationContext.track_value.


update_value method-wrapper

See SimulationContext.update_value.


SignalContext class

SignalContext(
    target_shape,
    group_lens,
    cash_sharing,
    index,
    freq,
    open,
    high,
    low,
    close,
    init_cash,
    init_position,
    init_price,
    order_records,
    order_counts,
    log_records,
    log_counts,
    track_cash_deposits,
    cash_deposits_out,
    track_cash_earnings,
    cash_earnings_out,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    last_limit_info,
    last_sl_info,
    last_tsl_info,
    last_tp_info,
    last_td_info,
    last_dt_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i,
    col
)

A named tuple representing the context of an element in a from-signals simulation.

Contains all fields from SignalSegmentContext plus the column field.

Passed to signal_func_nb and adjust_func_nb.

Superclasses

  • builtins.tuple

cash_deposits_out method-wrapper

See SignalSegmentContext.cash_deposits_out.


cash_earnings_out method-wrapper

See SignalSegmentContext.cash_earnings_out.


cash_sharing method-wrapper

See SignalSegmentContext.cash_sharing.


close method-wrapper

See SignalSegmentContext.close.


col method-wrapper

See OrderContext.col.


freq method-wrapper

See SignalSegmentContext.freq.


from_col method-wrapper

See SignalSegmentContext.from_col.


group method-wrapper

See SignalSegmentContext.group.


group_len method-wrapper

See SignalSegmentContext.group_len.


group_lens method-wrapper

See SignalSegmentContext.group_lens.


high method-wrapper

See SignalSegmentContext.high.


i method-wrapper

See SignalSegmentContext.i.


in_outputs method-wrapper

See SignalSegmentContext.in_outputs.


index method-wrapper

See SignalSegmentContext.index.


init_cash method-wrapper

See SignalSegmentContext.init_cash.


init_position method-wrapper

See SignalSegmentContext.init_position.


init_price method-wrapper

See SignalSegmentContext.init_price.


last_cash method-wrapper

See SignalSegmentContext.last_cash.


last_debt method-wrapper

See SignalSegmentContext.last_debt.


last_dt_info method-wrapper

See SignalSegmentContext.last_dt_info.


last_free_cash method-wrapper

See SignalSegmentContext.last_free_cash.


last_limit_info method-wrapper

See SignalSegmentContext.last_limit_info.


last_locked_cash method-wrapper

See SignalSegmentContext.last_locked_cash.


last_pos_info method-wrapper

See SignalSegmentContext.last_pos_info.


last_position method-wrapper

See SignalSegmentContext.last_position.


last_return method-wrapper

See SignalSegmentContext.last_return.


last_sl_info method-wrapper

See SignalSegmentContext.last_sl_info.


last_td_info method-wrapper

See SignalSegmentContext.last_td_info.


last_tp_info method-wrapper

See SignalSegmentContext.last_tp_info.


last_tsl_info method-wrapper

See SignalSegmentContext.last_tsl_info.


last_val_price method-wrapper

See SignalSegmentContext.last_val_price.


last_value method-wrapper

See SignalSegmentContext.last_value.


log_counts method-wrapper

See SignalSegmentContext.log_counts.


log_records method-wrapper

See SignalSegmentContext.log_records.


low method-wrapper

See SignalSegmentContext.low.


open method-wrapper

See SignalSegmentContext.open.


order_counts method-wrapper

See SignalSegmentContext.order_counts.


order_records method-wrapper

See SignalSegmentContext.order_records.


sim_end method-wrapper

See SignalSegmentContext.sim_end.


sim_start method-wrapper

See SignalSegmentContext.sim_start.


target_shape method-wrapper

See SignalSegmentContext.target_shape.


to_col method-wrapper

See SignalSegmentContext.to_col.


track_cash_deposits method-wrapper

See SignalSegmentContext.track_cash_deposits.


track_cash_earnings method-wrapper

See SignalSegmentContext.track_cash_earnings.


SignalSegmentContext class

SignalSegmentContext(
    target_shape,
    group_lens,
    cash_sharing,
    index,
    freq,
    open,
    high,
    low,
    close,
    init_cash,
    init_position,
    init_price,
    order_records,
    order_counts,
    log_records,
    log_counts,
    track_cash_deposits,
    cash_deposits_out,
    track_cash_earnings,
    cash_earnings_out,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    last_limit_info,
    last_sl_info,
    last_tsl_info,
    last_tp_info,
    last_td_info,
    last_dt_info,
    sim_start,
    sim_end,
    group,
    group_len,
    from_col,
    to_col,
    i
)

A named tuple representing the context of a segment in a from-signals simulation.

Contains information related to the cascade of the simulation, such as OHLC, but also internal information that is not passed by the user but created at the beginning of the simulation. To make use of other information, such as order size, use templates.

Passed to post_segment_func_nb.

Superclasses

  • builtins.tuple

cash_deposits_out method-wrapper

See SimulationOutput.cash_deposits.


cash_earnings_out method-wrapper

See SimulationOutput.cash_earnings.


cash_sharing method-wrapper

See RowContext.cash_sharing.


close method-wrapper

See RowContext.close.


freq method-wrapper

See RowContext.freq.


from_col method-wrapper

See GroupContext.from_col.


group method-wrapper

See GroupContext.group.


group_len method-wrapper

See GroupContext.group_len.


group_lens method-wrapper

See RowContext.group_lens.


high method-wrapper

See RowContext.high.


i method-wrapper

See RowContext.i.


in_outputs method-wrapper

See FSInOutputs.


index method-wrapper

See RowContext.index.


init_cash method-wrapper

See RowContext.init_cash.


init_position method-wrapper

See RowContext.init_position.


init_price method-wrapper

See RowContext.init_price.


last_cash method-wrapper

See RowContext.last_cash.


last_debt method-wrapper

See RowContext.last_debt.


last_dt_info method-wrapper

Record of type time_info_dt per column.

Accessible via c.last_dt_info[field][col].


last_free_cash method-wrapper

See RowContext.last_free_cash.


last_limit_info method-wrapper

Record of type limit_info_dt per column.

Accessible via c.limit_info_dt[field][col].


last_locked_cash method-wrapper

See RowContext.last_locked_cash.


last_pos_info method-wrapper

See RowContext.last_pos_info.


last_position method-wrapper

See RowContext.last_position.


last_return method-wrapper

See RowContext.last_return.


last_sl_info method-wrapper

Record of type sl_info_dt per column.

Accessible via c.last_sl_info[field][col].


last_td_info method-wrapper

Record of type time_info_dt per column.

Accessible via c.last_td_info[field][col].


last_tp_info method-wrapper

Record of type tp_info_dt per column.

Accessible via c.last_tp_info[field][col].


last_tsl_info method-wrapper

Record of type tsl_info_dt per column.

Accessible via c.last_tsl_info[field][col].


last_val_price method-wrapper

See RowContext.last_val_price.


last_value method-wrapper

See RowContext.last_value.


log_counts method-wrapper

See RowContext.log_counts.


log_records method-wrapper

See RowContext.log_records.


low method-wrapper

See RowContext.low.


open method-wrapper

See RowContext.open.


order_counts method-wrapper

See RowContext.order_counts.


order_records method-wrapper

See RowContext.order_records.


sim_end method-wrapper

See RowContext.sim_end.


sim_start method-wrapper

See RowContext.sim_start.


target_shape method-wrapper

See RowContext.target_shape.


to_col method-wrapper

See GroupContext.to_col.


track_cash_deposits method-wrapper

Whether to track cash deposits.

Becomes True if any value in cash_deposits is not zero.


track_cash_earnings method-wrapper

Whether to track cash earnings.

Becomes True if any value in cash_earnings is not zero.


SimulationContext class

SimulationContext(
    target_shape,
    group_lens,
    cash_sharing,
    call_seq,
    init_cash,
    init_position,
    init_price,
    cash_deposits,
    cash_earnings,
    segment_mask,
    call_pre_segment,
    call_post_segment,
    index,
    freq,
    open,
    high,
    low,
    close,
    bm_close,
    ffill_val_price,
    update_value,
    fill_pos_info,
    track_value,
    order_records,
    order_counts,
    log_records,
    log_counts,
    in_outputs,
    last_cash,
    last_position,
    last_debt,
    last_locked_cash,
    last_free_cash,
    last_val_price,
    last_value,
    last_return,
    last_pos_info,
    sim_start,
    sim_end
)

A named tuple representing the context of a simulation.

Contains general information available to all other contexts.

Passed to pre_sim_func_nb and post_sim_func_nb.

Superclasses

  • builtins.tuple

bm_close method-wrapper

Benchmark closing price at each time step.

Must broadcast to shape SimulationContext.target_shape.


call_post_segment method-wrapper

Whether to call post_segment_func_nb regardless of SimulationContext.segment_mask.

Allows, for example, to write user-defined arrays such as returns at the end of each segment.


call_pre_segment method-wrapper

Whether to call pre_segment_func_nb regardless of SimulationContext.segment_mask.


call_seq method-wrapper

Default sequence of calls per segment.

Controls the sequence in which order_func_nb is executed within each segment.

Has shape SimulationContext.target_shape and each value must exist in the range [0, group_len). Can also be None if not provided.

Note

To use sort_call_seq_1d_nb, must be generated using CallSeqType.Default.

To change the call sequence dynamically, better change SegmentContext.call_seq_now in-place.

Example

The default call sequence for three data points and two groups with three columns each:

np.array([
    [0, 1, 2, 0, 1, 2],
    [0, 1, 2, 0, 1, 2],
    [0, 1, 2, 0, 1, 2]
])

cash_deposits method-wrapper

Cash to be deposited/withdrawn per column (or per group with cash sharing).

Utilizes flexible indexing using flex_select_nb().

Must broadcast to shape (target_shape[0], group_lens.shape[0]).

Cash is deposited/withdrawn right after pre_segment_func_nb. You can modify this array in pre_segment_func_nb.

Note

To modify the array in place, make sure to build an array of the full shape.


cash_earnings method-wrapper

Earnings to be added per column.

Utilizes flexible indexing using flex_select_nb().

Must broadcast to shape SimulationContext.target_shape.

Earnings are added right before post_segment_func_nb and are already included in the value of each group. You can modify this array in pre_segment_func_nb or post_order_func_nb.

Note

To modify the array in place, make sure to build an array of the full shape.


cash_sharing method-wrapper

Whether cash sharing is enabled.


close method-wrapper

Closing price at each time step.

Replaces Order.price in case it's np.inf.

Acts as a boundary - see PriceArea.close.

Utilizes flexible indexing using flex_select_nb().

Must broadcast to shape SimulationContext.target_shape.

Note

To modify the array in place, make sure to build an array of the full shape.


ffill_val_price method-wrapper

Whether to track valuation price only if it's known.

Otherwise, unknown SimulationContext.close will lead to NaN in valuation price at the next timestamp.


fill_pos_info method-wrapper

Whether to fill position record.

Disable this to make simulation faster for simple use cases.


freq method-wrapper

Frequency of index in integer (nanosecond) format.


group_lens method-wrapper

Number of columns in each group.

Even if columns are not grouped, group_lens contains ones - one column per group.

Note

Changing this array may produce results inconsistent with those of Portfolio.

Example

In pairs trading, group_lens would be np.array([2]), while three independent columns would be represented by group_lens of np.array([1, 1, 1]).


high method-wrapper

Highest price.

Similar behavior to that of SimulationContext.close.


in_outputs method-wrapper

Named tuple with in-output objects.

Can contain objects of arbitrary shape and type. Will be returned as part of SimulationOutput.


index method-wrapper

Index in integer (nanosecond) format.

If datetime-like, assumed to have the UTC timezone. Preset simulation methods will automatically format any index as UTC without actually converting it to UTC, that is, 12:00 +02:00 will become 12:00 +00:00 to avoid timezone conversion issues.


init_cash method-wrapper

Initial capital per column (or per group with cash sharing).

Utilizes flexible indexing using flex_select_1d_pc_nb().

Must broadcast to shape (group_lens.shape[0],) with cash sharing, otherwise (target_shape[1],).

Note

Changing this array may produce results inconsistent with those of Portfolio.

Example

Consider three columns, each having $100 of starting capital. If we built one group of two columns and one group of one column, the init_cash would be np.array([200, 100]) with cash sharing and np.array([100, 100, 100]) without cash sharing.


init_position method-wrapper

Initial position per column.

Utilizes flexible indexing using flex_select_1d_pc_nb().

Must broadcast to shape (target_shape[1],).

Note

Changing this array may produce results inconsistent with those of Portfolio.


init_price method-wrapper

Initial position price per column.

Utilizes flexible indexing using flex_select_1d_pc_nb().

Must broadcast to shape (target_shape[1],).

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_cash method-wrapper

Latest cash per column (or per group with cash sharing).

At the very first timestamp, contains initial capital.

Gets updated right after order_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_debt method-wrapper

Latest debt from leverage or shorting per column.

Has shape (target_shape[1],).

Gets updated right after order_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_free_cash method-wrapper

Latest free cash per column (or per group with cash sharing).

Free cash never goes above the initial level, because an operation always costs money.

Has shape (target_shape[1],).

Gets updated right after order_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_locked_cash method-wrapper

Latest locked cash from leverage or shorting per column.

Has shape (target_shape[1],).

Gets updated right after order_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_pos_info method-wrapper

Latest position record in each column.

It's a 1-dimensional array with records of type trade_dt.

Has shape (target_shape[1],).

If SimulationContext.init_position is not zero in a column, that column's position record is automatically filled before the simulation with entry_price set to SimulationContext.init_price and entry_idx of -1.

The fields entry_price and exit_price are average entry and exit price respectively. The average exit price does not contain open statistics, as opposed to Positions. On the other hand, fields pnl and return contain statistics as if the position has been closed and are re-calculated using SimulationContext.last_val_price right before and after pre_segment_func_nb, right after order_func_nb, and right before post_segment_func_nb.

Note

In an open position record, the field exit_price doesn't reflect the latest valuation price, but keeps the average price at which the position has been reduced.


last_position method-wrapper

Latest position per column.

At the very first timestamp, contains initial position.

Has shape (target_shape[1],).

Gets updated right after order_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_return method-wrapper

Latest return per column (or per group with cash sharing).

Has the same shape as SimulationContext.last_value.

Calculated by comparing the current SimulationContext.last_value to the last one of the previous row.

Gets updated each time SimulationContext.last_value is updated.

Note

Changing this array may produce results inconsistent with those of Portfolio.


last_val_price method-wrapper

Latest valuation price per column.

Has shape (target_shape[1],).

Enables SizeType.Value, SizeType.TargetValue, and SizeType.TargetPercent.

Gets multiplied by the current position to get the value of the column (see SimulationContext.last_value).

Gets updated right before pre_segment_func_nb using SimulationContext.open. Then, gets updated right after pre_segment_func_nb - you can use pre_segment_func_nb to override last_val_price in-place, such that order_func_nb can use the new group value. If SimulationContext.update_value, gets also updated right after order_func_nb using filled order price as the latest known price. Finally, gets updated right before post_segment_func_nb using SimulationContext.close.

If SimulationContext.ffill_val_price, gets updated only if the value is not NaN. For example, close of [1, 2, np.nan, np.nan, 5] yields valuation price of [1, 2, 2, 2, 5].

Note

You are not allowed to use -np.inf or np.inf - only finite values.

If SimulationContext.open is NaN in the first row, the last_val_price is also NaN.

Example

Consider 10 units in column 1 and 20 units in column 2. The current opening price of them is $40 and $50 respectively, which is also the default valuation price in the current row, available as last_val_price in pre_segment_func_nb. If both columns are in the same group with cash sharing, the group is valued at $1400 before any order_func_nb is called, and can be later accessed via OrderContext.value_now.


last_value method-wrapper

Latest value per column (or per group with cash sharing).

Calculated by multiplying the valuation price by the current position and adding the cash. The value in each column in a group with cash sharing is summed to get the value of the entire group.

Gets updated right before pre_segment_func_nb. Then, gets updated right after pre_segment_func_nb. If SimulationContext.update_value, gets also updated right after order_func_nb using filled order price as the latest known price (the difference will be minimal, only affected by costs). Finally, gets updated right before post_segment_func_nb.

Note

Changing this array may produce results inconsistent with those of Portfolio.


log_counts method-wrapper

Number of filled log records in each column.

Similar to SimulationContext.log_counts but for log records.

Note

Changing this array may produce results inconsistent with those of Portfolio.


log_records method-wrapper

Log records per column.

Similar to SimulationContext.order_records but of type log_dt and count SimulationContext.log_counts.


low method-wrapper

Lowest price.

Similar behavior to that of SimulationContext.close.


open method-wrapper

Opening price.

Replaces Order.price in case it's -np.inf.

Similar behavior to that of SimulationContext.close.


order_counts method-wrapper

Number of filled order records in each column.

Points to SimulationContext.order_records and has shape (target_shape[1],).

Example

order_counts of np.array([2, 100, 0]) means the latest filled order is order_records[1, 0] in the first column, order_records[99, 1] in the second column, and no orders have been filled yet in the third column (order_records[0, 2] is empty).

Note

Changing this array may produce results inconsistent with those of Portfolio.


order_records method-wrapper

Order records per column.

It's a 2-dimensional array with records of type order_dt.

The array is initialized with empty records first (they contain random data), and then gradually filled with order data. The number of empty records depends upon max_order_records, but usually it matches the number of rows, meaning there is maximal one order record per element. max_order_records can be chosen lower if not every order_func_nb leads to a filled order, to save memory. It can also be chosen higher if more than one order per element is expected.

You can use SimulationContext.order_counts to get the number of filled orders in each column. To get all order records filled up to this point in a column, do order_records[:order_counts[col], col].

Example

Before filling, each order record looks like this:

np.array([(-8070450532247928832, -8070450532247928832, 4, 0., 0., 0., 5764616306889786413)]

After filling, it becomes like this:

np.array([(0, 0, 1, 50., 1., 0., 1)]

segment_mask method-wrapper

Mask of whether a particular segment should be executed.

A segment is simply a sequence of order_func_nb calls under the same group and row.

If a segment is inactive, any callback function inside of it will not be executed. You can still execute the segment's pre- and postprocessing function by enabling SimulationContext.call_pre_segment and SimulationContext.call_post_segment respectively.

Utilizes flexible indexing using flex_select_nb().

Must broadcast to shape (target_shape[0], group_lens.shape[0]).

Note

To modify the array in place, make sure to build an array of the full shape.

Example

Consider two groups with two columns each and the following activity mask:

np.array([[ True, False], 
          [False,  True]])

The first group is only executed in the first row and the second group is only executed in the second row.


sim_end method-wrapper

Alias for field number 38


sim_start method-wrapper

End of the simulation per column or group (also without cash sharing).

Changing in-place will apply to the current simulation if it's lower than the initial value.


target_shape method-wrapper

Target shape of the simulation.

A tuple with exactly two elements: the number of rows and columns.

Example

One day of minute data for three assets would yield a target_shape of (1440, 3), where the first axis are rows (minutes) and the second axis are columns (assets).


track_value method-wrapper

Whether to track value metrics such as the current valuation price, value, and return.

If False, 'SimulationContext.last_val_price', 'SimulationContext.last_value', and 'SimulationContext.last_return' will stay NaN and the statistics of any open position won't be updated. You won't be able to use SizeType.Value, SizeType.TargetValue, and SizeType.TargetPercent.

Disable this to make simulation faster for simple use cases.


update_value method-wrapper

Whether to update group value after each filled order.

Otherwise, stays the same for all columns in the group (the value is calculated only once, before executing any order).

The change is marginal and mostly driven by transaction costs and slippage.


SimulationOutput class

SimulationOutput(
    order_records,
    log_records,
    cash_deposits,
    cash_earnings,
    call_seq,
    in_outputs,
    sim_start,
    sim_end
)

A named tuple representing the output of a simulation.

Superclasses

  • builtins.tuple

call_seq method-wrapper

Call sequence.

If not tracked, becomes None.


cash_deposits method-wrapper

Cash deposited/withdrawn at each timestamp.

If not tracked, becomes zero of shape (1, 1).


cash_earnings method-wrapper

Cash earnings added/removed at each timestamp.

If not tracked, becomes zero of shape (1, 1).


in_outputs method-wrapper

Named tuple with in-output objects.

If not tracked, becomes None.


log_records method-wrapper

Log records (flattened).


order_records method-wrapper

Order records (flattened).


sim_end method-wrapper

End of the simulation per column.

Use vectorbtpro.generic.nb.base.prepare_ungrouped_sim_range_nb to ungroup the array.

If not tracked, becomes None.


sim_start method-wrapper

Start of the simulation per column.

Use vectorbtpro.generic.nb.base.prepare_ungrouped_sim_range_nb to ungroup the array.

If not tracked, becomes None.