enums module¶
Named tuples and enumerated types for portfolio.
Defines enums and other schemas for vectorbtpro.portfolio.
AccumulationMode namedtuple¶
Accumulation mode.
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 namedtuple¶
Call sequence type.
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 namedtuple¶
Conflict mode.
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 namedtuple¶
Delta format.
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 namedtuple¶
Position direction.
Attributes
LongOnly- Only long positions.
ShortOnly- Only short positions.
Both- Both long and short positions.
DirectionConflictMode namedtuple¶
Direction conflict mode.
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 namedtuple¶
Initial cash mode.
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 namedtuple¶
Leverage mode.
Attributes
Lazy- Applies leverage only if free cash has been exhausted.
Eager- Applies leverage to each order.
LimitOrderPrice namedtuple¶
Limit order price.
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 namedtuple¶
Order that should not be processed.
NoPriceArea namedtuple¶
No price area.
OppositeEntryMode namedtuple¶
Opposite entry mode.
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 namedtuple¶
Order price error.
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 namedtuple¶
Order side.
OrderStatus namedtuple¶
Order status.
Attributes
Filled- Order has been filled.
Ignored- Order has been ignored.
Rejected- Order has been rejected.
OrderStatusInfo namedtuple¶
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 namedtuple¶
Order type.
PendingConflictMode namedtuple¶
Conflict mode for pending signals.
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 namedtuple¶
Position feature.
PriceAreaVioMode namedtuple¶
Price are violation mode.
Attributes
Ignore- Ignore any violation.
Cap- Cap price to prevent violation.
Error- Throw an error upon violation.
PriceType namedtuple¶
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.infandfrom_agowill be set to 1. NextClose-
Next closing price.
Will be substituted by
np.infandfrom_agowill be set to 1. NextValidOpen-
Next valid (non-NA) opening price.
Will be substituted by
-np.infandfrom_agowill be set to the distance to the previous valid value. NextValidClose-
Next valid (non-NA) closing price.
Will be substituted by
np.infandfrom_agowill be set to the distance to the previous valid value.
SizeType namedtuple¶
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.Amountusing 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%
- When long buying, the percentage of ExecState.free_cash
- When long selling, the percentage of ExecState.position
- When short selling, the percentage of ExecState.free_cash
- When short buying, the percentage of ExecState.free_cash, ExecState.debt, and ExecState.locked_cash
- When reversing, the percentage is getting applied on the final position
Percent100SizeType.Percentwhere 1.0 means 1%.ValuePercent-
Percentage of total value.
Uses ExecState.value to get the current total value. Gets converted into
SizeType.Value. ValuePercent100SizeType.ValuePercentwhere 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_nowto get the current total value. Gets converted intoSizeType.TargetValue. TargetPercent100SizeType.TargetPercentwhere 1.0 means 1%.
StopEntryPrice namedtuple¶
Stop entry price.
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 namedtuple¶
Stop exit price.
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 namedtuple¶
Stop exit type.
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 namedtuple¶
Stop ladder mode.
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 namedtuple¶
Stop update mode.
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 namedtuple¶
Time delta format.
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 namedtuple¶
Trade direction.
TradeStatus namedtuple¶
Event status.
TradesType namedtuple¶
Trades type.
ValPriceType namedtuple¶
Asset valuation price type.
Attributes
Latest- Latest price. Will be substituted by
-np.inf. Price- Order price. Will be substituted by
np.inf.
alloc_point_dt dtype¶
np.dtype of allocation point records.
alloc_point_fields list¶
Fields for alloc_point_dt.
alloc_range_dt dtype¶
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 dtype¶
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 dtype¶
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
-1to disable. expiry- Expiry time in integer format. Set to
-1to 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 dtype¶
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 dtype¶
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 dtype¶
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 dtype¶
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 dtype¶
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 dtype¶
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 dtype¶
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 dtype¶
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¶
State of the account.
Superclasses
builtins.tuple
cash field¶
Cash.
Per group with cash sharing, otherwise per column.
debt field¶
Debt.
Per column.
free_cash field¶
Free cash.
Per group with cash sharing, otherwise per column.
locked_cash field¶
Locked cash.
Per column.
position field¶
Position.
Per column.
ExecState class¶
State before or after order execution.
Superclasses
builtins.tuple
cash field¶
See AccountState.cash.
debt field¶
See AccountState.debt.
free_cash field¶
locked_cash field¶
position field¶
val_price field¶
Valuation price in the current column.
value field¶
Value in the current column (or group with cash sharing).
FOInOutputs class¶
A named tuple representing the in-outputs for simulation based on orders.
Superclasses
builtins.tuple
cash field¶
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 field¶
See AccountState.debt.
Follows columns.
Gets filled if save_state is True, otherwise has the shape (0, 0).
free_cash field¶
Follows groups if cash sharing is enabled, otherwise columns.
Gets filled if save_state is True, otherwise has the shape (0, 0).
locked_cash field¶
Follows columns.
Gets filled if save_state is True, otherwise has the shape (0, 0).
position field¶
Follows columns.
Gets filled if save_state is True, otherwise has the shape (0, 0).
returns field¶
Returns.
Follows groups if cash sharing is enabled, otherwise columns.
Gets filled if save_returns is True, otherwise has the shape (0, 0).
value field¶
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¶
A named tuple representing the in-outputs for simulation based on signals.
Superclasses
builtins.tuple
cash field¶
See FOInOutputs.cash.
debt field¶
See FOInOutputs.debt.
free_cash field¶
locked_cash field¶
position field¶
See FOInOutputs.position.
returns field¶
See FOInOutputs.returns.
value field¶
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 field¶
See SimulationContext.bm_close.
call_idx field¶
Index of the current call.
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
call_seq_now field¶
See SegmentContext.call_seq_now.
cash_deposits field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
freq field¶
from_col field¶
group field¶
See GroupContext.group.
group_len field¶
group_lens field¶
See SimulationContext.group_lens.
high field¶
i field¶
See RowContext.i.
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
to_col field¶
See GroupContext.to_col.
track_value field¶
See SimulationContext.track_value.
update_value field¶
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 field¶
See SimulationContext.bm_close.
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
cash_deposits field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
freq field¶
from_col field¶
Index of the first column in the current group.
Has range [0, target_shape[1]).
group field¶
Index of the current group.
Has range [0, group_lens.shape[0]).
group_len field¶
Number of columns in the current group.
Scalar value. Same as group_lens[group].
group_lens field¶
See SimulationContext.group_lens.
high field¶
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
to_col field¶
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 field¶
See SimulationContext.track_value.
update_value field¶
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 field¶
Whether to allow partial fill.
Otherwise, the order gets rejected.
Does not apply when Order.size is np.inf.
direction field¶
See Direction.
fees field¶
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 field¶
Fixed amount of fees to pay for this order.
Similar to Order.fees, can be negative.
leverage field¶
Leverage.
leverage_mode field¶
See LeverageMode.
log field¶
Whether to log this order by filling a log record.
Remember to increase max_log_records.
max_size field¶
Maximum size in both directions.
Depends on Order.size_type. Higher than that will be partly filled.
min_size field¶
Minimum size in both directions.
Depends on Order.size_type. Lower than that will be rejected.
price field¶
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 field¶
See PriceAreaVioMode.
raise_reject field¶
Whether to raise exception if order has been rejected.
Terminates the simulation.
reject_prob field¶
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 field¶
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.infto buy for all cash, or-np.infto sell for all free cash. If Order.direction is notDirection.Both,-np.infwill close the position. - Set to
np.nanor 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.nanto skip.
size_granularity field¶
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 field¶
See SizeType.
slippage field¶
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 field¶
See SimulationContext.bm_close.
call_idx field¶
Index of the current call in SegmentContext.call_seq_now.
Has range [0, group_len).
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
call_seq_now field¶
See SegmentContext.call_seq_now.
cash_deposits field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_now field¶
SimulationContext.last_cash for the current column/group.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
col field¶
Current column.
Has range [0, target_shape[1]) and is always within [from_col, to_col).
debt_now field¶
SimulationContext.last_debt for the current column.
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
free_cash_now field¶
SimulationContext.last_free_cash for the current column/group.
freq field¶
from_col field¶
group field¶
See GroupContext.group.
group_len field¶
group_lens field¶
See SimulationContext.group_lens.
high field¶
i field¶
See RowContext.i.
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
locked_cash_now field¶
SimulationContext.last_locked_cash for the current column.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
pos_info_now field¶
SimulationContext.last_pos_info for the current column.
position_now field¶
SimulationContext.last_position for the current column.
return_now field¶
SimulationContext.last_return for the current column/group.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
to_col field¶
See GroupContext.to_col.
track_value field¶
See SimulationContext.track_value.
update_value field¶
See SimulationContext.update_value.
val_price_now field¶
SimulationContext.last_val_price for the current column.
value_now field¶
SimulationContext.last_value for the current column/group.
OrderResult class¶
A named tuple representing an order result.
Superclasses
builtins.tuple
fees field¶
Total fees paid for this order.
price field¶
Filled price per unit, adjusted with slippage.
side field¶
See OrderSide.
size field¶
Filled size.
status field¶
See OrderStatus.
status_info field¶
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 field¶
See SimulationContext.bm_close.
call_idx field¶
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
call_seq_now field¶
See SegmentContext.call_seq_now.
cash_before field¶
OrderContext.cash_now before execution.
cash_deposits field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_now field¶
OrderContext.cash_now after execution.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
col field¶
See OrderContext.col.
debt_before field¶
OrderContext.debt_now before execution.
debt_now field¶
OrderContext.debt_now after execution.
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
free_cash_before field¶
OrderContext.free_cash_now before execution.
free_cash_now field¶
OrderContext.free_cash_now after execution.
freq field¶
from_col field¶
group field¶
See GroupContext.group.
group_len field¶
group_lens field¶
See SimulationContext.group_lens.
high field¶
i field¶
See RowContext.i.
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
locked_cash_before field¶
OrderContext.locked_cash_now before execution.
locked_cash_now field¶
OrderContext.locked_cash_now after execution.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
order_result field¶
Order result of type OrderResult.
Can be used to check whether the order has been filled, ignored, or rejected.
pos_info_now field¶
OrderContext.pos_info_now after execution.
position_before field¶
OrderContext.position_now before execution.
position_now field¶
OrderContext.position_now after execution.
return_now field¶
OrderContext.return_now after execution.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
to_col field¶
See GroupContext.to_col.
track_value field¶
See SimulationContext.track_value.
update_value field¶
See SimulationContext.update_value.
val_price_before field¶
OrderContext.val_price_now before execution.
val_price_now field¶
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 field¶
OrderContext.value_now before execution.
value_now field¶
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 field¶
ExecState.cash before execution.
cash_deposits_out field¶
See SignalContext.cash_deposits_out.
cash_earnings_out field¶
See SignalContext.cash_earnings_out.
cash_sharing field¶
See SignalContext.cash_sharing.
close field¶
See SignalContext.close.
col field¶
See SignalContext.col.
debt_before field¶
ExecState.debt before execution.
free_cash_before field¶
ExecState.val_price before execution.
freq field¶
See SignalContext.freq.
from_col field¶
group field¶
See SignalContext.group.
group_len field¶
group_lens field¶
high field¶
See SignalContext.high.
i field¶
See SignalContext.i.
in_outputs field¶
index field¶
See SignalContext.index.
init_cash field¶
init_position field¶
See SignalContext.init_position.
init_price field¶
last_cash field¶
last_debt field¶
last_dt_info field¶
See SignalContext.last_dt_info.
last_free_cash field¶
See SignalContext.last_free_cash.
last_limit_info field¶
See SignalContext.last_limit_info.
last_locked_cash field¶
See SignalContext.last_locked_cash.
last_pos_info field¶
See SignalContext.last_pos_info.
last_position field¶
See SignalContext.last_position.
last_return field¶
See SignalContext.last_return.
last_sl_info field¶
See SignalContext.last_sl_info.
last_td_info field¶
See SignalContext.last_td_info.
last_tp_info field¶
See SignalContext.last_tp_info.
last_tsl_info field¶
See SignalContext.last_tsl_info.
last_val_price field¶
See SignalContext.last_val_price.
last_value field¶
locked_cash_before field¶
ExecState.free_cash before execution.
log_counts field¶
log_records field¶
See SignalContext.log_records.
low field¶
See SignalContext.low.
open field¶
See SignalContext.open.
order_counts field¶
See SignalContext.order_counts.
order_records field¶
See SignalContext.order_records.
order_result field¶
PostOrderContext.order_result.
position_before field¶
ExecState.position before execution.
sim_end field¶
sim_start field¶
target_shape field¶
See SignalContext.target_shape.
to_col field¶
See SignalContext.to_col.
track_cash_deposits field¶
See SignalContext.track_cash_deposits.
track_cash_earnings field¶
See SignalContext.track_cash_earnings.
val_price_before field¶
ExecState.value before execution.
value_before field¶
Alias for field number 50
PriceArea class¶
Price area defined by four boundaries.
Used together with PriceAreaVioMode.
Superclasses
builtins.tuple
close field¶
Closing price of the time step.
Violation takes place when adjusted price goes beyond this value.
high field¶
Highest price of the time step.
Violation takes place when adjusted price goes above this value.
low field¶
Lowest price of the time step.
Violation takes place when adjusted price goes below this value.
open field¶
Opening price of the time step.
RejectedOrderError class¶
Rejected order error.
Superclasses
builtins.BaseExceptionbuiltins.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 field¶
See SimulationContext.bm_close.
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
cash_deposits field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
freq field¶
group_lens field¶
See SimulationContext.group_lens.
high field¶
i field¶
Index of the current row.
Has range [0, target_shape[0]).
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
track_value field¶
See SimulationContext.track_value.
update_value field¶
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 field¶
See SimulationContext.bm_close.
call_post_segment field¶
See SimulationContext.call_post_segment.
call_pre_segment field¶
See SimulationContext.call_pre_segment.
call_seq field¶
See SimulationContext.call_seq.
call_seq_now field¶
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 field¶
See SimulationContext.cash_deposits.
cash_earnings field¶
See SimulationContext.cash_earnings.
cash_sharing field¶
See SimulationContext.cash_sharing.
close field¶
ffill_val_price field¶
See SimulationContext.ffill_val_price.
fill_pos_info field¶
See SimulationContext.fill_pos_info.
freq field¶
from_col field¶
group field¶
See GroupContext.group.
group_len field¶
group_lens field¶
See SimulationContext.group_lens.
high field¶
i field¶
See RowContext.i.
in_outputs field¶
See SimulationContext.in_outputs.
index field¶
init_cash field¶
See SimulationContext.init_cash.
init_position field¶
See SimulationContext.init_position.
init_price field¶
See SimulationContext.init_price.
last_cash field¶
See SimulationContext.last_cash.
last_debt field¶
See SimulationContext.last_debt.
last_free_cash field¶
See SimulationContext.last_free_cash.
last_locked_cash field¶
See SimulationContext.last_locked_cash.
last_pos_info field¶
See SimulationContext.last_pos_info.
last_position field¶
See SimulationContext.last_position.
last_return field¶
See SimulationContext.last_return.
last_val_price field¶
See SimulationContext.last_val_price.
last_value field¶
See SimulationContext.last_value.
log_counts field¶
See SimulationContext.log_counts.
log_records field¶
See SimulationContext.log_records.
low field¶
open field¶
order_counts field¶
See SimulationContext.order_counts.
order_records field¶
See SimulationContext.order_records.
segment_mask field¶
See SimulationContext.segment_mask.
sim_end field¶
See SimulationContext.sim_end.
sim_start field¶
See SimulationContext.sim_start.
target_shape field¶
See SimulationContext.target_shape.
to_col field¶
See GroupContext.to_col.
track_value field¶
See SimulationContext.track_value.
update_value field¶
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 field¶
See SignalSegmentContext.cash_deposits_out.
cash_earnings_out field¶
See SignalSegmentContext.cash_earnings_out.
cash_sharing field¶
See SignalSegmentContext.cash_sharing.
close field¶
See SignalSegmentContext.close.
col field¶
See OrderContext.col.
freq field¶
See SignalSegmentContext.freq.
from_col field¶
See SignalSegmentContext.from_col.
group field¶
See SignalSegmentContext.group.
group_len field¶
See SignalSegmentContext.group_len.
group_lens field¶
See SignalSegmentContext.group_lens.
high field¶
See SignalSegmentContext.high.
i field¶
in_outputs field¶
See SignalSegmentContext.in_outputs.
index field¶
See SignalSegmentContext.index.
init_cash field¶
See SignalSegmentContext.init_cash.
init_position field¶
See SignalSegmentContext.init_position.
init_price field¶
See SignalSegmentContext.init_price.
last_cash field¶
See SignalSegmentContext.last_cash.
last_debt field¶
See SignalSegmentContext.last_debt.
last_dt_info field¶
See SignalSegmentContext.last_dt_info.
last_free_cash field¶
See SignalSegmentContext.last_free_cash.
last_limit_info field¶
See SignalSegmentContext.last_limit_info.
last_locked_cash field¶
See SignalSegmentContext.last_locked_cash.
last_pos_info field¶
See SignalSegmentContext.last_pos_info.
last_position field¶
See SignalSegmentContext.last_position.
last_return field¶
See SignalSegmentContext.last_return.
last_sl_info field¶
See SignalSegmentContext.last_sl_info.
last_td_info field¶
See SignalSegmentContext.last_td_info.
last_tp_info field¶
See SignalSegmentContext.last_tp_info.
last_tsl_info field¶
See SignalSegmentContext.last_tsl_info.
last_val_price field¶
See SignalSegmentContext.last_val_price.
last_value field¶
See SignalSegmentContext.last_value.
log_counts field¶
See SignalSegmentContext.log_counts.
log_records field¶
See SignalSegmentContext.log_records.
low field¶
open field¶
See SignalSegmentContext.open.
order_counts field¶
See SignalSegmentContext.order_counts.
order_records field¶
See SignalSegmentContext.order_records.
sim_end field¶
See SignalSegmentContext.sim_end.
sim_start field¶
See SignalSegmentContext.sim_start.
target_shape field¶
See SignalSegmentContext.target_shape.
to_col field¶
See SignalSegmentContext.to_col.
track_cash_deposits field¶
See SignalSegmentContext.track_cash_deposits.
track_cash_earnings field¶
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 field¶
See SimulationOutput.cash_deposits.
cash_earnings_out field¶
See SimulationOutput.cash_earnings.
cash_sharing field¶
close field¶
See RowContext.close.
freq field¶
See RowContext.freq.
from_col field¶
group field¶
See GroupContext.group.
group_len field¶
group_lens field¶
high field¶
See RowContext.high.
i field¶
See RowContext.i.
in_outputs field¶
See FSInOutputs.
index field¶
See RowContext.index.
init_cash field¶
See RowContext.init_cash.
init_position field¶
init_price field¶
last_cash field¶
See RowContext.last_cash.
last_debt field¶
See RowContext.last_debt.
last_dt_info field¶
Record of type time_info_dt per column.
Accessible via c.last_dt_info[field][col].
last_free_cash field¶
See RowContext.last_free_cash.
last_limit_info field¶
Record of type limit_info_dt per column.
Accessible via c.limit_info_dt[field][col].
last_locked_cash field¶
See RowContext.last_locked_cash.
last_pos_info field¶
last_position field¶
last_return field¶
last_sl_info field¶
Record of type sl_info_dt per column.
Accessible via c.last_sl_info[field][col].
last_td_info field¶
Record of type time_info_dt per column.
Accessible via c.last_td_info[field][col].
last_tp_info field¶
Record of type tp_info_dt per column.
Accessible via c.last_tp_info[field][col].
last_tsl_info field¶
Record of type tsl_info_dt per column.
Accessible via c.last_tsl_info[field][col].
last_val_price field¶
See RowContext.last_val_price.
last_value field¶
log_counts field¶
log_records field¶
low field¶
See RowContext.low.
open field¶
See RowContext.open.
order_counts field¶
order_records field¶
sim_end field¶
See RowContext.sim_end.
sim_start field¶
See RowContext.sim_start.
target_shape field¶
to_col field¶
See GroupContext.to_col.
track_cash_deposits field¶
Whether to track cash deposits.
Becomes True if any value in cash_deposits is not zero.
track_cash_earnings field¶
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 field¶
Benchmark closing price at each time step.
Must broadcast to shape SimulationContext.target_shape.
call_post_segment field¶
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 field¶
Whether to call pre_segment_func_nb regardless of SimulationContext.segment_mask.
call_seq field¶
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:
cash_deposits field¶
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 field¶
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 field¶
Whether cash sharing is enabled.
close field¶
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 field¶
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 field¶
Whether to fill position record.
Disable this to make simulation faster for simple use cases.
freq field¶
Frequency of index in integer (nanosecond) format.
group_lens field¶
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 field¶
Highest price.
Similar behavior to that of SimulationContext.close.
in_outputs field¶
Named tuple with in-output objects.
Can contain objects of arbitrary shape and type. Will be returned as part of SimulationOutput.
index field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
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 field¶
Log records per column.
Similar to SimulationContext.order_records but of type log_dt and count SimulationContext.log_counts.
low field¶
Lowest price.
Similar behavior to that of SimulationContext.close.
open field¶
Opening price.
Replaces Order.price in case it's -np.inf.
Similar behavior to that of SimulationContext.close.
order_counts field¶
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 field¶
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:
After filling, it becomes like this:
segment_mask field¶
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:
The first group is only executed in the first row and the second group is only executed in the second row.
sim_end field¶
Alias for field number 38
sim_start field¶
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 field¶
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 field¶
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 field¶
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 field¶
Call sequence.
If not tracked, becomes None.
cash_deposits field¶
Cash deposited/withdrawn at each timestamp.
If not tracked, becomes zero of shape (1, 1).
cash_earnings field¶
Cash earnings added/removed at each timestamp.
If not tracked, becomes zero of shape (1, 1).
in_outputs field¶
Named tuple with in-output objects.
If not tracked, becomes None.
log_records field¶
Log records (flattened).
order_records field¶
Order records (flattened).
sim_end field¶
End of the simulation per column.
Use prepare_ungrouped_sim_range_nb to ungroup the array.
If not tracked, becomes None.
sim_start field¶
Start of the simulation per column.
Use prepare_ungrouped_sim_range_nb to ungroup the array.
If not tracked, becomes None.