Skip to content

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

>>> 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()

100%

>>> 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

Trades class has two subplots based on Trades.plot() and Trades.plot_pnl():

>>> pf.trades['a'].plots().show()


entry_trades_field_config ReadonlyConfig

Field config for EntryTrades.

ReadonlyConfig(
    settings=dict(
        id=dict(
            title='Entry Trade Id'
        ),
        idx=dict(
            name='entry_idx'
        )
    )
)

exit_trades_field_config ReadonlyConfig

Field config for ExitTrades.

ReadonlyConfig(
    settings=dict(
        id=dict(
            title='Exit Trade Id'
        )
    )
)

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

EntryTrades(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends Trades for working with entry trade records.

Superclasses

Inherited members


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.Scatter for EntryTrades.close.
long_entry_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Long Entry" markers.
short_entry_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Short Entry" markers.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
fig : Figure or FigureWidget
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

ExitTrades(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends Trades for working with exit trade records.

Superclasses

Inherited members


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.Scatter for ExitTrades.close.
long_exit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Long Exit" markers.
short_exit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Short Exit" markers.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
fig : Figure or FigureWidget
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

Positions(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends Trades for working with position records.

Superclasses

Inherited members


from_trades class method

Positions.from_trades(
    trades,
    open=None,
    high=None,
    low=None,
    close=None,
    jitted=None,
    chunked=None,
    **kwargs
)

Build Positions from Trades.


Trades class

Trades(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends Ranges for working with trade-like records, such as entry trades, exit trades, and positions.

Superclasses

Inherited members

Subclasses


best_price property

Trades.get_best_price() with default arguments.


best_price_idx property

Trades.get_best_price_idx() with default arguments.


direction property

Mapped array of the field direction.


direction_long property

Records filtered by direction == 0.


direction_short property

Records filtered by direction == 1.


edge_ratio property

Trades.get_edge_ratio() with default arguments.


entry_fees property

Mapped array of the field entry_fees.


entry_idx property

Mapped array of the field entry_idx.


entry_order_id property

Mapped array of the field entry_order_id.


entry_price property

Mapped array of the field entry_price.


exit_fees property

Mapped array of the field exit_fees.


exit_idx property

Mapped array of the field exit_idx.


exit_order_id property

Mapped array of the field exit_order_id.


exit_price property

Mapped array of the field exit_price.


expanding_best_price property

Trades.get_expanding_best_price() with default arguments.


expanding_mae property

Trades.get_expanding_mae() with default arguments.


expanding_mae_returns property

Trades.get_expanding_mae() with arguments {'use_returns': True}.


expanding_mfe property

Trades.get_expanding_mfe() with default arguments.


expanding_mfe_returns property

Trades.get_expanding_mfe() with arguments {'use_returns': True}.


expanding_worst_price property

Trades.get_expanding_worst_price() with default arguments.


expectancy property

Trades.get_expectancy() with arguments {'use_returns': False}.


field_config class variable

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.

See expanding_best_price_nb().


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.

See expanding_worst_price_nb().


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

Trades.get_long_view(
    **kwargs
)

get_losing method

Trades.get_losing(
    **kwargs
)

Get losing trades.


get_losing_streak method

Trades.get_losing_streak(
    **kwargs
)

Get losing streak at each trade in the current column.

See trade_losing_streak_nb().


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

Trades.get_ranges(
    **kwargs
)

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.

See running_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_short_view method

Trades.get_short_view(
    **kwargs
)

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

Trades.get_win_rate(
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None,
    **kwargs
)

Get rate of winning trades.


get_winning method

Trades.get_winning(
    **kwargs
)

Get winning trades.


get_winning_streak method

Trades.get_winning_streak(
    **kwargs
)

Get winning streak at each trade in the current column.

See trade_winning_streak_nb().


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 property

Trades.get_long_view() with default arguments.


losing property

Trades.get_losing() with default arguments.


losing_streak property

Trades.get_losing_streak() with default arguments.


mae property

Trades.get_mae() with default arguments.


mae_returns property

Trades.get_mae() with arguments {'use_returns': True}.


metrics class variable

Metrics supported by Trades.

HybridConfig(
    start_index=dict(
        title='Start Index',
        calc_func=<function Trades.<lambda> at 0x16488a2a0>,
        agg_func=None,
        tags='wrapper'
    ),
    end_index=dict(
        title='End Index',
        calc_func=<function Trades.<lambda> at 0x16488a340>,
        agg_func=None,
        tags='wrapper'
    ),
    total_duration=dict(
        title='Total Duration',
        calc_func=<function Trades.<lambda> at 0x16488a3e0>,
        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 0x16488a480>,
        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 0x16488a520>,
        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 0x16488a5c0>,
        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 0x16488a660>,
        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 0x16488a700>,
        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 property

Trades.get_mfe() with default arguments.


mfe_returns property

Trades.get_mfe() with arguments {'use_returns': True}.


parent_id 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.Scatter for Trades.close.
entry_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Entry" markers.
exit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Exit" markers.
exit_profit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Exit - Profit" markers.
exit_loss_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Exit - Loss" markers.
active_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Active" markers.
profit_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for profit zones.
loss_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for loss zones.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
xref : str
X coordinate axis.
yref : str
Y coordinate axis.
fig : Figure or FigureWidget
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.Scatter for "Closed" markers.
closed_profit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Closed - Profit" markers.
closed_loss_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Closed - Loss" markers.
open_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Open" markers.
hline_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for horizontal zeroline.
vline_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for vertical zeroline.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
xref : str
X coordinate axis.
yref : str
Y coordinate axis.
fig : Figure or FigureWidget
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 : str or array_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, str or callable
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 : Figure or FigureWidget
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

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='expanding_mae',
    field_label='MAE',
    column=None,
    group_by=False,
    plot_bands=False,
    colorize='last',
    field_pct_scale=False,
    add_trace_kwargs=None,
    fig=None,
    **kwargs
)

plot_expanding_mae_returns method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='expanding_mae_returns',
    field_label='MAE Return',
    column=None,
    group_by=False,
    plot_bands=False,
    colorize='last',
    field_pct_scale=True,
    add_trace_kwargs=None,
    fig=None,
    **kwargs
)

plot_expanding_mfe method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='expanding_mfe',
    field_label='MFE',
    column=None,
    group_by=False,
    plot_bands=False,
    colorize='last',
    field_pct_scale=False,
    add_trace_kwargs=None,
    fig=None,
    **kwargs
)

plot_expanding_mfe_returns method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='expanding_mfe_returns',
    field_label='MFE Return',
    column=None,
    group_by=False,
    plot_bands=False,
    colorize='last',
    field_pct_scale=True,
    add_trace_kwargs=None,
    fig=None,
    **kwargs
)

plot_mae method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='mae',
    field_label='MAE',
    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_mae_returns method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='mae_returns',
    field_label='MAE Return',
    column=None,
    group_by=False,
    pct_scale=True,
    field_pct_scale=True,
    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_mfe method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='mfe',
    field_label='MFE',
    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_mfe_returns method

partialmethod._make_unbound_method.<locals>._method(
    *,
    field='mfe_returns',
    field_label='MFE Return',
    column=None,
    group_by=False,
    pct_scale=True,
    field_pct_scale=True,
    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_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.Scatter for "Closed" markers.
closed_profit_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Closed - Profit" markers.
closed_loss_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Closed - Loss" markers.
open_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Open" markers.
hline_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for zeroline.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
xref : str
X coordinate axis.
yref : str
Y coordinate axis.
fig : Figure or FigureWidget
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

partialmethod._make_unbound_method.<locals>._method(
    column=None,
    group_by=False,
    *,
    pct_scale=True,
    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_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 property

Defaults for PlotsBuilderMixin.plots().

Merges Ranges.plots_defaults and plots from trades.


pnl property

Mapped array of the field pnl.


profit_factor property

Trades.get_profit_factor() with arguments {'use_returns': False}.


ranges property

Trades.get_ranges() with default arguments.


rel_expectancy property

Trades.get_expectancy() with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_expectancy'}}.


rel_profit_factor property

Trades.get_profit_factor() with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_profit_factor'}}.


rel_sqn property

Trades.get_sqn() with arguments {'use_returns': True, 'wrap_kwargs': {'name_or_index': 'rel_sqn'}}.


returns property

Mapped array of the field return.


running_edge_ratio property

Trades.get_running_edge_ratio() with default arguments.


short_view property

Trades.get_short_view() with default arguments.


size property

Mapped array of the field size.


sqn property

Trades.get_sqn() with arguments {'use_returns': False}.


stats_defaults property

Defaults for StatsBuilderMixin.stats().

Merges Ranges.stats_defaults and stats from trades.


subplots class variable

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 property

Trades.get_win_rate() with default arguments.


winning property

Trades.get_winning() with default arguments.


winning_streak property

Trades.get_winning_streak() with default arguments.


worst_price property

Trades.get_worst_price() with default arguments.


worst_price_idx property

Trades.get_worst_price_idx() with default arguments.