Skip to content
New: Star-import, signal unraveling, Python 3.12 support, and more

#
nb module

Numba-compiled functions for signals.

Provides an arsenal of Numba-compiled functions that are used by accessors and in many other parts of the backtesting pipeline, such as technical indicators. These only accept NumPy arrays and other Numba-compatible types.

Note

vectorbt treats matrices as first-class citizens and expects input arrays to be 2-dim, unless function has suffix `_1d` or is meant to be input to another function. Data is processed along index (axis 0).

All functions passed as argument must be Numba-compiled.

## between_partition_ranges_nb function

    between_partition_ranges_nb(
        mask
    )

Create a record of type range_dt for each range between two partitions in `mask`.

## between_ranges_nb function

    between_ranges_nb(
        mask,
        incl_open=False
    )

Create a record of type range_dt for each range between two signals in `mask`.

## between_two_ranges_nb function

    between_two_ranges_nb(
        source_mask,
        target_mask,
        relation=1,
        incl_open=False
    )

Create a record of type range_dt for each range between a source and target mask.

Index pairs are resolved with relation_idxs_1d_nb().

## clean_enex_1d_nb function

    clean_enex_1d_nb(
        entries,
        exits,
        force_first=True,
        keep_conflicts=False,
        reverse_order=False
    )

Clean entry and exit arrays by picking the first signal out of each.

Set `force_first` to True to force placing the first entry/exit before the first exit/entry. Set `keep_conflicts` to True to process signals at the same timestamp sequentially instead of removing them. Set `reverse_order` to True to reverse the order of signals.

## clean_enex_nb function

    clean_enex_nb(
        entries,
        exits,
        force_first=True,
        keep_conflicts=False,
        reverse_order=False
    )

2-dim version of clean_enex_1d_nb().

## distance_from_last_1d_nb function

    distance_from_last_1d_nb(
        mask,
        nth=1
    )

Distance from the last n-th True value to the current value.

Unless `nth` is zero, the current True value isn't counted as one of the last True values.

## distance_from_last_nb function

    distance_from_last_nb(
        mask,
        nth=1
    )

2-dim version of distance_from_last_1d_nb().

## first_place_nb function

    first_place_nb(
        c,
        mask
    )

`place_func_nb` that keeps only the first signal in `mask`.

## generate_enex_nb function

    generate_enex_nb(
        target_shape,
        entry_place_func_nb,
        entry_place_args,
        exit_place_func_nb,
        exit_place_args,
        entry_wait=1,
        exit_wait=1
    )

Place entry signals using `entry_place_func_nb` and exit signals using `exit_place_func_nb` one after another.

Args

`target_shape` :`array`
  Target shape.
`entry_place_func_nb` :`callable`

  Entry place function.

  `entry_place_func_nb` must accept a context of type GenEnExContext, and return the index of the last signal (-1 to break the loop).

`entry_place_args` :`tuple`
  Arguments unpacked and passed to `entry_place_func_nb`.
`exit_place_func_nb` :`callable`

  Exit place function.

  `exit_place_func_nb` must accept a context of type GenEnExContext, and return the index of the last signal (-1 to break the loop).

`exit_place_args` :`tuple`
  Arguments unpacked and passed to `exit_place_func_nb`.
`entry_wait` :`int`

  Number of ticks to wait before placing entries.

  Note

  Setting `entry_wait` to 0 or False assumes that both entry and exit can be processed within the same bar, and exit can be processed before entry.

`exit_wait` :`int`

  Number of ticks to wait before placing exits.

  Note

  Setting `exit_wait` to 0 or False assumes that both entry and exit can be processed within the same bar, and entry can be processed before exit.

## generate_ex_nb function

    generate_ex_nb(
        entries,
        exit_place_func_nb,
        exit_place_args=(),
        wait=1,
        until_next=True,
        skip_until_exit=False
    )

Place exit signals using `exit_place_func_nb` after each signal in `entries`.

Args

`entries` :`array`
  Boolean array with entry signals.
`exit_place_func_nb` :`callable`

  Exit place function.

  `exit_place_func_nb` must accept a context of type GenExContext, and return the index of the last signal (-1 to break the loop).

`exit_place_args` :`callable`
  Arguments passed to `exit_place_func_nb`.
`wait` :`int`

  Number of ticks to wait before placing exits.

  Note

  Setting `wait` to 0 or False may result in two signals at one bar.

`until_next` :`int`

  Whether to place signals up to the next entry signal.

  Note

  Setting it to False makes it difficult to tell which exit belongs to which entry.

`skip_until_exit` :`bool`

  Whether to skip processing entry signals until the next exit.

  Has only effect when `until_next` is disabled.

  Note

  Setting it to True makes it impossible to tell which exit belongs to which entry.

