trades module¶
Base class for working with trade records.
Trade records capture information on trades.
In vectorbt, a trade is a sequence of orders that starts with an opening order and optionally ends with a closing order. Every pair of opposite orders can be represented by a trade. Each trade has a PnL info attached to quickly assess its performance. An interesting effect of this representation is the ability to aggregate trades: if two or more trades are happening one after another in time, they can be aggregated into a bigger trade. This way, for example, single-order trades can be aggregated into positions; but also multiple positions can be aggregated into a single blob that reflects the performance of the entire symbol.
Warning
All classes return both closed AND open trades/positions, which may skew your performance results. To only consider closed trades/positions, you should explicitly query the status_closed attribute.
Trade types¶
There are three main types of trades.
Entry trades¶
An entry trade is created from each order that opens or adds to a position.
For example, if we have a single large buy order and 100 smaller sell orders, we will see a single trade with the entry information copied from the buy order and the exit information being a size-weighted average over the exit information of all sell orders. On the other hand, if we have 100 smaller buy orders and a single sell order, we will see 100 trades, each with the entry information copied from the buy order and the exit information being a size-based fraction of the exit information of the sell order.
Use EntryTrades.from_orders to build entry trades from orders. Also available as Portfolio.entry_trades.
Exit trades¶
An exit trade is created from each order that closes or removes from a position.
Use ExitTrades.from_orders to build exit trades from orders. Also available as Portfolio.exit_trades.
Positions¶
A position is created from a sequence of entry or exit trades.
Use Positions.from_trades to build positions from entry or exit trades. Also available as Portfolio.positions.
Example¶
- Increasing position:
>>> from vectorbtpro import *
>>> # Entry trades
>>> pf_kwargs = dict(
... close=pd.Series([1., 2., 3., 4., 5.]),
... size=pd.Series([1., 1., 1., 1., -4.]),
... fixed_fees=1.
... )
>>> entry_trades = vbt.Portfolio.from_orders(**pf_kwargs).entry_trades
>>> entry_trades.readable
Entry Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
1 1 0 1.0 1 1 2.0
2 2 0 1.0 2 2 3.0
3 3 0 1.0 3 3 4.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 4 4 5.0 0.25 2.75
1 1.0 4 4 5.0 0.25 1.75
2 1.0 4 4 5.0 0.25 0.75
3 1.0 4 4 5.0 0.25 -0.25
Return Direction Status Position Id
0 2.7500 Long Closed 0
1 0.8750 Long Closed 0
2 0.2500 Long Closed 0
3 -0.0625 Long Closed 0
>>> # Exit trades
>>> exit_trades = vbt.Portfolio.from_orders(**pf_kwargs).exit_trades
>>> exit_trades.readable
Exit Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 4.0 0 0 2.5
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 4.0 4 4 5.0 1.0 5.0
Return Direction Status Position Id
0 0.5 Long Closed 0
>>> # Positions
>>> positions = vbt.Portfolio.from_orders(**pf_kwargs).positions
>>> positions.readable
Position Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 4.0 0 0 2.5
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 4.0 4 4 5.0 1.0 5.0
Return Direction Status
0 0.5 Long Closed
>>> entry_trades.pnl.sum() == exit_trades.pnl.sum() == positions.pnl.sum()
True
- Decreasing position:
>>> # Entry trades
>>> pf_kwargs = dict(
... close=pd.Series([1., 2., 3., 4., 5.]),
... size=pd.Series([4., -1., -1., -1., -1.]),
... fixed_fees=1.
... )
>>> entry_trades = vbt.Portfolio.from_orders(**pf_kwargs).entry_trades
>>> entry_trades.readable
Entry Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 4.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 4 4 3.5 4.0 5.0
Return Direction Status Position Id
0 1.25 Long Closed 0
>>> # Exit trades
>>> exit_trades = vbt.Portfolio.from_orders(**pf_kwargs).exit_trades
>>> exit_trades.readable
Exit Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
1 1 0 1.0 0 0 1.0
2 2 0 1.0 0 0 1.0
3 3 0 1.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 0.25 1 1 2.0 1.0 -0.25
1 0.25 2 2 3.0 1.0 0.75
2 0.25 3 3 4.0 1.0 1.75
3 0.25 4 4 5.0 1.0 2.75
Return Direction Status Position Id
0 -0.25 Long Closed 0
1 0.75 Long Closed 0
2 1.75 Long Closed 0
3 2.75 Long Closed 0
>>> # Positions
>>> positions = vbt.Portfolio.from_orders(**pf_kwargs).positions
>>> positions.readable
Position Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 4.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 4 4 3.5 4.0 5.0
Return Direction Status
0 1.25 Long Closed
>>> entry_trades.pnl.sum() == exit_trades.pnl.sum() == positions.pnl.sum()
True
- Multiple reversing positions:
>>> # Entry trades
>>> pf_kwargs = dict(
... close=pd.Series([1., 2., 3., 4., 5.]),
... size=pd.Series([1., -2., 2., -2., 1.]),
... fixed_fees=1.
... )
>>> entry_trades = vbt.Portfolio.from_orders(**pf_kwargs).entry_trades
>>> entry_trades.readable
Entry Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
1 1 0 1.0 1 1 2.0
2 2 0 1.0 2 2 3.0
3 3 0 1.0 3 3 4.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 1 1 2.0 0.5 -0.5
1 0.5 2 2 3.0 0.5 -2.0
2 0.5 3 3 4.0 0.5 0.0
3 0.5 4 4 5.0 1.0 -2.5
Return Direction Status Position Id
0 -0.500 Long Closed 0
1 -1.000 Short Closed 1
2 0.000 Long Closed 2
3 -0.625 Short Closed 3
>>> # Exit trades
>>> exit_trades = vbt.Portfolio.from_orders(**pf_kwargs).exit_trades
>>> exit_trades.readable
Exit Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
1 1 0 1.0 1 1 2.0
2 2 0 1.0 2 2 3.0
3 3 0 1.0 3 3 4.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 1 1 2.0 0.5 -0.5
1 0.5 2 2 3.0 0.5 -2.0
2 0.5 3 3 4.0 0.5 0.0
3 0.5 4 4 5.0 1.0 -2.5
Return Direction Status Position Id
0 -0.500 Long Closed 0
1 -1.000 Short Closed 1
2 0.000 Long Closed 2
3 -0.625 Short Closed 3
>>> # Positions
>>> positions = vbt.Portfolio.from_orders(**pf_kwargs).positions
>>> positions.readable
Position Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
1 1 0 1.0 1 1 2.0
2 2 0 1.0 2 2 3.0
3 3 0 1.0 3 3 4.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 1 1 2.0 0.5 -0.5
1 0.5 2 2 3.0 0.5 -2.0
2 0.5 3 3 4.0 0.5 0.0
3 0.5 4 4 5.0 1.0 -2.5
Return Direction Status
0 -0.500 Long Closed
1 -1.000 Short Closed
2 0.000 Long Closed
3 -0.625 Short Closed
>>> entry_trades.pnl.sum() == exit_trades.pnl.sum() == positions.pnl.sum()
True
- Open position:
>>> # Entry trades
>>> pf_kwargs = dict(
... close=pd.Series([1., 2., 3., 4., 5.]),
... size=pd.Series([1., 0., 0., 0., 0.]),
... fixed_fees=1.
... )
>>> entry_trades = vbt.Portfolio.from_orders(**pf_kwargs).entry_trades
>>> entry_trades.readable
Entry Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 -1 4 5.0 0.0 3.0
Return Direction Status Position Id
0 3.0 Long Open 0
>>> # Exit trades
>>> exit_trades = vbt.Portfolio.from_orders(**pf_kwargs).exit_trades
>>> exit_trades.readable
Exit Trade Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 -1 4 5.0 0.0 3.0
Return Direction Status Position Id
0 3.0 Long Open 0
>>> # Positions
>>> positions = vbt.Portfolio.from_orders(**pf_kwargs).positions
>>> positions.readable
Position Id Column Size Entry Order Id Entry Index Avg Entry Price \
0 0 0 1.0 0 0 1.0
Entry Fees Exit Order Id Exit Index Avg Exit Price Exit Fees PnL \
0 1.0 -1 4 5.0 0.0 3.0
Return Direction Status
0 3.0 Long Open
>>> entry_trades.pnl.sum() == exit_trades.pnl.sum() == positions.pnl.sum()
True
Get trade count, trade PnL, and winning trade PnL:
>>> price = pd.Series([1., 2., 3., 4., 3., 2., 1.])
>>> size = pd.Series([1., -0.5, -0.5, 2., -0.5, -0.5, -0.5])
>>> trades = vbt.Portfolio.from_orders(price, size).trades
>>> trades.count()
6
>>> trades.pnl.sum()
-3.0
>>> trades.winning.count()
2
>>> trades.winning.pnl.sum()
1.5
Get count and PnL of trades with duration of more than 2 days:
>>> mask = (trades.records['exit_idx'] - trades.records['entry_idx']) > 2
>>> trades_filtered = trades.apply_mask(mask)
>>> trades_filtered.count()
2
>>> trades_filtered.pnl.sum()
-3.0
Stats¶
Hint
See StatsBuilderMixin.stats and Trades.metrics.
>>> price = vbt.RandomData.pull(
... ['a', 'b'],
... start=datetime(2020, 1, 1),
... end=datetime(2020, 3, 1),
... seed=vbt.symbol_dict(a=42, b=43)
... ).get()
>>> size = pd.DataFrame({
... 'a': np.random.randint(-1, 2, size=len(price.index)),
... 'b': np.random.randint(-1, 2, size=len(price.index)),
... }, index=price.index, columns=price.columns)
>>> pf = vbt.Portfolio.from_orders(price, size, fees=0.01, init_cash="auto")
>>> pf.trades['a'].stats()
Start 2019-12-31 23:00:00+00:00
End 2020-02-29 23:00:00+00:00
Period 61 days 00:00:00
First Trade Start 2019-12-31 23:00:00+00:00
Last Trade End 2020-02-29 23:00:00+00:00
Coverage 60 days 00:00:00
Overlap Coverage 49 days 00:00:00
Total Records 19.0
Total Long Trades 2.0
Total Short Trades 17.0
Total Closed Trades 18.0
Total Open Trades 1.0
Open Trade PnL 16.063
Win Rate [%] 61.111111
Max Win Streak 11.0
Max Loss Streak 7.0
Best Trade [%] 3.526377
Worst Trade [%] -6.543679
Avg Winning Trade [%] 2.225861
Avg Losing Trade [%] -3.601313
Avg Winning Trade Duration 32 days 19:38:10.909090909
Avg Losing Trade Duration 5 days 00:00:00
Profit Factor 1.022425
Expectancy 0.028157
SQN 0.039174
Name: agg_stats, dtype: object
Positions share almost identical metrics with trades:
>>> pf.positions['a'].stats()
Start 2019-12-31 23:00:00+00:00
End 2020-02-29 23:00:00+00:00
Period 61 days 00:00:00
First Trade Start 2019-12-31 23:00:00+00:00
Last Trade End 2020-02-29 23:00:00+00:00
Coverage 60 days 00:00:00
Overlap Coverage 0 days 00:00:00
Total Records 5.0
Total Long Trades 2.0
Total Short Trades 3.0
Total Closed Trades 4.0
Total Open Trades 1.0
Open Trade PnL 38.356823
Win Rate [%] 0.0
Max Win Streak 0.0
Max Loss Streak 4.0
Best Trade [%] -1.529613
Worst Trade [%] -6.543679
Avg Winning Trade [%] NaN
Avg Losing Trade [%] -3.786739
Avg Winning Trade Duration NaT
Avg Losing Trade Duration 4 days 00:00:00
Profit Factor 0.0
Expectancy -5.446748
SQN -1.794214
Name: agg_stats, dtype: object
To also include open trades/positions when calculating metrics such as win rate, pass incl_open=True:
>>> pf.trades['a'].stats(settings=dict(incl_open=True))
Start 2019-12-31 23:00:00+00:00
End 2020-02-29 23:00:00+00:00
Period 61 days 00:00:00
First Trade Start 2019-12-31 23:00:00+00:00
Last Trade End 2020-02-29 23:00:00+00:00
Coverage 60 days 00:00:00
Overlap Coverage 49 days 00:00:00
Total Records 19.0
Total Long Trades 2.0
Total Short Trades 17.0
Total Closed Trades 18.0
Total Open Trades 1.0
Open Trade PnL 16.063
Win Rate [%] 61.111111
Max Win Streak 12.0
Max Loss Streak 7.0
Best Trade [%] 3.526377
Worst Trade [%] -6.543679
Avg Winning Trade [%] 2.238896
Avg Losing Trade [%] -3.601313
Avg Winning Trade Duration 33 days 18:00:00
Avg Losing Trade Duration 5 days 00:00:00
Profit Factor 1.733143
Expectancy 0.872096
SQN 0.804714
Name: agg_stats, dtype: object
StatsBuilderMixin.stats also supports (re-)grouping:
>>> pf.trades.stats(group_by=True)
Start 2019-12-31 23:00:00+00:00
End 2020-02-29 23:00:00+00:00
Period 61 days 00:00:00
First Trade Start 2019-12-31 23:00:00+00:00
Last Trade End 2020-02-29 23:00:00+00:00
Coverage 61 days 00:00:00
Overlap Coverage 61 days 00:00:00
Total Records 37
Total Long Trades 5
Total Short Trades 32
Total Closed Trades 35
Total Open Trades 2
Open Trade PnL 1.336259
Win Rate [%] 37.142857
Max Win Streak 11
Max Loss Streak 10
Best Trade [%] 3.526377
Worst Trade [%] -8.710238
Avg Winning Trade [%] 1.907799
Avg Losing Trade [%] -3.259135
Avg Winning Trade Duration 28 days 14:46:09.230769231
Avg Losing Trade Duration 14 days 00:00:00
Profit Factor 0.340493
Expectancy -1.292596
SQN -2.509223
Name: group, dtype: object
Plots¶
Hint
See PlotsBuilderMixin.plots and Trades.subplots.
Trades class has two subplots based on Trades.plot and Trades.plot_pnl:
entry_trades_field_config ReadonlyConfig¶
Field config for EntryTrades.
exit_trades_field_config ReadonlyConfig¶
Field config for ExitTrades.
positions_field_config ReadonlyConfig¶
Field config for Positions.
ReadonlyConfig(
settings=dict(
id=dict(
title='Position Id'
),
parent_id=dict(
title='Parent Id',
ignore=True
)
)
)
trades_attach_field_config ReadonlyConfig¶
Config of fields to be attached to Trades.
ReadonlyConfig(
return=dict(
attach='returns'
),
direction=dict(
attach_filters=True
),
status=dict(
attach_filters=True,
on_conflict='ignore'
)
)
trades_field_config ReadonlyConfig¶
Field config for Trades.
ReadonlyConfig(
dtype=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')
]),
settings=dict(
id=dict(
title='Trade Id'
),
idx=dict(
name='exit_idx'
),
start_idx=dict(
name='entry_idx'
),
end_idx=dict(
name='exit_idx'
),
size=dict(
title='Size'
),
entry_order_id=dict(
title='Entry Order Id',
mapping='ids'
),
entry_idx=dict(
title='Entry Index',
mapping='index'
),
entry_price=dict(
title='Avg Entry Price'
),
entry_fees=dict(
title='Entry Fees'
),
exit_order_id=dict(
title='Exit Order Id',
mapping='ids'
),
exit_idx=dict(
title='Exit Index',
mapping='index'
),
exit_price=dict(
title='Avg Exit Price'
),
exit_fees=dict(
title='Exit Fees'
),
pnl=dict(
title='PnL'
),
return=dict(
title='Return',
hovertemplate='$title: %{customdata[$index]:,%}'
),
direction=dict(
title='Direction',
mapping=TradeDirectionT(
Long=0,
Short=1
)
),
status=dict(
title='Status',
mapping=TradeStatusT(
Open=0,
Closed=1
)
),
parent_id=dict(
title='Position Id',
mapping='ids'
)
)
)
trades_shortcut_config ReadonlyConfig¶
Config of shortcut properties to be attached to Trades.
ReadonlyConfig(
ranges=dict(),
long_view=dict(),
short_view=dict(),
winning=dict(),
losing=dict(),
winning_streak=dict(
obj_type='mapped_array'
),
losing_streak=dict(
obj_type='mapped_array'
),
win_rate=dict(
obj_type='red_array'
),
profit_factor=dict(
obj_type='red_array',
method_kwargs=dict(
use_returns=False
)
),
rel_profit_factor=dict(
obj_type='red_array',
method_name='get_profit_factor',
method_kwargs=dict(
use_returns=True,
wrap_kwargs=dict(
name_or_index='rel_profit_factor'
)
)
),
expectancy=dict(
obj_type='red_array',
method_kwargs=dict(
use_returns=False
)
),
rel_expectancy=dict(
obj_type='red_array',
method_name='get_expectancy',
method_kwargs=dict(
use_returns=True,
wrap_kwargs=dict(
name_or_index='rel_expectancy'
)
)
),
sqn=dict(
obj_type='red_array',
method_kwargs=dict(
use_returns=False
)
),
rel_sqn=dict(
obj_type='red_array',
method_name='get_sqn',
method_kwargs=dict(
use_returns=True,
wrap_kwargs=dict(
name_or_index='rel_sqn'
)
)
),
best_price=dict(
obj_type='mapped_array'
),
worst_price=dict(
obj_type='mapped_array'
),
best_price_idx=dict(
obj_type='mapped_array'
),
worst_price_idx=dict(
obj_type='mapped_array'
),
expanding_best_price=dict(
obj_type='array'
),
expanding_worst_price=dict(
obj_type='array'
),
mfe=dict(
obj_type='mapped_array'
),
mfe_returns=dict(
obj_type='mapped_array',
method_name='get_mfe',
method_kwargs=dict(
use_returns=True
)
),
mae=dict(
obj_type='mapped_array'
),
mae_returns=dict(
obj_type='mapped_array',
method_name='get_mae',
method_kwargs=dict(
use_returns=True
)
),
expanding_mfe=dict(
obj_type='array'
),
expanding_mfe_returns=dict(
obj_type='array',
method_name='get_expanding_mfe',
method_kwargs=dict(
use_returns=True
)
),
expanding_mae=dict(
obj_type='array'
),
expanding_mae_returns=dict(
obj_type='array',
method_name='get_expanding_mae',
method_kwargs=dict(
use_returns=True
)
),
edge_ratio=dict(
obj_type='red_array'
),
running_edge_ratio=dict(
obj_type='array'
)
)
EntryTrades class¶
Extends Trades for working with entry trade records.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Ranges
- Records
- StatsBuilderMixin
- Trades
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.indexing_func
- PriceRecords.indexing_func_meta
- PriceRecords.resample
- PriceRecords.resolve_column_stack_kwargs
- PriceRecords.resolve_row_stack_kwargs
- Ranges.crop
- Ranges.filter_max_duration
- Ranges.filter_min_duration
- Ranges.from_array
- Ranges.from_delta
- Ranges.get_avg_duration
- Ranges.get_coverage
- Ranges.get_duration
- Ranges.get_first_idx
- Ranges.get_first_pd_mask
- Ranges.get_invalid
- Ranges.get_last_idx
- Ranges.get_last_pd_mask
- Ranges.get_max_duration
- Ranges.get_projections
- Ranges.get_ranges_pd_mask
- Ranges.get_real_duration
- Ranges.get_valid
- Ranges.plot_projections
- Ranges.plot_shapes
- Ranges.with_delta
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Trades.avg_duration
- Trades.bar_close
- Trades.bar_close_time
- Trades.bar_high
- Trades.bar_low
- Trades.bar_open
- Trades.bar_open_time
- Trades.best_price
- Trades.best_price_idx
- Trades.close
- Trades.cls_dir
- Trades.col
- Trades.col_arr
- Trades.col_mapper
- Trades.column_only_select
- Trades.config
- Trades.coverage
- Trades.direction
- Trades.direction_long
- Trades.direction_short
- Trades.duration
- Trades.edge_ratio
- Trades.end_idx
- Trades.entry_fees
- Trades.entry_idx
- Trades.entry_order_id
- Trades.entry_price
- Trades.exit_fees
- Trades.exit_idx
- Trades.exit_order_id
- Trades.exit_price
- Trades.expanding_best_price
- Trades.expanding_mae
- Trades.expanding_mae_returns
- Trades.expanding_mfe
- Trades.expanding_mfe_returns
- Trades.expanding_worst_price
- Trades.expectancy
- Trades.field_names
- Trades.first_idx
- Trades.first_pd_mask
- Trades.get_best_price
- Trades.get_best_price_idx
- Trades.get_edge_ratio
- Trades.get_expanding_best_price
- Trades.get_expanding_mae
- Trades.get_expanding_mfe
- Trades.get_expanding_worst_price
- Trades.get_expectancy
- Trades.get_long_view
- Trades.get_losing
- Trades.get_losing_streak
- Trades.get_mae
- Trades.get_mfe
- Trades.get_profit_factor
- Trades.get_ranges
- Trades.get_running_edge_ratio
- Trades.get_short_view
- Trades.get_sqn
- Trades.get_win_rate
- Trades.get_winning
- Trades.get_winning_streak
- Trades.get_worst_price
- Trades.get_worst_price_idx
- Trades.group_select
- Trades.high
- Trades.id
- Trades.id_arr
- Trades.idx_arr
- Trades.iloc
- Trades.indexing_kwargs
- Trades.invalid
- Trades.last_idx
- Trades.last_pd_mask
- Trades.loc
- Trades.long_view
- Trades.losing
- Trades.losing_streak
- Trades.low
- Trades.mae
- Trades.mae_returns
- Trades.max_duration
- Trades.mfe
- Trades.mfe_returns
- Trades.open
- Trades.overlap_coverage
- Trades.parent_id
- Trades.pd_mask
- Trades.plot
- Trades.plot_against_pnl
- Trades.plot_expanding
- Trades.plot_expanding_mae
- Trades.plot_expanding_mae_returns
- Trades.plot_expanding_mfe
- Trades.plot_expanding_mfe_returns
- Trades.plot_mae
- Trades.plot_mae_returns
- Trades.plot_mfe
- Trades.plot_mfe_returns
- Trades.plot_pnl
- Trades.plot_returns
- Trades.plot_running_edge_ratio
- Trades.plots_defaults
- Trades.pnl
- Trades.profit_factor
- Trades.projections
- Trades.range_only_select
- Trades.ranges
- Trades.ranges_pd_mask
- Trades.readable
- Trades.real_duration
- Trades.rec_state
- Trades.recarray
- Trades.records
- Trades.records_arr
- Trades.records_readable
- Trades.rel_expectancy
- Trades.rel_profit_factor
- Trades.rel_sqn
- Trades.returns
- Trades.running_edge_ratio
- Trades.self_aliases
- Trades.short_view
- Trades.size
- Trades.sqn
- Trades.start_idx
- Trades.stats_defaults
- Trades.status
- Trades.status_closed
- Trades.status_open
- Trades.unwrapped
- Trades.valid
- Trades.values
- Trades.win_rate
- Trades.winning
- Trades.winning_streak
- Trades.worst_price
- Trades.worst_price_idx
- Trades.wrapper
- Trades.xloc
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
field_config property¶
Field config of EntryTrades.
HybridConfig(
dtype=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')
]),
settings=dict(
id=dict(
name='id',
title='Entry Trade Id',
mapping='ids'
),
col=dict(
name='col',
title='Column',
mapping='columns',
as_customdata=False
),
idx=dict(
name='entry_idx',
title='Index',
mapping='index'
),
start_idx=dict(
title='Start Index',
mapping='index',
name='entry_idx'
),
end_idx=dict(
title='End Index',
mapping='index',
name='exit_idx'
),
status=dict(
title='Status',
mapping=TradeStatusT(
Open=0,
Closed=1
)
),
size=dict(
title='Size'
),
entry_order_id=dict(
title='Entry Order Id',
mapping='ids'
),
entry_idx=dict(
title='Entry Index',
mapping='index'
),
entry_price=dict(
title='Avg Entry Price'
),
entry_fees=dict(
title='Entry Fees'
),
exit_order_id=dict(
title='Exit Order Id',
mapping='ids'
),
exit_idx=dict(
title='Exit Index',
mapping='index'
),
exit_price=dict(
title='Avg Exit Price'
),
exit_fees=dict(
title='Exit Fees'
),
pnl=dict(
title='PnL'
),
return=dict(
title='Return',
hovertemplate='$title: %{customdata[$index]:,%}'
),
direction=dict(
title='Direction',
mapping=TradeDirectionT(
Long=0,
Short=1
)
),
parent_id=dict(
title='Position Id',
mapping='ids'
)
)
)
Returns EntryTrades._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change fields, you can either change the config in-place, override this property, or overwrite the instance variable EntryTrades._field_config.
from_orders class method¶
EntryTrades.from_orders(
orders,
open=None,
high=None,
low=None,
close=None,
init_position=0.0,
init_price=nan,
sim_start=None,
sim_end=None,
jitted=None,
chunked=None,
**kwargs
)
Build EntryTrades from Orders.
plot_signals method¶
EntryTrades.plot_signals(
column=None,
plot_ohlc=True,
plot_close=True,
ohlc_type=None,
ohlc_trace_kwargs=None,
close_trace_kwargs=None,
long_entry_trace_kwargs=None,
short_entry_trace_kwargs=None,
add_trace_kwargs=None,
fig=None,
**layout_kwargs
)
Plot entry trade signals.
Args
column:str- Name of the column to plot.
plot_ohlc:bool- Whether to plot OHLC.
plot_close:bool- Whether to plot close.
ohlc_type-
Either 'OHLC', 'Candlestick' or Plotly trace.
Pass None to use the default.
ohlc_trace_kwargs:dict- Keyword arguments passed to
ohlc_type. close_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor EntryTrades.close. long_entry_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Long Entry" markers. short_entry_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Short Entry" markers. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
>>> index = pd.date_range("2020", periods=7)
>>> price = pd.Series([1, 2, 3, 2, 3, 4, 3], index=index)
>>> orders = pd.Series([1, 0, -1, 0, -1, 2, -2], index=index)
>>> pf = vbt.Portfolio.from_orders(price, orders)
>>> pf.entry_trades.plot_signals().show()
ExitTrades class¶
Extends Trades for working with exit trade records.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Ranges
- Records
- StatsBuilderMixin
- Trades
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.indexing_func
- PriceRecords.indexing_func_meta
- PriceRecords.resample
- PriceRecords.resolve_column_stack_kwargs
- PriceRecords.resolve_row_stack_kwargs
- Ranges.crop
- Ranges.filter_max_duration
- Ranges.filter_min_duration
- Ranges.from_array
- Ranges.from_delta
- Ranges.get_avg_duration
- Ranges.get_coverage
- Ranges.get_duration
- Ranges.get_first_idx
- Ranges.get_first_pd_mask
- Ranges.get_invalid
- Ranges.get_last_idx
- Ranges.get_last_pd_mask
- Ranges.get_max_duration
- Ranges.get_projections
- Ranges.get_ranges_pd_mask
- Ranges.get_real_duration
- Ranges.get_valid
- Ranges.plot_projections
- Ranges.plot_shapes
- Ranges.with_delta
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Trades.avg_duration
- Trades.bar_close
- Trades.bar_close_time
- Trades.bar_high
- Trades.bar_low
- Trades.bar_open
- Trades.bar_open_time
- Trades.best_price
- Trades.best_price_idx
- Trades.close
- Trades.cls_dir
- Trades.col
- Trades.col_arr
- Trades.col_mapper
- Trades.column_only_select
- Trades.config
- Trades.coverage
- Trades.direction
- Trades.direction_long
- Trades.direction_short
- Trades.duration
- Trades.edge_ratio
- Trades.end_idx
- Trades.entry_fees
- Trades.entry_idx
- Trades.entry_order_id
- Trades.entry_price
- Trades.exit_fees
- Trades.exit_idx
- Trades.exit_order_id
- Trades.exit_price
- Trades.expanding_best_price
- Trades.expanding_mae
- Trades.expanding_mae_returns
- Trades.expanding_mfe
- Trades.expanding_mfe_returns
- Trades.expanding_worst_price
- Trades.expectancy
- Trades.field_names
- Trades.first_idx
- Trades.first_pd_mask
- Trades.get_best_price
- Trades.get_best_price_idx
- Trades.get_edge_ratio
- Trades.get_expanding_best_price
- Trades.get_expanding_mae
- Trades.get_expanding_mfe
- Trades.get_expanding_worst_price
- Trades.get_expectancy
- Trades.get_long_view
- Trades.get_losing
- Trades.get_losing_streak
- Trades.get_mae
- Trades.get_mfe
- Trades.get_profit_factor
- Trades.get_ranges
- Trades.get_running_edge_ratio
- Trades.get_short_view
- Trades.get_sqn
- Trades.get_win_rate
- Trades.get_winning
- Trades.get_winning_streak
- Trades.get_worst_price
- Trades.get_worst_price_idx
- Trades.group_select
- Trades.high
- Trades.id
- Trades.id_arr
- Trades.idx_arr
- Trades.iloc
- Trades.indexing_kwargs
- Trades.invalid
- Trades.last_idx
- Trades.last_pd_mask
- Trades.loc
- Trades.long_view
- Trades.losing
- Trades.losing_streak
- Trades.low
- Trades.mae
- Trades.mae_returns
- Trades.max_duration
- Trades.mfe
- Trades.mfe_returns
- Trades.open
- Trades.overlap_coverage
- Trades.parent_id
- Trades.pd_mask
- Trades.plot
- Trades.plot_against_pnl
- Trades.plot_expanding
- Trades.plot_expanding_mae
- Trades.plot_expanding_mae_returns
- Trades.plot_expanding_mfe
- Trades.plot_expanding_mfe_returns
- Trades.plot_mae
- Trades.plot_mae_returns
- Trades.plot_mfe
- Trades.plot_mfe_returns
- Trades.plot_pnl
- Trades.plot_returns
- Trades.plot_running_edge_ratio
- Trades.plots_defaults
- Trades.pnl
- Trades.profit_factor
- Trades.projections
- Trades.range_only_select
- Trades.ranges
- Trades.ranges_pd_mask
- Trades.readable
- Trades.real_duration
- Trades.rec_state
- Trades.recarray
- Trades.records
- Trades.records_arr
- Trades.records_readable
- Trades.rel_expectancy
- Trades.rel_profit_factor
- Trades.rel_sqn
- Trades.returns
- Trades.running_edge_ratio
- Trades.self_aliases
- Trades.short_view
- Trades.size
- Trades.sqn
- Trades.start_idx
- Trades.stats_defaults
- Trades.status
- Trades.status_closed
- Trades.status_open
- Trades.unwrapped
- Trades.valid
- Trades.values
- Trades.win_rate
- Trades.winning
- Trades.winning_streak
- Trades.worst_price
- Trades.worst_price_idx
- Trades.wrapper
- Trades.xloc
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
field_config property¶
Field config of ExitTrades.
HybridConfig(
dtype=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')
]),
settings=dict(
id=dict(
name='id',
title='Exit Trade Id',
mapping='ids'
),
col=dict(
name='col',
title='Column',
mapping='columns',
as_customdata=False
),
idx=dict(
name='exit_idx',
title='Index',
mapping='index'
),
start_idx=dict(
title='Start Index',
mapping='index',
name='entry_idx'
),
end_idx=dict(
title='End Index',
mapping='index',
name='exit_idx'
),
status=dict(
title='Status',
mapping=TradeStatusT(
Open=0,
Closed=1
)
),
size=dict(
title='Size'
),
entry_order_id=dict(
title='Entry Order Id',
mapping='ids'
),
entry_idx=dict(
title='Entry Index',
mapping='index'
),
entry_price=dict(
title='Avg Entry Price'
),
entry_fees=dict(
title='Entry Fees'
),
exit_order_id=dict(
title='Exit Order Id',
mapping='ids'
),
exit_idx=dict(
title='Exit Index',
mapping='index'
),
exit_price=dict(
title='Avg Exit Price'
),
exit_fees=dict(
title='Exit Fees'
),
pnl=dict(
title='PnL'
),
return=dict(
title='Return',
hovertemplate='$title: %{customdata[$index]:,%}'
),
direction=dict(
title='Direction',
mapping=TradeDirectionT(
Long=0,
Short=1
)
),
parent_id=dict(
title='Position Id',
mapping='ids'
)
)
)
Returns ExitTrades._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change fields, you can either change the config in-place, override this property, or overwrite the instance variable ExitTrades._field_config.
from_orders class method¶
ExitTrades.from_orders(
orders,
open=None,
high=None,
low=None,
close=None,
init_position=0.0,
init_price=nan,
sim_start=None,
sim_end=None,
jitted=None,
chunked=None,
**kwargs
)
Build ExitTrades from Orders.
plot_signals method¶
ExitTrades.plot_signals(
column=None,
plot_ohlc=True,
plot_close=True,
ohlc_type=None,
ohlc_trace_kwargs=None,
close_trace_kwargs=None,
long_exit_trace_kwargs=None,
short_exit_trace_kwargs=None,
add_trace_kwargs=None,
fig=None,
**layout_kwargs
)
Plot exit trade signals.
Args
column:str- Name of the column to plot.
plot_ohlc:bool- Whether to plot OHLC.
plot_close:bool- Whether to plot close.
ohlc_type-
Either 'OHLC', 'Candlestick' or Plotly trace.
Pass None to use the default.
ohlc_trace_kwargs:dict- Keyword arguments passed to
ohlc_type. close_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor ExitTrades.close. long_exit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Long Exit" markers. short_exit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Short Exit" markers. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
>>> index = pd.date_range("2020", periods=7)
>>> price = pd.Series([1, 2, 3, 2, 3, 4, 3], index=index)
>>> orders = pd.Series([1, 0, -1, 0, -1, 2, -2], index=index)
>>> pf = vbt.Portfolio.from_orders(price, orders)
>>> pf.exit_trades.plot_signals().show()
Positions class¶
Extends Trades for working with position records.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Ranges
- Records
- StatsBuilderMixin
- Trades
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.indexing_func
- PriceRecords.indexing_func_meta
- PriceRecords.resample
- PriceRecords.resolve_column_stack_kwargs
- PriceRecords.resolve_row_stack_kwargs
- Ranges.crop
- Ranges.filter_max_duration
- Ranges.filter_min_duration
- Ranges.from_array
- Ranges.from_delta
- Ranges.get_avg_duration
- Ranges.get_coverage
- Ranges.get_duration
- Ranges.get_first_idx
- Ranges.get_first_pd_mask
- Ranges.get_invalid
- Ranges.get_last_idx
- Ranges.get_last_pd_mask
- Ranges.get_max_duration
- Ranges.get_projections
- Ranges.get_ranges_pd_mask
- Ranges.get_real_duration
- Ranges.get_valid
- Ranges.plot_projections
- Ranges.plot_shapes
- Ranges.with_delta
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Trades.avg_duration
- Trades.bar_close
- Trades.bar_close_time
- Trades.bar_high
- Trades.bar_low
- Trades.bar_open
- Trades.bar_open_time
- Trades.best_price
- Trades.best_price_idx
- Trades.close
- Trades.cls_dir
- Trades.col
- Trades.col_arr
- Trades.col_mapper
- Trades.column_only_select
- Trades.config
- Trades.coverage
- Trades.direction
- Trades.direction_long
- Trades.direction_short
- Trades.duration
- Trades.edge_ratio
- Trades.end_idx
- Trades.entry_fees
- Trades.entry_idx
- Trades.entry_order_id
- Trades.entry_price
- Trades.exit_fees
- Trades.exit_idx
- Trades.exit_order_id
- Trades.exit_price
- Trades.expanding_best_price
- Trades.expanding_mae
- Trades.expanding_mae_returns
- Trades.expanding_mfe
- Trades.expanding_mfe_returns
- Trades.expanding_worst_price
- Trades.expectancy
- Trades.field_names
- Trades.first_idx
- Trades.first_pd_mask
- Trades.get_best_price
- Trades.get_best_price_idx
- Trades.get_edge_ratio
- Trades.get_expanding_best_price
- Trades.get_expanding_mae
- Trades.get_expanding_mfe
- Trades.get_expanding_worst_price
- Trades.get_expectancy
- Trades.get_long_view
- Trades.get_losing
- Trades.get_losing_streak
- Trades.get_mae
- Trades.get_mfe
- Trades.get_profit_factor
- Trades.get_ranges
- Trades.get_running_edge_ratio
- Trades.get_short_view
- Trades.get_sqn
- Trades.get_win_rate
- Trades.get_winning
- Trades.get_winning_streak
- Trades.get_worst_price
- Trades.get_worst_price_idx
- Trades.group_select
- Trades.high
- Trades.id
- Trades.id_arr
- Trades.idx_arr
- Trades.iloc
- Trades.indexing_kwargs
- Trades.invalid
- Trades.last_idx
- Trades.last_pd_mask
- Trades.loc
- Trades.long_view
- Trades.losing
- Trades.losing_streak
- Trades.low
- Trades.mae
- Trades.mae_returns
- Trades.max_duration
- Trades.mfe
- Trades.mfe_returns
- Trades.open
- Trades.overlap_coverage
- Trades.parent_id
- Trades.pd_mask
- Trades.plot
- Trades.plot_against_pnl
- Trades.plot_expanding
- Trades.plot_expanding_mae
- Trades.plot_expanding_mae_returns
- Trades.plot_expanding_mfe
- Trades.plot_expanding_mfe_returns
- Trades.plot_mae
- Trades.plot_mae_returns
- Trades.plot_mfe
- Trades.plot_mfe_returns
- Trades.plot_pnl
- Trades.plot_returns
- Trades.plot_running_edge_ratio
- Trades.plots_defaults
- Trades.pnl
- Trades.profit_factor
- Trades.projections
- Trades.range_only_select
- Trades.ranges
- Trades.ranges_pd_mask
- Trades.readable
- Trades.real_duration
- Trades.rec_state
- Trades.recarray
- Trades.records
- Trades.records_arr
- Trades.records_readable
- Trades.rel_expectancy
- Trades.rel_profit_factor
- Trades.rel_sqn
- Trades.returns
- Trades.running_edge_ratio
- Trades.self_aliases
- Trades.short_view
- Trades.size
- Trades.sqn
- Trades.start_idx
- Trades.stats_defaults
- Trades.status
- Trades.status_closed
- Trades.status_open
- Trades.unwrapped
- Trades.valid
- Trades.values
- Trades.win_rate
- Trades.winning
- Trades.winning_streak
- Trades.worst_price
- Trades.worst_price_idx
- Trades.wrapper
- Trades.xloc
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
field_config property¶
Field config of Positions.
HybridConfig(
dtype=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')
]),
settings=dict(
id=dict(
name='id',
title='Position Id',
mapping='ids'
),
col=dict(
name='col',
title='Column',
mapping='columns',
as_customdata=False
),
idx=dict(
name='exit_idx',
title='Index',
mapping='index'
),
start_idx=dict(
title='Start Index',
mapping='index',
name='entry_idx'
),
end_idx=dict(
title='End Index',
mapping='index',
name='exit_idx'
),
status=dict(
title='Status',
mapping=TradeStatusT(
Open=0,
Closed=1
)
),
size=dict(
title='Size'
),
entry_order_id=dict(
title='Entry Order Id',
mapping='ids'
),
entry_idx=dict(
title='Entry Index',
mapping='index'
),
entry_price=dict(
title='Avg Entry Price'
),
entry_fees=dict(
title='Entry Fees'
),
exit_order_id=dict(
title='Exit Order Id',
mapping='ids'
),
exit_idx=dict(
title='Exit Index',
mapping='index'
),
exit_price=dict(
title='Avg Exit Price'
),
exit_fees=dict(
title='Exit Fees'
),
pnl=dict(
title='PnL'
),
return=dict(
title='Return',
hovertemplate='$title: %{customdata[$index]:,%}'
),
direction=dict(
title='Direction',
mapping=TradeDirectionT(
Long=0,
Short=1
)
),
parent_id=dict(
title='Parent Id',
mapping='ids',
ignore=True
)
)
)
Returns Positions._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change fields, you can either change the config in-place, override this property, or overwrite the instance variable Positions._field_config.
from_trades class method¶
Positions.from_trades(
trades,
open=None,
high=None,
low=None,
close=None,
jitted=None,
chunked=None,
**kwargs
)
Trades class¶
Extends Ranges for working with trade-like records, such as entry trades, exit trades, and positions.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Ranges
- Records
- StatsBuilderMixin
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.indexing_func
- PriceRecords.indexing_func_meta
- PriceRecords.resample
- PriceRecords.resolve_column_stack_kwargs
- PriceRecords.resolve_row_stack_kwargs
- Ranges.avg_duration
- Ranges.bar_close
- Ranges.bar_close_time
- Ranges.bar_high
- Ranges.bar_low
- Ranges.bar_open
- Ranges.bar_open_time
- Ranges.close
- Ranges.cls_dir
- Ranges.col
- Ranges.col_arr
- Ranges.col_mapper
- Ranges.column_only_select
- Ranges.config
- Ranges.coverage
- Ranges.crop
- Ranges.duration
- Ranges.end_idx
- Ranges.field_names
- Ranges.filter_max_duration
- Ranges.filter_min_duration
- Ranges.first_idx
- Ranges.first_pd_mask
- Ranges.from_array
- Ranges.from_delta
- Ranges.get_avg_duration
- Ranges.get_coverage
- Ranges.get_duration
- Ranges.get_first_idx
- Ranges.get_first_pd_mask
- Ranges.get_invalid
- Ranges.get_last_idx
- Ranges.get_last_pd_mask
- Ranges.get_max_duration
- Ranges.get_projections
- Ranges.get_ranges_pd_mask
- Ranges.get_real_duration
- Ranges.get_valid
- Ranges.group_select
- Ranges.high
- Ranges.id
- Ranges.id_arr
- Ranges.idx_arr
- Ranges.iloc
- Ranges.indexing_kwargs
- Ranges.invalid
- Ranges.last_idx
- Ranges.last_pd_mask
- Ranges.loc
- Ranges.low
- Ranges.max_duration
- Ranges.open
- Ranges.overlap_coverage
- Ranges.pd_mask
- Ranges.plot_projections
- Ranges.plot_shapes
- Ranges.projections
- Ranges.range_only_select
- Ranges.ranges_pd_mask
- Ranges.readable
- Ranges.real_duration
- Ranges.rec_state
- Ranges.recarray
- Ranges.records
- Ranges.records_arr
- Ranges.records_readable
- Ranges.self_aliases
- Ranges.start_idx
- Ranges.status
- Ranges.status_closed
- Ranges.status_open
- Ranges.unwrapped
- Ranges.valid
- Ranges.values
- Ranges.with_delta
- Ranges.wrapper
- Ranges.xloc
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
Subclasses
best_price cacheable_property¶
Trades.get_best_price with default arguments.
best_price_idx cacheable_property¶
Trades.get_best_price_idx with default arguments.
direction cached_property¶
Mapped array of the field direction.
direction_long cached_property¶
Records filtered by direction == 0.
direction_short cached_property¶
Records filtered by direction == 1.
edge_ratio cached_property¶
Trades.get_edge_ratio with default arguments.
entry_fees cached_property¶
Mapped array of the field entry_fees.
entry_idx cached_property¶
Mapped array of the field entry_idx.
entry_order_id cached_property¶
Mapped array of the field entry_order_id.
entry_price cached_property¶
Mapped array of the field entry_price.
exit_fees cached_property¶
Mapped array of the field exit_fees.
exit_idx cached_property¶
Mapped array of the field exit_idx.
exit_order_id cached_property¶
Mapped array of the field exit_order_id.
exit_price cached_property¶
Mapped array of the field exit_price.
expanding_best_price cacheable_property¶
Trades.get_expanding_best_price with default arguments.
expanding_mae cacheable_property¶
Trades.get_expanding_mae with default arguments.
expanding_mae_returns cacheable_property¶
Trades.get_expanding_mae with arguments {'use_returns': True}.
expanding_mfe cacheable_property¶
Trades.get_expanding_mfe with default arguments.
expanding_mfe_returns cacheable_property¶
Trades.get_expanding_mfe with arguments {'use_returns': True}.
expanding_worst_price cacheable_property¶
Trades.get_expanding_worst_price with default arguments.
expectancy cached_property¶
Trades.get_expectancy with arguments {'use_returns': False}.
field_config property¶
Field config of Trades.
HybridConfig(
dtype=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')
]),
settings=dict(
id=dict(
name='id',
title='Trade Id',
mapping='ids'
),
col=dict(
name='col',
title='Column',
mapping='columns',
as_customdata=False
),
idx=dict(
name='exit_idx',
title='Index',
mapping='index'
),
start_idx=dict(
title='Start Index',
mapping='index',
name='entry_idx'
),
end_idx=dict(
title='End Index',
mapping='index',
name='exit_idx'
),
status=dict(
title='Status',
mapping=TradeStatusT(
Open=0,
Closed=1
)
),
size=dict(
title='Size'
),
entry_order_id=dict(
title='Entry Order Id',
mapping='ids'
),
entry_idx=dict(
title='Entry Index',
mapping='index'
),
entry_price=dict(
title='Avg Entry Price'
),
entry_fees=dict(
title='Entry Fees'
),
exit_order_id=dict(
title='Exit Order Id',
mapping='ids'
),
exit_idx=dict(
title='Exit Index',
mapping='index'
),
exit_price=dict(
title='Avg Exit Price'
),
exit_fees=dict(
title='Exit Fees'
),
pnl=dict(
title='PnL'
),
return=dict(
title='Return',
hovertemplate='$title: %{customdata[$index]:,%}'
),
direction=dict(
title='Direction',
mapping=TradeDirectionT(
Long=0,
Short=1
)
),
parent_id=dict(
title='Position Id',
mapping='ids'
)
)
)
Returns Trades._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change fields, you can either change the config in-place, override this property, or overwrite the instance variable Trades._field_config.
get_best_price method¶
Trades.get_best_price(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
**kwargs
)
Get best price.
See best_price_nb.
get_best_price_idx method¶
Trades.get_best_price_idx(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
relative=True,
**kwargs
)
Get (relative) index of best price.
See best_price_idx_nb.
get_edge_ratio method¶
Trades.get_edge_ratio(
volatility=None,
entry_price_open=False,
exit_price_close=False,
max_duration=None,
group_by=None,
jitted=None,
chunked=None,
wrap_kwargs=None
)
Get edge ratio.
See edge_ratio_nb.
If volatility is None, calculates the 14-period ATR if both high and low are provided, otherwise the 14-period rolling standard deviation.
get_expanding_best_price method¶
Trades.get_expanding_best_price(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
jitted=None,
clean_index_kwargs=None,
wrap_kwargs=None
)
Get expanding best price.
get_expanding_mae method¶
Trades.get_expanding_mae(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
use_returns=False,
jitted=None,
chunked=None,
**kwargs
)
Get expanding MAE.
See expanding_mae_nb.
get_expanding_mfe method¶
Trades.get_expanding_mfe(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
use_returns=False,
jitted=None,
chunked=None,
**kwargs
)
Get expanding MFE.
See expanding_mfe_nb.
get_expanding_worst_price method¶
Trades.get_expanding_worst_price(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
jitted=None,
clean_index_kwargs=None,
wrap_kwargs=None
)
Get expanding worst price.
get_expectancy method¶
Trades.get_expectancy(
use_returns=False,
group_by=None,
jitted=None,
chunked=None,
wrap_kwargs=None,
**kwargs
)
Get average profitability.
get_long_view method¶
Get long view.
get_losing method¶
Get losing trades.
get_losing_streak method¶
Get losing streak at each trade in the current column.
get_mae method¶
Trades.get_mae(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
use_returns=False,
jitted=None,
chunked=None,
**kwargs
)
Get MAE.
See mae_nb.
get_mfe method¶
Trades.get_mfe(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
use_returns=False,
jitted=None,
chunked=None,
**kwargs
)
Get MFE.
See mfe_nb.
get_profit_factor method¶
Trades.get_profit_factor(
use_returns=False,
group_by=None,
jitted=None,
chunked=None,
wrap_kwargs=None,
**kwargs
)
Get profit factor.
get_ranges method¶
Get records of type Ranges.
get_running_edge_ratio method¶
Trades.get_running_edge_ratio(
volatility=None,
entry_price_open=False,
exit_price_close=False,
max_duration=None,
incl_shorter=False,
group_by=None,
jitted=None,
wrap_kwargs=None
)
Get running edge ratio.
If volatility is None, calculates the 14-period ATR if both high and low are provided, otherwise the 14-period rolling standard deviation.
get_short_view method¶
Get short view.
get_sqn method¶
Trades.get_sqn(
ddof=1,
use_returns=False,
group_by=None,
jitted=None,
chunked=None,
wrap_kwargs=None,
**kwargs
)
Get System Quality Number (SQN).
get_win_rate method¶
Get rate of winning trades.
get_winning method¶
Get winning trades.
get_winning_streak method¶
Get winning streak at each trade in the current column.
get_worst_price method¶
Trades.get_worst_price(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
**kwargs
)
Get worst price.
See worst_price_nb.
get_worst_price_idx method¶
Trades.get_worst_price_idx(
entry_price_open=False,
exit_price_close=False,
max_duration=None,
relative=True,
**kwargs
)
Get (relative) index of worst price.
See worst_price_idx_nb.
long_view cached_property¶
Trades.get_long_view with default arguments.
losing cached_property¶
Trades.get_losing with default arguments.
losing_streak cacheable_property¶
Trades.get_losing_streak with default arguments.
mae cacheable_property¶
Trades.get_mae with default arguments.
mae_returns cacheable_property¶
Trades.get_mae with arguments {'use_returns': True}.
metrics property¶
Metrics supported by Trades.
HybridConfig(
start_index=dict(
title='Start Index',
calc_func=<function Trades.<lambda> at 0x1726a9760>,
agg_func=None,
tags='wrapper'
),
end_index=dict(
title='End Index',
calc_func=<function Trades.<lambda> at 0x1726a9800>,
agg_func=None,
tags='wrapper'
),
total_duration=dict(
title='Total Duration',
calc_func=<function Trades.<lambda> at 0x1726a98a0>,
apply_to_timedelta=True,
agg_func=None,
tags='wrapper'
),
first_trade_start=dict(
title='First Trade Start',
calc_func='entry_idx.nth',
n=0,
wrap_kwargs=dict(
to_index=True
),
tags=[
'trades',
'index'
]
),
last_trade_end=dict(
title='Last Trade End',
calc_func='exit_idx.nth',
n=-1,
wrap_kwargs=dict(
to_index=True
),
tags=[
'trades',
'index'
]
),
coverage=dict(
title='Coverage',
calc_func='coverage',
overlapping=False,
normalize=False,
apply_to_timedelta=True,
tags=[
'ranges',
'coverage'
]
),
overlap_coverage=dict(
title='Overlap Coverage',
calc_func='coverage',
overlapping=True,
normalize=False,
apply_to_timedelta=True,
tags=[
'ranges',
'coverage'
]
),
total_records=dict(
title='Total Records',
calc_func='count',
tags='records'
),
total_long_trades=dict(
title='Total Long Trades',
calc_func='direction_long.count',
tags=[
'trades',
'long'
]
),
total_short_trades=dict(
title='Total Short Trades',
calc_func='direction_short.count',
tags=[
'trades',
'short'
]
),
total_closed_trades=dict(
title='Total Closed Trades',
calc_func='status_closed.count',
tags=[
'trades',
'closed'
]
),
total_open_trades=dict(
title='Total Open Trades',
calc_func='status_open.count',
tags=[
'trades',
'open'
]
),
open_trade_pnl=dict(
title='Open Trade PnL',
calc_func='status_open.pnl.sum',
tags=[
'trades',
'open'
]
),
win_rate=dict(
title='Win Rate [%]',
calc_func='status_closed.get_win_rate',
post_calc_func=<function Trades.<lambda> at 0x1726a9940>,
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
winning_streak=dict(
title='Max Win Streak',
calc_func=RepEval(
template="'winning_streak.max' if incl_open else 'status_closed.winning_streak.max'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
wrap_kwargs=dict(
dtype=Int64Dtype()
),
tags=RepEval(
template="['trades', *incl_open_tags, 'streak']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
losing_streak=dict(
title='Max Loss Streak',
calc_func=RepEval(
template="'losing_streak.max' if incl_open else 'status_closed.losing_streak.max'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
wrap_kwargs=dict(
dtype=Int64Dtype()
),
tags=RepEval(
template="['trades', *incl_open_tags, 'streak']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
best_trade=dict(
title='Best Trade [%]',
calc_func=RepEval(
template="'returns.max' if incl_open else 'status_closed.returns.max'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
post_calc_func=<function Trades.<lambda> at 0x1726a99e0>,
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
worst_trade=dict(
title='Worst Trade [%]',
calc_func=RepEval(
template="'returns.min' if incl_open else 'status_closed.returns.min'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
post_calc_func=<function Trades.<lambda> at 0x1726a9a80>,
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
avg_winning_trade=dict(
title='Avg Winning Trade [%]',
calc_func=RepEval(
template="'winning.returns.mean' if incl_open else 'status_closed.winning.returns.mean'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
post_calc_func=<function Trades.<lambda> at 0x1726a9b20>,
tags=RepEval(
template="['trades', *incl_open_tags, 'winning']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
avg_losing_trade=dict(
title='Avg Losing Trade [%]',
calc_func=RepEval(
template="'losing.returns.mean' if incl_open else 'status_closed.losing.returns.mean'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
post_calc_func=<function Trades.<lambda> at 0x1726a9bc0>,
tags=RepEval(
template="['trades', *incl_open_tags, 'losing']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
avg_winning_trade_duration=dict(
title='Avg Winning Trade Duration',
calc_func=RepEval(
template="'winning.avg_duration' if incl_open else 'status_closed.winning.get_avg_duration'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
fill_wrap_kwargs=True,
tags=RepEval(
template="['trades', *incl_open_tags, 'winning', 'duration']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
avg_losing_trade_duration=dict(
title='Avg Losing Trade Duration',
calc_func=RepEval(
template="'losing.avg_duration' if incl_open else 'status_closed.losing.get_avg_duration'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
fill_wrap_kwargs=True,
tags=RepEval(
template="['trades', *incl_open_tags, 'losing', 'duration']",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
profit_factor=dict(
title='Profit Factor',
calc_func=RepEval(
template="'profit_factor' if incl_open else 'status_closed.get_profit_factor'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
expectancy=dict(
title='Expectancy',
calc_func=RepEval(
template="'expectancy' if incl_open else 'status_closed.get_expectancy'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
sqn=dict(
title='SQN',
calc_func=RepEval(
template="'sqn' if incl_open else 'status_closed.get_sqn'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
),
edge_ratio=dict(
title='Edge Ratio',
calc_func=RepEval(
template="'edge_ratio' if incl_open else 'status_closed.get_edge_ratio'",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
),
tags=RepEval(
template="['trades', *incl_open_tags]",
context=None,
strict=None,
context_merge_kwargs=None,
eval_id=None
)
)
)
Returns Trades._metrics, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change metrics, you can either change the config in-place, override this property, or overwrite the instance variable Trades._metrics.
mfe cacheable_property¶
Trades.get_mfe with default arguments.
mfe_returns cacheable_property¶
Trades.get_mfe with arguments {'use_returns': True}.
parent_id cached_property¶
Mapped array of the field parent_id.
plot method¶
Trades.plot(
column=None,
plot_ohlc=True,
plot_close=True,
plot_markers=True,
plot_zones=True,
plot_by_type=True,
ohlc_type=None,
ohlc_trace_kwargs=None,
close_trace_kwargs=None,
entry_trace_kwargs=None,
exit_trace_kwargs=None,
exit_profit_trace_kwargs=None,
exit_loss_trace_kwargs=None,
active_trace_kwargs=None,
profit_shape_kwargs=None,
loss_shape_kwargs=None,
add_trace_kwargs=None,
xref='x',
yref='y',
fig=None,
**layout_kwargs
)
Plot trades.
Args
column:str- Name of the column to plot.
plot_ohlc:bool- Whether to plot OHLC.
plot_close:bool- Whether to plot close.
plot_markers:bool- Whether to plot markers.
plot_zones:bool- Whether to plot zones.
plot_by_type:bool-
Whether to plot exit trades by type.
Otherwise, the appearance will be controlled using
exit_trace_kwargs. ohlc_type-
Either 'OHLC', 'Candlestick' or Plotly trace.
Pass None to use the default.
ohlc_trace_kwargs:dict- Keyword arguments passed to
ohlc_type. close_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor Trades.close. entry_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Entry" markers. exit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Exit" markers. exit_profit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Exit - Profit" markers. exit_loss_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Exit - Loss" markers. active_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Active" markers. profit_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor profit zones. loss_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor loss zones. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
>>> index = pd.date_range("2020", periods=7)
>>> price = pd.Series([1., 2., 3., 4., 3., 2., 1.], index=index)
>>> size = pd.Series([1., -0.5, -0.5, 2., -0.5, -0.5, -0.5], index=index)
>>> pf = vbt.Portfolio.from_orders(price, size)
>>> pf.trades.plot().show()
plot_against_pnl method¶
Trades.plot_against_pnl(
field,
field_label=None,
column=None,
group_by=False,
pct_scale=False,
field_pct_scale=False,
closed_trace_kwargs=None,
closed_profit_trace_kwargs=None,
closed_loss_trace_kwargs=None,
open_trace_kwargs=None,
hline_shape_kwargs=None,
vline_shape_kwargs=None,
add_trace_kwargs=None,
xref='x',
yref='y',
fig=None,
**layout_kwargs
)
Plot a field against PnL or returns.
Args
field:str,MappedArray,or array_like-
Field to be plotted.
Can be also provided as a mapped array or 1-dim array.
field_label:str- Label of the field.
column:str- Name of the column to plot.
group_by:any- Group columns. See Grouper.
pct_scale:bool- Whether to set x-axis to Trades.returns, otherwise to Trades.pnl.
field_pct_scale:bool- Whether to make y-axis a percentage scale.
closed_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed" markers. closed_profit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed - Profit" markers. closed_loss_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed - Loss" markers. open_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Open" markers. hline_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor horizontal zeroline. vline_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor vertical zeroline. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
>>> index = pd.date_range("2020", periods=10)
>>> price = pd.Series([1., 2., 3., 4., 5., 6., 5., 3., 2., 1.], index=index)
>>> orders = pd.Series([1., -0.5, 0., -0.5, 2., 0., -0.5, -0.5, 0., -0.5], index=index)
>>> pf = vbt.Portfolio.from_orders(price, orders)
>>> trades = pf.trades
>>> trades.plot_against_pnl("MFE").show()
plot_expanding method¶
Trades.plot_expanding(
field,
field_label=None,
column=None,
group_by=False,
plot_bands=False,
colorize='last',
field_pct_scale=False,
add_trace_kwargs=None,
fig=None,
**kwargs
)
Plot projections of an expanding field.
Args
field:strorarray_like-
Field to be plotted.
Can be also provided as a 2-dim array.
field_label:str- Label of the field.
column:str- Name of the column to plot. Optional.
group_by:any- Group columns. See Grouper.
plot_bands:bool- See GenericDFAccessor.plot_projections.
colorize:bool,strorcallable- See GenericDFAccessor.plot_projections.
field_pct_scale:bool- Whether to make y-axis a percentage scale.
add_trace_kwargs:dict- Keyword arguments passed to
add_trace. fig:FigureorFigureWidget- Figure to add traces to.
**kwargs- Keyword arguments passed to GenericDFAccessor.plot_projections.
Usage
>>> index = pd.date_range("2020", periods=10)
>>> price = pd.Series([1., 2., 3., 2., 4., 5., 6., 5., 6., 7.], index=index)
>>> orders = pd.Series([1., 0., 0., -2., 0., 0., 2., 0., 0., -1.], index=index)
>>> pf = vbt.Portfolio.from_orders(price, orders)
>>> pf.trades.plot_expanding("MFE").show()
plot_expanding_mae method¶
Trades.plot_expanding for Trades.expanding_mae.
plot_expanding_mae_returns method¶
Trades.plot_expanding for Trades.expanding_mae_returns.
plot_expanding_mfe method¶
Trades.plot_expanding for Trades.expanding_mfe.
plot_expanding_mfe_returns method¶
Trades.plot_expanding for Trades.expanding_mfe_returns.
plot_mae method¶
Trades.plot_against_pnl for Trades.mae.
plot_mae_returns method¶
Trades.plot_against_pnl for Trades.mae_returns.
plot_mfe method¶
Trades.plot_against_pnl for Trades.mfe.
plot_mfe_returns method¶
Trades.plot_against_pnl for Trades.mfe_returns.
plot_pnl method¶
Trades.plot_pnl(
column=None,
group_by=False,
pct_scale=False,
marker_size_range=(7, 14),
opacity_range=(0.75, 0.9),
closed_trace_kwargs=None,
closed_profit_trace_kwargs=None,
closed_loss_trace_kwargs=None,
open_trace_kwargs=None,
hline_shape_kwargs=None,
add_trace_kwargs=None,
xref='x',
yref='y',
fig=None,
**layout_kwargs
)
Plot trade PnL or returns.
Args
column:str- Name of the column to plot.
group_by:any- Group columns. See Grouper.
pct_scale:bool- Whether to set y-axis to Trades.returns, otherwise to Trades.pnl.
marker_size_range:tuple- Range of marker size.
opacity_range:tuple- Range of marker opacity.
closed_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed" markers. closed_profit_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed - Profit" markers. closed_loss_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Closed - Loss" markers. open_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor "Open" markers. hline_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor zeroline. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
>>> index = pd.date_range("2020", periods=7)
>>> price = pd.Series([1., 2., 3., 4., 3., 2., 1.], index=index)
>>> orders = pd.Series([1., -0.5, -0.5, 2., -0.5, -0.5, -0.5], index=index)
>>> pf = vbt.Portfolio.from_orders(price, orders)
>>> pf.trades.plot_pnl().show()
plot_returns method¶
Trades.plot_pnl for Trades.returns.
plot_running_edge_ratio method¶
Trades.plot_running_edge_ratio(
column=None,
volatility=None,
entry_price_open=False,
exit_price_close=False,
max_duration=None,
incl_shorter=False,
group_by=None,
jitted=None,
xref='x',
yref='y',
hline_shape_kwargs=None,
**kwargs
)
Plot one column/group of edge ratio.
**kwargs are passed to GenericAccessor.plot_against.
plots_defaults class property¶
Defaults for PlotsBuilderMixin.plots.
Merges Ranges.plots_defaults and plots from trades.
pnl cached_property¶
Mapped array of the field pnl.
profit_factor cached_property¶
Trades.get_profit_factor with arguments {'use_returns': False}.
ranges cached_property¶
Trades.get_ranges with default arguments.
rel_expectancy cached_property¶
Trades.get_expectancy with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_expectancy'}}.
rel_profit_factor cached_property¶
Trades.get_profit_factor with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_profit_factor'}}.
rel_sqn cached_property¶
Trades.get_sqn with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_sqn'}}.
returns cached_property¶
Mapped array of the field return.
running_edge_ratio cacheable_property¶
Trades.get_running_edge_ratio with default arguments.
short_view cached_property¶
Trades.get_short_view with default arguments.
size cached_property¶
Mapped array of the field size.
sqn cached_property¶
Trades.get_sqn with arguments {'use_returns': False}.
stats_defaults class property¶
Defaults for StatsBuilderMixin.stats.
Merges Ranges.stats_defaults and stats from trades.
subplots property¶
Subplots supported by Trades.
HybridConfig(
plot=dict(
title='Trades',
yaxis_kwargs=dict(
title='Price'
),
check_is_not_grouped=True,
plot_func='plot',
tags='trades'
),
plot_pnl=dict(
title='Trade PnL',
yaxis_kwargs=dict(
title='Trade PnL'
),
check_is_not_grouped=True,
plot_func='plot_pnl',
tags='trades'
)
)
Returns Trades._subplots, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change subplots, you can either change the config in-place, override this property, or overwrite the instance variable Trades._subplots.
win_rate cached_property¶
Trades.get_win_rate with default arguments.
winning cached_property¶
Trades.get_winning with default arguments.
winning_streak cacheable_property¶
Trades.get_winning_streak with default arguments.
worst_price cacheable_property¶
Trades.get_worst_price with default arguments.
worst_price_idx cacheable_property¶
Trades.get_worst_price_idx with default arguments.