nb module¶
Numba-compiled functions.
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.
>>> import numpy as np
>>> import vectorbt as vbt
>>> # vectorbt.signals.nb.pos_rank_nb
>>> vbt.signals.nb.pos_rank_nb(np.array([False, True, True, True, False])[:, None])[:, 0]
[-1 0 1 2 -1]
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 should be Numba-compiled.
Returned indices should be absolute.
between_partition_ranges_nb function¶
between_partition_ranges_nb(
a
)
Create a record of type range_dt for each range between two partitions in a
.
between_ranges_nb function¶
between_ranges_nb(
a
)
Create a record of type range_dt for each range between two signals in a
.
between_two_ranges_nb function¶
between_two_ranges_nb(
a,
b,
from_other=False
)
Create a record of type range_dt for each range between two signals in a
and b
.
If from_other
is False, returns ranges from each in a
to the succeeding in b
. Otherwise, returns ranges from each in b
to the preceding in a
.
When a
and b
overlap (two signals at the same time), the distance between overlapping signals is still considered and from_i
would match to_i
.
clean_enex_1d_nb function¶
clean_enex_1d_nb(
entries,
exits,
entry_first
)
Clean entry and exit arrays by picking the first signal out of each.
Entry signal must be picked first. If both signals are present, selects none.
clean_enex_nb function¶
clean_enex_nb(
entries,
exits,
entry_first
)
2-dim version of clean_enex_1d_nb().
first_choice_nb function¶
first_choice_nb(
from_i,
to_i,
col,
a
)
choice_func_nb
that returns the index of the first signal in a
.
generate_enex_nb function¶
generate_enex_nb(
shape,
entry_wait,
exit_wait,
entry_pick_first,
exit_pick_first,
entry_choice_func_nb,
entry_args,
exit_choice_func_nb,
exit_args
)
Pick entry signals using entry_choice_func_nb
and exit signals using exit_choice_func_nb
one after another.
Args
shape
:array
- Target shape.
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. entry_pick_first
:bool
- Whether to pick the first entry out of all returned by
entry_choice_func_nb
. exit_pick_first
:bool
-
Whether to pick the first exit out of all returned by
exit_choice_func_nb
.Setting it to False acts similarly to setting
skip_until_exit
to True in generate_ex_nb(). entry_choice_func_nb
:callable
-
Entry choice function.
See
choice_func_nb
in generate_nb(). entry_args
:tuple
- Arguments unpacked and passed to
entry_choice_func_nb
. exit_choice_func_nb
:callable
-
Exit choice function.
See
choice_func_nb
in generate_nb(). exit_args
:tuple
- Arguments unpacked and passed to
exit_choice_func_nb
.
generate_ex_nb function¶
generate_ex_nb(
entries,
wait,
until_next,
skip_until_exit,
pick_first,
exit_choice_func_nb,
*args
)
Pick exit signals using exit_choice_func_nb
after each signal in entries
.
Args
entries
:array
- Boolean array with entry signals.
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 difficult to tell which exit belongs to which entry.
pick_first
:bool
- Whether to pick the first signal out of all returned by
exit_choice_func_nb
. exit_choice_func_nb
:callable
-
Exit choice function.
See
choice_func_nb
in generate_nb(). *args
:callable
- Arguments passed to
exit_choice_func_nb
.
generate_nb function¶
generate_nb(
shape,
pick_first,
choice_func_nb,
*args
)
Create a boolean matrix of shape
and pick signals using choice_func_nb
.
Args
shape
:array
- Target shape.
pick_first
:bool
- Whether to pick the first signal out of all returned by
choice_func_nb
. choice_func_nb
:callable
-
Choice function.
choice_func_nb
should accept index of the start of the rangefrom_i
, index of the end of the rangeto_i
, index of the columncol
, and*args
. It should return an array of indices from[from_i, to_i)
(can be empty). *args
- Arguments passed to
choice_func_nb
.
Usage
>>> from numba import njit
>>> import numpy as np
>>> from vectorbt.signals.nb import generate_nb
>>> @njit
... def choice_func_nb(from_i, to_i, col):
... return np.array([from_i + col])
>>> generate_nb((5, 3), choice_func_nb)
[[ True False False]
[False True False]
[False False True]
[False False False]
[False False False]]
generate_ohlc_stop_enex_nb function¶
generate_ohlc_stop_enex_nb(
entries,
open,
high,
low,
close,
stop_price_out,
stop_type_out,
sl_stop,
sl_trail,
tp_stop,
reverse,
is_open_safe,
entry_wait,
exit_wait,
pick_first,
flex_2d
)
Generate one after another using generate_enex_nb() and ohlc_stop_choice_nb().
Returns two arrays: new entries and exits.
Note
Has the same logic as calling generate_ohlc_stop_ex_nb() with skip_until_exit=True
, but removes all entries that come before the next exit.
generate_ohlc_stop_ex_nb function¶
generate_ohlc_stop_ex_nb(
entries,
open,
high,
low,
close,
stop_price_out,
stop_type_out,
sl_stop,
sl_trail,
tp_stop,
reverse,
is_open_safe,
wait,
until_next,
skip_until_exit,
pick_first,
flex_2d
)
Generate using generate_ex_nb() and ohlc_stop_choice_nb().
Usage
- Generate trailing stop loss and take profit signals for 10%. Illustrates how exit signal can be generated within the same bar as entry.
>>> import numpy as np
>>> from vectorbt.signals.nb import generate_ohlc_stop_ex_nb
>>> entries = np.asarray([True, False, True, False, False])[:, None]
>>> entry_price = np.asarray([10, 11, 12, 11, 10])[:, None]
>>> high_price = entry_price + 1
>>> low_price = entry_price - 1
>>> close_price = entry_price
>>> stop_price_out = np.full_like(entries, np.nan, dtype=np.float_)
>>> stop_type_out = np.full_like(entries, -1, dtype=np.int_)
>>> generate_ohlc_stop_ex_nb(
... entries=entries,
... open=entry_price,
... high=high_price,
... low=low_price,
... close=close_price,
... stop_price_out=stop_price_out,
... stop_type_out=stop_type_out,
... sl_stop=0.1,
... sl_trail=True,
... tp_stop=0.1,
... reverse=False,
... is_open_safe=True,
... wait=1,
... until_next=True,
... skip_until_exit=False,
... pick_first=True,
... flex_2d=True
... )
array([[ True],
[False],
[False],
[ True],
[False]])
>>> stop_price_out
array([[ 9. ], << trailing SL from 10 (entry_price)
[ nan],
[ nan],
[11.7], << trailing SL from 13 (high_price)
[ nan]])
>>> stop_type_out
array([[ 1],
[-1],
[-1],
[ 1],
[-1]])
Note that if is_open_safe
was False, the first exit would be executed at the second bar. This is because we don't know whether the entry price comes before the high and low price at the first bar, and so the trailing stop isn't triggered for the low price of 9.0.
generate_rand_by_prob_nb function¶
generate_rand_by_prob_nb(
shape,
prob,
pick_first,
flex_2d,
seed=None
)
Create a boolean matrix of shape
and pick signals randomly by probability prob
.
prob
should be a 2-dim array of shape shape
. Specify seed
to make output deterministic.
generate_rand_enex_by_prob_nb function¶
generate_rand_enex_by_prob_nb(
shape,
entry_prob,
exit_prob,
entry_wait,
exit_wait,
entry_pick_first,
exit_pick_first,
flex_2d,
seed=None
)
Pick entries by probability entry_prob
and exits by probability exit_prob
one after another.
entry_prob
and exit_prob
should be 2-dim arrays of shape shape
. Specify seed
to make output deterministic.
generate_rand_enex_nb function¶
generate_rand_enex_nb(
shape,
n,
entry_wait,
exit_wait,
seed=None
)
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. Specify seed
to make output deterministic.
generate_rand_ex_by_prob_nb function¶
generate_rand_ex_by_prob_nb(
entries,
prob,
wait,
until_next,
skip_until_exit,
flex_2d,
seed=None
)
Pick an exit after each entry in entries
by probability prob
.
prob
should be a 2-dim array of shape shape
. Specify seed
to make output deterministic.
generate_rand_ex_nb function¶
generate_rand_ex_nb(
entries,
wait,
until_next,
skip_until_exit,
seed=None
)
Pick an exit after each entry in entries
.
Specify seed
to make output deterministic.
generate_rand_nb function¶
generate_rand_nb(
shape,
n,
seed=None
)
Create a boolean matrix of shape
and pick a number of signals randomly.
Specify seed
to make output deterministic.
See rand_choice_nb().
generate_stop_enex_nb function¶
generate_stop_enex_nb(
entries,
ts,
stop,
trailing,
entry_wait,
exit_wait,
pick_first,
flex_2d
)
Generate one after another using generate_enex_nb() and stop_choice_nb().
Returns two arrays: new entries and exits.
Note
Has the same logic as calling generate_stop_ex_nb() with skip_until_exit=True
, but removes all entries that come before the next exit.
generate_stop_ex_nb function¶
generate_stop_ex_nb(
entries,
ts,
stop,
trailing,
wait,
until_next,
skip_until_exit,
pick_first,
flex_2d
)
Generate using generate_ex_nb() and stop_choice_nb().
Usage
- Generate trailing stop loss and take profit signals for 10%.
>>> import numpy as np
>>> from vectorbt.signals.nb import generate_stop_ex_nb
>>> entries = np.asarray([False, True, False, False, False])[:, None]
>>> ts = np.asarray([1, 2, 3, 2, 1])[:, None]
>>> generate_stop_ex_nb(entries, ts, -0.1, True, 1, True, True)
array([[False],
[False],
[False],
[ True],
[False]])
>>> generate_stop_ex_nb(entries, ts, 0.1, False, 1, True, True)
array([[False],
[False],
[ True],
[False],
[False]])
norm_avg_index_1d_nb function¶
norm_avg_index_1d_nb(
a
)
Get mean index normalized to (-1, 1).
norm_avg_index_nb function¶
norm_avg_index_nb(
a
)
2-dim version of norm_avg_index_1d_nb().
nth_index_1d_nb function¶
nth_index_1d_nb(
a,
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(
a,
n
)
2-dim version of nth_index_1d_nb().
ohlc_stop_choice_nb function¶
ohlc_stop_choice_nb(
from_i,
to_i,
col,
open,
high,
low,
close,
stop_price_out,
stop_type_out,
sl_stop,
sl_trail,
tp_stop,
reverse,
is_open_safe,
wait,
pick_first,
temp_idx_arr,
flex_2d
)
choice_func_nb
that returns the indices of the stop price being hit within OHLC.
Compared to stop_choice_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
We don't have intra-candle data. If there was a huge price fluctuation in both directions, we can't determine whether SL was triggered before TP and vice versa. So some assumptions need to be made: 1) trailing stop can only be based on previous close/high, and 2) we pessimistically assume that SL comes before TP.
Args
col
:int
- Current column.
from_i
:int
- Index to start generation from (inclusive).
to_i
:int
- Index to run generation to (exclusive).
open
:array
offloat
- Entry price such as open or previous close.
high
:array
offloat
- High price.
low
:array
offloat
- Low price.
close
:array
offloat
- Close price.
stop_price_out
:array
offloat
- Array where hit price of each exit will be stored.
stop_type_out
:array
ofint
-
Array where stop type of each exit will be stored.
0 for stop loss, 1 for take profit.
sl_stop
:float
orarray_like
-
Percentage value for stop loss.
Can be per frame, column, row, or element-wise. Set to
np.nan
to disable. sl_trail
:bool
orarray_like
-
Whether
sl_stop
is trailing.Can be per frame, column, row, or element-wise. Set to False to disable.
tp_stop
:float
orarray_like
-
Percentage value for take profit.
Can be per frame, column, row, or element-wise. Set to
np.nan
to disable. reverse
:bool
orarray_like
- Whether to do the opposite, i.e.: prices are followed downwards.
is_open_safe
:bool
-
Whether entry price comes right at or before open.
If True and wait is 0, can use high/low at entry bar. Otherwise uses only close.
wait
:int
-
Number of ticks to wait before placing exits.
Setting False or 0 may result in entry and exit signal at one bar.
Note
If
wait
is greater than 0, even withis_open_safe
set to True, trailing stop won't update at bars that come beforefrom_i
. pick_first
:bool
- Whether to stop as soon as the first exit signal is found.
temp_idx_arr
:array
ofint
- Empty integer array used to temporarily store indices.
flex_2d
:bool
- See flex_select_auto_nb().
part_pos_rank_nb function¶
part_pos_rank_nb(
i,
col,
reset_i,
prev_part_end_i,
part_start_i,
part_pos_temp
)
rank_func_nb
that returns the rank of each partition by its position in the series.
partition_ranges_nb function¶
partition_ranges_nb(
a
)
Create a record of type range_dt for each partition of signals in a
.
rand_by_prob_choice_nb function¶
rand_by_prob_choice_nb(
from_i,
to_i,
col,
prob,
pick_first,
temp_idx_arr,
flex_2d
)
choice_func_nb
to randomly pick values from range [from_i, to_i)
with probability prob
.
prob
uses flexible indexing.
rand_choice_nb function¶
rand_choice_nb(
from_i,
to_i,
col,
n
)
choice_func_nb
to randomly pick n
values from range [from_i, to_i)
.
n
uses flexible indexing.
rand_enex_apply_nb function¶
rand_enex_apply_nb(
input_shape,
n,
entry_wait,
exit_wait
)
apply_func_nb
that calls generate_rand_enex_nb().
rank_nb function¶
rank_nb(
a,
reset_by,
after_false,
rank_func_nb,
*args
)
Rank each signal using rank_func_nb
.
Applies rank_func_nb
on each True value. Should accept index of the row, index of the column, index of the last reset signal, index of the end of the previous partition, index of the start of the current partition, and *args
. Should 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.
sig_pos_rank_nb function¶
sig_pos_rank_nb(
i,
col,
reset_i,
prev_part_end_i,
part_start_i,
sig_pos_temp,
allow_gaps
)
rank_func_nb
that returns the rank of each signal by its position in the partition.
stop_choice_nb function¶
stop_choice_nb(
from_i,
to_i,
col,
ts,
stop,
trailing,
wait,
pick_first,
temp_idx_arr,
flex_2d
)
choice_func_nb
that returns the indices of the stop being hit.
Args
from_i
:int
- Index to start generation from (inclusive).
to_i
:int
- Index to run generation to (exclusive).
col
:int
- Current column.
ts
:array
offloat
- 2-dim time series array such as price.
stop
:float
orarray_like
-
Stop value for stop loss.
Can be per frame, column, row, or element-wise. Set to
np.nan
to disable. trailing
:bool
orarray_like
-
Whether to use trailing stop.
Can be per frame, column, row, or element-wise. Set to False to disable.
wait
:int
-
Number of ticks to wait before placing exits.
Setting False or 0 may result in two signals at one bar.
Note
If
wait
is greater than 0, trailing stop won't update at bars that come beforefrom_i
. pick_first
:bool
- Whether to stop as soon as the first exit signal is found.
temp_idx_arr
:array
ofint
- Empty integer array used to temporarily store indices.
flex_2d
:bool
- See flex_select_auto_nb().