## generate_nb function

    generate_nb(
        target_shape,
        place_func_nb,
        place_args=(),
        only_once=True,
        wait=1
    )

Create a boolean matrix of `target_shape` and place signals using `place_func_nb`.

Args

`target_shape` :`array`
  Target shape.
`place_func_nb` :`callable`

  Signal placement function.

  `place_func_nb` must accept a context of type GenEnContext, and return the index of the last signal (-1 to break the loop).

`place_args`
  Arguments passed to `place_func_nb`.
`only_once` :`bool`
  Whether to run the placement function only once.
`wait` :`int`
  Number of ticks to wait before placing the next entry.

Note

The first argument is always a 1-dimensional boolean array that contains only those elements where signals can be placed. The range and column indices only describe which range this array maps to.

## generate_rand_enex_nb function

    generate_rand_enex_nb(
        target_shape,
        n,
        entry_wait=1,
        exit_wait=1
    )

Pick a number of entries and the same number of exits one after another.

Respects `entry_wait` and `exit_wait` constraints through a number of tricks. Tries to mimic a uniform distribution as much as possible.

The idea is the following: with constraints, there is some fixed amount of total space required between first entry and last exit. Upscale this space in a way that distribution of entries and exit is similar to a uniform distribution. This means randomizing the position of first entry, last exit, and all signals between them.

`n` uses flexible indexing and thus must be at least a 0-dim array.

## norm_avg_index_1d_nb function

    norm_avg_index_1d_nb(
        mask
    )

Get mean index normalized to (-1, 1).

## norm_avg_index_grouped_nb function

    norm_avg_index_grouped_nb(
        mask,
        group_lens
    )

Grouped version of norm_avg_index_nb().

## norm_avg_index_nb function

    norm_avg_index_nb(
        mask
    )

2-dim version of norm_avg_index_1d_nb().

## nth_index_1d_nb function

    nth_index_1d_nb(
        mask,
        n
    )

Get the index of the n-th True value.

Note

`n` starts with 0 and can be negative.

## nth_index_nb function

    nth_index_nb(
        mask,
        n
    )

2-dim version of nth_index_1d_nb().

## ohlc_stop_place_nb function

    ohlc_stop_place_nb(
        c,
        entry_price,
        open,
        high,
        low,
        close,
        stop_price_out,
        stop_type_out,
        sl_stop,
        tsl_th,
        tsl_stop,
        tp_stop,
        reverse,
        is_entry_open=False
    )

`place_func_nb` that places an exit signal whenever a threshold is being hit using OHLC.

Compared to stop_place_nb(), takes into account the whole bar, can check for both (trailing) stop loss and take profit simultaneously, and tracks hit price and stop type.

Note

Waiting time cannot be higher than 1.

Args

`c` :`GenExContext` or `GenEnExContext`
  Signal context.
`entry_price` :`array` of `float`

  Entry price.

  Utilizes flexible indexing.

`open` :`array` of `float`

  Open price.

  Utilizes flexible indexing. If Nan and `is_entry_open` is True, defaults to entry price.

`high` :`array` of `float`

  High price.

  Utilizes flexible indexing. If NaN, gets calculated from open and close.

`low` :`array` of `float`

  Low price.

  Utilizes flexible indexing. If NaN, gets calculated from open and close.

`close` :`array` of `float`

  Close price.

  Utilizes flexible indexing. If Nan and `is_entry_open` is False, defaults to entry price.

`stop_price_out` :`array` of `float`

  Array where hit price of each exit will be stored.

  Must be of the full shape.

`stop_type_out` :`array` of `int`

  Array where stop type of each exit will be stored.

  Must be of the full shape. 0 for stop loss, 1 for take profit.

`sl_stop` :`array` of `float`

  Stop loss as a percentage.

  Utilizes flexible indexing. Set an element to `np.nan` to disable.

`tsl_th` :`array` of `float`

  Take profit threshold as a percentage for the trailing stop loss.

  Utilizes flexible indexing. Set an element to `np.nan` to disable.

`tsl_stop` :`array` of `float`

  Trailing stop loss as a percentage for the trailing stop loss.

  Utilizes flexible indexing. Set an element to `np.nan` to disable.

`tp_stop` :`array` of `float`

  Take profit as a percentage.

  Utilizes flexible indexing. Set an element to `np.nan` to disable.

`reverse` :`array` of `float`

  Whether to do the opposite, i.e.: prices are followed downwards.

  Utilizes flexible indexing.

`is_entry_open` :`bool`

  Whether entry price comes right at or before open.

  If True, uses high and low of the entry bar. Otherwise, uses only close.

## part_pos_rank_nb function

    part_pos_rank_nb(
        c
    )

`rank_func_nb` that returns the rank of each partition by its position in the series.

Resets at each reset signal.

## partition_ranges_nb function

    partition_ranges_nb(
        mask
    )

Create a record of type range_dt for each partition of signals in `mask`.

## rand_by_prob_place_nb function

    rand_by_prob_place_nb(
        c,
        prob,
        pick_first=False
    )

`place_func_nb` to randomly place signals with probability `prob`.

`prob` uses flexible indexing.

## rand_enex_apply_nb function

    rand_enex_apply_nb(
        target_shape,
        n,
        entry_wait=1,
        exit_wait=1
    )

`apply_func_nb` that calls generate_rand_enex_nb().

## rand_place_nb function

    rand_place_nb(
        c,
        n
    )

`place_func_nb` to randomly pick `n` values.

`n` uses flexible indexing.

## rank_nb function

    rank_nb(
        mask,
        rank_func_nb,
        rank_args=(),
        reset_by=None,
        after_false=False,
        after_reset=False,
        reset_wait=1
    )

Rank each signal using `rank_func_nb`.

Applies `rank_func_nb` on each True value. Must accept a context of type RankContext. Must return -1 for no rank, otherwise 0 or greater.

Setting `after_false` to True will disregard the first partition of True values if there is no False value before them. Setting `after_reset` to True will disregard the first partition of True values coming before the first reset signal. Setting `reset_wait` to 0 will treat the signal at the same position as the reset signal as the first signal in the next partition. Setting it to 1 will treat it as the last signal in the previous partition.

## ravel_nb function

    ravel_nb(
        mask,
        group_map
    )

Ravel True values of each group into a separate column.

## relation_idxs_1d_nb function

    relation_idxs_1d_nb(
        source_mask,
        target_mask,
        relation=1
    )

Get index pairs of True values between a source and target mask.

For `relation`, see SignalRelation.

Note

If both True values happen at the same time, source signal is assumed to come first.

## sig_pos_rank_nb function

    sig_pos_rank_nb(
        c,
        allow_gaps
    )

`rank_func_nb` that returns the rank of each signal by its position in the partition if `allow_gaps` is False, otherwise globally.

Resets at each reset signal.

## stop_place_nb function

    stop_place_nb(
        c,
        entry_ts,
        ts,
        follow_ts,
        stop_ts_out,
        stop,
        trailing
    )

`place_func_nb` that places an exit signal whenever a threshold is being hit.

Note

Waiting time cannot be higher than 1.

If waiting time is 0, `entry_ts` should be the first value in the bar. If waiting time is 1, `entry_ts` should be the last value in the bar.

Args

`c` :`GenExContext` or `GenEnExContext`
  Signal context.
`entry_ts` :`array` of `float`

  Entry price.

  Utilizes flexible indexing.

`ts` :`array` of `float`

  Price to compare the stop value against.

  Utilizes flexible indexing. If NaN, defaults to `entry_ts`.

`follow_ts` :`array` of `float`

  Following price.

  Utilizes flexible indexing. If NaN, defaults to `ts`. Applied only if the stop is trailing.

`stop_ts_out` :`array` of `float`

  Array where hit price of each exit will be stored.

  Must be of the full shape.

`stop` :`array` of `float`

  Stop value.

  Utilizes flexible indexing. Set an element to `np.nan` to disable it.

`trailing` :`array` of `bool`

  Whether the stop is trailing.

  Utilizes flexible indexing. Set an element to False to disable it.

## unravel_between_nb function

    unravel_between_nb(
        mask,
        incl_open_source=False,
        incl_empty_cols=True
    )

Unravel each pair of successive True values in a mask to a separate column.

Returns the new mask, the index of each source True value in its column, the index of each target True value in its column, the row index of each source True value in the original mask, the row index of each target True value in the original mask, and the column index of each True value in the original mask.

## unravel_between_two_nb function

    unravel_between_two_nb(
        source_mask,
        target_mask,
        relation=1,
        incl_open_source=False,
        incl_open_target=False,
        incl_empty_cols=True
    )

Unravel each pair of successive True values between a source and target mask to a separate column.

Index pairs are resolved with relation_idxs_1d_nb().

Returns the new source mask, the new target mask, the index of each source True value in its column, the index of each target True value in its column, the row index of each True value in each original mask, and the column index of each True value in both original masks.

## unravel_nb function

    unravel_nb(
        mask,
        incl_empty_cols=True
    )

Unravel each True value in a mask to a separate column.

Returns the new mask, the index of each True value in its column, the row index of each True value in its column, and the column index of each True value in the original mask.

#### Cookie consent

We use cookies to recognize your repeated visits and preferences, as well as to measure the effectiveness of our documentation and whether users find what they're searching for. With your consent, you're helping us to make our documentation better.

- Google Analytics
- GitHub

Manage settings