Skip to content

ranges module

Base class for working with range records.

Range records capture information on ranges. They are useful for analyzing duration of processes, such as drawdowns, trades, and positions. They also come in handy when analyzing distance between events, such as entry and exit signals.

Each range has a starting point and an ending point. For example, the points for range(20) are 0 and 20 (not 19!) respectively.

Note

Be aware that if a range hasn't ended in a column, its end_idx will point at the latest index. Make sure to account for this when computing custom metrics involving duration.

>>> from vectorbtpro import *

>>> start = '2019-01-01 UTC'  # crypto is in UTC
>>> end = '2020-01-01 UTC'
>>> price = vbt.YFData.pull('BTC-USD', start=start, end=end).get('Close')

100%

>>> fast_ma = vbt.MA.run(price, 10)
>>> slow_ma = vbt.MA.run(price, 50)
>>> fast_below_slow = fast_ma.ma_above(slow_ma)

>>> ranges = vbt.Ranges.from_array(fast_below_slow, wrapper_kwargs=dict(freq='d'))

>>> ranges.readable
   Range Id  Column           Start Timestamp             End Timestamp  \
0         0       0 2019-02-19 00:00:00+00:00 2019-07-25 00:00:00+00:00
1         1       0 2019-08-08 00:00:00+00:00 2019-08-19 00:00:00+00:00
2         2       0 2019-11-01 00:00:00+00:00 2019-11-20 00:00:00+00:00

   Status
0  Closed
1  Closed
2  Closed

>>> ranges.duration.max(wrap_kwargs=dict(to_timedelta=True))
Timedelta('156 days 00:00:00')

From accessors

Moreover, all generic accessors have a property ranges and a method get_ranges:

>>> # vectorbtpro.generic.accessors.GenericAccessor.ranges.coverage
>>> fast_below_slow.vbt.ranges.coverage
0.5081967213114754

Stats

>>> df = pd.DataFrame({
...     'a': [1, 2, np.nan, np.nan, 5, 6],
...     'b': [np.nan, 2, np.nan, 4, np.nan, 6]
... })
>>> ranges = df.vbt(freq='d').ranges

>>> ranges['a'].stats()
Start                             0
End                               5
Period              6 days 00:00:00
Total Records                     2
Coverage                   0.666667
Overlap Coverage                0.0
Duration: Min       2 days 00:00:00
Duration: Median    2 days 00:00:00
Duration: Max       2 days 00:00:00
Name: a, dtype: object

StatsBuilderMixin.stats() also supports (re-)grouping:

>>> ranges.stats(group_by=True)
Start                                       0
End                                         5
Period                        6 days 00:00:00
Total Records                               5
Coverage                             0.416667
Overlap Coverage                          0.4
Duration: Min                 1 days 00:00:00
Duration: Median              1 days 00:00:00
Duration: Max                 2 days 00:00:00
Name: group, dtype: object

Plots

Ranges class has a single subplot based on Ranges.plot():

>>> ranges['a'].plots().show()


pattern_ranges_field_config ReadonlyConfig

Field config for PatternRanges.

ReadonlyConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('start_idx', 'int64'),
        ('end_idx', 'int64'),
        ('status', 'int64'),
        ('similarity', 'float64')
    ]),
    settings=dict(
        id=dict(
            title='Pattern Range Id'
        ),
        similarity=dict(
            title='Similarity'
        )
    )
)

ranges_attach_field_config ReadonlyConfig

Config of fields to be attached to Ranges.

ReadonlyConfig(
    status=dict(
        attach_filters=True
    )
)

ranges_field_config ReadonlyConfig

Field config for Ranges.

ReadonlyConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('start_idx', 'int64'),
        ('end_idx', 'int64'),
        ('status', 'int64')
    ]),
    settings=dict(
        id=dict(
            title='Range Id'
        ),
        idx=dict(
            name='end_idx'
        ),
        start_idx=dict(
            title='Start Index',
            mapping='index'
        ),
        end_idx=dict(
            title='End Index',
            mapping='index'
        ),
        status=dict(
            title='Status',
            mapping=RangeStatusT(
                Open=0,
                Closed=1
            )
        )
    )
)

ranges_shortcut_config ReadonlyConfig

Config of shortcut properties to be attached to Ranges.

ReadonlyConfig(
    valid=dict(),
    invalid=dict(),
    first_pd_mask=dict(
        obj_type='array'
    ),
    last_pd_mask=dict(
        obj_type='array'
    ),
    ranges_pd_mask=dict(
        obj_type='array'
    ),
    first_idx=dict(
        obj_type='mapped_array'
    ),
    last_idx=dict(
        obj_type='mapped_array'
    ),
    duration=dict(
        obj_type='mapped_array'
    ),
    real_duration=dict(
        obj_type='mapped_array'
    ),
    avg_duration=dict(
        obj_type='red_array'
    ),
    max_duration=dict(
        obj_type='red_array'
    ),
    coverage=dict(
        obj_type='red_array'
    ),
    overlap_coverage=dict(
        method_name='get_coverage',
        obj_type='red_array',
        method_kwargs=dict(
            overlapping=True
        )
    ),
    projections=dict(
        obj_type='array'
    )
)

PSC class

PSC(
    *args,
    **kwargs
)

Class that represents a pattern search config.

Every field will be resolved into the format suitable for Numba.

Superclasses

Inherited members


distance_measure class variable

Distance measure. See DistanceMeasure.


error_type class variable

Error type. See ErrorType.


interp_mode class variable

Interpolation mode. See InterpMode.


invert class variable

Whether to invert the pattern vertically.


max_error class variable

Maximum error at each point. Can be provided as a flexible array.

If max_error is an array, it must be of the same size as the pattern array. It also should be provided within the same scale as the pattern.


max_error_as_maxdist class variable

Whether PSC.max_error should be used as the maximum distance at each point.

If False, crossing PSC.max_error will set the distance to the maximum distance based on PSC.pmin, PSC.pmax, and the pattern value at that point.

If True and any of the points in a window is np.nan, the point will be skipped.


max_error_interp_mode class variable

Interpolation mode for PSC.max_error. See InterpMode.

If None, defaults to PSC.interp_mode.


max_error_strict class variable

Whether crossing PSC.max_error even once should yield the similarity of np.nan.


max_pct_change class variable

Maximum percentage change of the window to stay a candidate for search.

If any window crosses this mark, its similarity becomes np.nan.


max_records class variable

Maximum number of records expected to be filled.

Set to avoid creating empty arrays larger than needed.


max_window class variable

Maximum window (including).


min_pct_change class variable

Minimum percentage change of the window to stay a candidate for search.

If any window doesn't cross this mark, its similarity becomes np.nan.


min_similarity class variable

Minimum similarity.

If any window doesn't cross this mark, its similarity becomes np.nan.


minp class variable

Minimum number of observations in price window required to have a value.


name class variable

Name of the config.


overlap_mode class variable

Overlapping mode. See OverlapMode.


pattern class variable

Flexible pattern array.

Can be smaller or bigger than the source array; in such a case, the values of the smaller array will be "stretched" by interpolation of the type in PSC.interp_mode.


pmax class variable

Value to be considered as the maximum of PSC.pattern.

Used in rescaling using RescaleMode.MinMax and calculating the maximum distance at each point if PSC.max_error_as_maxdist is disabled.

If np.nan, gets calculated dynamically.


pmin class variable

Value to be considered as the minimum of PSC.pattern.

Used in rescaling using RescaleMode.MinMax and calculating the maximum distance at each point if PSC.max_error_as_maxdist is disabled.

If np.nan, gets calculated dynamically.


rescale_mode class variable

Rescaling mode. See RescaleMode.


roll_forward class variable

Whether to roll windows to the left of the current row, otherwise to the right.


row_select_prob class variable

Row selection probability.


vmax class variable

Maximum value of any window. Should only be used when the array has fixed bounds.

Used in rescaling using RescaleMode.MinMax and checking against PSC.min_pct_change and PSC.max_pct_change.

If np.nan, gets calculated dynamically.


vmin class variable

Minimum value of any window. Should only be used when the array has fixed bounds.

Used in rescaling using RescaleMode.MinMax and checking against PSC.min_pct_change and PSC.max_pct_change.

If np.nan, gets calculated dynamically.


window class variable

Minimum window.

Defaults to the length of PSC.pattern.


window_select_prob class variable

Window selection probability.


PatternRanges class

PatternRanges(
    wrapper,
    records_arr,
    search_configs,
    **kwargs
)

Extends Ranges for working with range records generated from pattern search.

Superclasses

Inherited members


field_config class variable

Field config of PatternRanges.

HybridConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('start_idx', 'int64'),
        ('end_idx', 'int64'),
        ('status', 'int64'),
        ('similarity', 'float64')
    ]),
    settings=dict(
        id=dict(
            name='id',
            title='Pattern Range Id',
            mapping='ids'
        ),
        col=dict(
            name='col',
            title='Column',
            mapping='columns',
            as_customdata=False
        ),
        idx=dict(
            name='end_idx',
            title='Index',
            mapping='index'
        ),
        start_idx=dict(
            title='Start Index',
            mapping='index'
        ),
        end_idx=dict(
            title='End Index',
            mapping='index'
        ),
        status=dict(
            title='Status',
            mapping=RangeStatusT(
                Open=0,
                Closed=1
            )
        ),
        similarity=dict(
            title='Similarity'
        )
    )
)

Returns PatternRanges._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 PatternRanges._field_config.


PatternRanges.from_pattern_search(
    arr,
    pattern=None,
    window=None,
    max_window=None,
    row_select_prob=1.0,
    window_select_prob=1.0,
    roll_forward=False,
    interp_mode='mixed',
    rescale_mode='minmax',
    vmin=nan,
    vmax=nan,
    pmin=nan,
    pmax=nan,
    invert=False,
    error_type='absolute',
    distance_measure='mae',
    max_error=nan,
    max_error_interp_mode=None,
    max_error_as_maxdist=False,
    max_error_strict=False,
    min_pct_change=nan,
    max_pct_change=nan,
    min_similarity=0.85,
    minp=None,
    overlap_mode='disallow',
    max_records=None,
    random_subset=None,
    seed=None,
    search_configs=None,
    jitted=None,
    execute_kwargs=None,
    attach_as_close=True,
    clean_index_kwargs=None,
    wrapper_kwargs=None,
    **kwargs
)

Build PatternRanges from all occurrences of a pattern in an array.

Searches for parameters of the type Param, and if found, broadcasts and combines them using combine_params(). Then, converts them into a list of search configurations. If none of such parameters was found among the passed arguments, builds one search configuration using the passed arguments. If search_configs is not None, uses it instead. In all cases, it uses the defaults defined in the signature of this method to augment search configurations. For example, passing min_similarity of 95% will use it in all search configurations except where it was explicitly overridden.

Argument search_configs must be provided as a sequence of PSC instances. If any element is a list of PSC instances itself, it will be used per column in arr, otherwise per entire arr. Each configuration will be resolved using PatternRanges.resolve_search_config() to prepare arguments for the use in Numba.

After all the search configurations have been resolved, uses execute() to loop over each configuration and execute it using find_pattern_1d_nb(). The results are then concatenated into a single records array and wrapped with PatternRanges.

If attach_as_close is True, will attach arr as close.

**kwargs will be passed to PatternRanges.


indexing_func method

PatternRanges.indexing_func(
    *args,
    ranges_meta=None,
    **kwargs
)

Perform indexing on PatternRanges.


metrics class variable

Metrics supported by PatternRanges.

HybridConfig(
    start_index=dict(
        title='Start Index',
        calc_func=<function Ranges.<lambda> at 0x1325968e0>,
        agg_func=None,
        tags='wrapper'
    ),
    end_index=dict(
        title='End Index',
        calc_func=<function Ranges.<lambda> at 0x132596980>,
        agg_func=None,
        tags='wrapper'
    ),
    total_duration=dict(
        title='Total Duration',
        calc_func=<function Ranges.<lambda> at 0x132596a20>,
        apply_to_timedelta=True,
        agg_func=None,
        tags='wrapper'
    ),
    total_records=dict(
        title='Total Records',
        calc_func='count',
        tags='records'
    ),
    coverage=dict(
        title='Coverage',
        calc_func='coverage',
        overlapping=False,
        tags=[
            'ranges',
            'coverage'
        ]
    ),
    overlap_coverage=dict(
        title='Overlap Coverage',
        calc_func='coverage',
        overlapping=True,
        tags=[
            'ranges',
            'coverage'
        ]
    ),
    duration=dict(
        title='Duration',
        calc_func='duration.describe',
        post_calc_func=<function Ranges.<lambda> at 0x132596ac0>,
        apply_to_timedelta=True,
        tags=[
            'ranges',
            'duration'
        ]
    ),
    similarity=dict(
        title='Similarity',
        calc_func='similarity.describe',
        post_calc_func=<function PatternRanges.<lambda> at 0x1325a8e00>,
        tags=[
            'pattern_ranges',
            'similarity'
        ]
    )
)

Returns PatternRanges._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 PatternRanges._metrics.


plot method

PatternRanges.plot(
    column=None,
    top_n=None,
    fit_ranges=False,
    plot_patterns=True,
    plot_max_error=False,
    fill_distance=True,
    pattern_trace_kwargs=None,
    lower_max_error_trace_kwargs=None,
    upper_max_error_trace_kwargs=None,
    add_trace_kwargs=None,
    xref='x',
    yref='y',
    fig=None,
    **kwargs
)

Plot pattern ranges.

Based on Ranges.plot() and GenericAccessor.plot_pattern().

Args

column : str
Name of the column to plot.
top_n : int
Filter top N range records by maximum duration.
fit_ranges : bool, int, or sequence of int

Whether or which range records to fit.

True to fit to all range records, integer or a sequence of such to fit to specific range records.

plot_patterns : bool or array_like
Whether to plot PSC.pattern.
plot_max_error : array_like
Whether to plot PSC.max_error.
fill_distance : bool

Whether to fill the space between close and pattern.

Visible for every interpolation mode except discrete.

pattern_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for pattern.
lower_max_error_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for lower max error.
upper_max_error_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for upper max error.
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.
**kwargs
Keyword arguments passed to Ranges.plot().

resolve_column_stack_kwargs class method

PatternRanges.resolve_column_stack_kwargs(
    *objs,
    **kwargs
)

Resolve keyword arguments for initializing PatternRanges after stacking along columns.


resolve_row_stack_kwargs class method

PatternRanges.resolve_row_stack_kwargs(
    *objs,
    **kwargs
)

Resolve keyword arguments for initializing PatternRanges after stacking along columns.


resolve_search_config class method

PatternRanges.resolve_search_config(
    search_config=None,
    **kwargs
)

Resolve search config for PatternRanges.from_pattern_search().

Converts array-like objects into arrays and enums into integers.


search_configs property

List of PSC instances, one per column.


similarity property

Mapped array of the field similarity.


with_delta method

PatternRanges.with_delta(
    *args,
    **kwargs
)

Pass self to Ranges.from_delta() but with the index set to the last index.


Ranges class

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

Extends PriceRecords for working with range records.

Requires records_arr to have all fields defined in range_dt.

Superclasses

Inherited members

Subclasses


avg_duration property

Ranges.get_avg_duration() with default arguments.


col property

Mapped array of the field col.


coverage property

Ranges.get_coverage() with default arguments.


crop method

Ranges.crop()

Remove any data outside the minimum start index and the maximum end index.


duration property

Ranges.get_duration() with default arguments.


end_idx property

Mapped array of the field end_idx.


field_config class variable

Field config of Ranges.

HybridConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('start_idx', 'int64'),
        ('end_idx', 'int64'),
        ('status', 'int64')
    ]),
    settings=dict(
        id=dict(
            name='id',
            title='Range Id',
            mapping='ids'
        ),
        col=dict(
            name='col',
            title='Column',
            mapping='columns',
            as_customdata=False
        ),
        idx=dict(
            name='end_idx',
            title='Index',
            mapping='index'
        ),
        start_idx=dict(
            title='Start Index',
            mapping='index'
        ),
        end_idx=dict(
            title='End Index',
            mapping='index'
        ),
        status=dict(
            title='Status',
            mapping=RangeStatusT(
                Open=0,
                Closed=1
            )
        )
    )
)

Returns Ranges._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 Ranges._field_config.


filter_max_duration method

Ranges.filter_max_duration(
    max_duration,
    real=False,
    **kwargs
)

Filter out ranges that last more than a maximum duration.


filter_min_duration method

Ranges.filter_min_duration(
    min_duration,
    real=False,
    **kwargs
)

Filter out ranges that last less than a minimum duration.


first_idx property

Ranges.get_first_idx() with default arguments.


first_pd_mask property

Ranges.get_first_pd_mask() with default arguments.


from_array class method

Ranges.from_array(
    arr,
    gap_value=None,
    attach_as_close=True,
    jitted=None,
    chunked=None,
    wrapper_kwargs=None,
    **kwargs
)

Build Ranges from an array.

Searches for sequences of

  • True values in boolean data (False acts as a gap),
  • positive values in integer data (-1 acts as a gap), and
  • non-NaN values in any other data (NaN acts as a gap).

If attach_as_close is True, will attach arr as close.

**kwargs will be passed to Ranges.


from_delta class method

Ranges.from_delta(
    records_or_mapped,
    delta,
    shift=None,
    idx_field_or_arr=None,
    jitted=None,
    chunked=None,
    **kwargs
)

Build Ranges from a record/mapped array with a timedelta applied on its index field.

See get_ranges_from_delta_nb().

Set delta to an integer to wait a certain amount of rows. Set it to anything else to wait a timedelta. The conversion is done using to_timedelta64(). The second option requires the index to be datetime-like, or at least the frequency to be set.

**kwargs will be passed to Ranges.


get_avg_duration method

Ranges.get_avg_duration(
    real=False,
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None,
    **kwargs
)

Get average range duration (as timedelta).


get_coverage method

Ranges.get_coverage(
    overlapping=False,
    normalize=True,
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None
)

Get coverage, that is, the number of steps that are covered by all ranges.

See range_coverage_nb().


get_duration method

Ranges.get_duration(
    jitted=None,
    chunked=None,
    **kwargs
)

Get the effective duration of each range in integer format.


get_first_idx method

Ranges.get_first_idx(
    **kwargs
)

Get the first index in each range.


get_first_pd_mask method

Ranges.get_first_pd_mask(
    group_by=None,
    **kwargs
)

Get mask from Ranges.get_first_idx().


get_invalid method

Ranges.get_invalid(
    **kwargs
)

Get invalid ranges.

An invalid range has the start and/or end index set to -1.


get_last_idx method

Ranges.get_last_idx(
    **kwargs
)

Get the last index in each range.


get_last_pd_mask method

Ranges.get_last_pd_mask(
    group_by=None,
    **kwargs
)

Get mask from Ranges.get_last_idx().


get_max_duration method

Ranges.get_max_duration(
    real=False,
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None,
    **kwargs
)

Get maximum range duration (as timedelta).


get_projections method

Ranges.get_projections(
    close=None,
    proj_start=None,
    proj_period=None,
    incl_end_idx=True,
    extend=False,
    rebase=True,
    start_value=1.0,
    ffill=False,
    remove_empty=True,
    return_raw=False,
    start_index=None,
    id_level=None,
    jitted=None,
    wrap_kwargs=None,
    clean_index_kwargs=None
)

Generate a projection for each range record.

See map_ranges_to_projections_nb().

Set proj_start to an integer to generate a projection after a certain row after the start row. Set it to anything else to wait a timedelta. The conversion is done using to_timedelta64(). The second option requires the index to be datetime-like, or at least the frequency to be set.

Set proj_period the same way as proj_start to generate a projection of a certain length. Unless extend is True, it still respects the duration of the range.

Set extend to True to extend the projection even after the end of the range. The extending period is taken from the longest range duration if proj_period is None, and from the longest proj_period if it's not None.

Set rebase to True to make each projection start with 1, otherwise, each projection will consist of original close values during the projected period. Use start_value to replace 1 with another start value. It can also be a flexible array with elements per column. If start_value is -1, will set it to the latest row in close.

Set ffill to True to forward fill NaN values, even if they are NaN in close itself.

Set remove_empty to True to remove projections that are either NaN or with only one element. The index of each projection is still being tracked and will appear in the multi-index of the returned DataFrame.

Note

As opposed to the Numba-compiled function, the returned DataFrame will have projections stacked along columns rather than rows. Set return_raw to True to return them in the original format.


get_ranges_pd_mask method

Ranges.get_ranges_pd_mask(
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None
)

Get mask from ranges.

See ranges_to_mask_nb().


get_real_duration method

Ranges.get_real_duration(
    jitted=None,
    chunked=None,
    **kwargs
)

Get the real duration of each range in timedelta format.


get_valid method

Ranges.get_valid(
    **kwargs
)

Get valid ranges.

A valid range doesn't have the start and end index set to -1.


id property

Mapped array of the field id.


invalid property

Ranges.get_invalid() with default arguments.


last_idx property

Ranges.get_last_idx() with default arguments.


last_pd_mask property

Ranges.get_last_pd_mask() with default arguments.


max_duration property

Ranges.get_max_duration() with default arguments.


metrics class variable

Metrics supported by Ranges.

HybridConfig(
    start_index=dict(
        title='Start Index',
        calc_func=<function Ranges.<lambda> at 0x1325968e0>,
        agg_func=None,
        tags='wrapper'
    ),
    end_index=dict(
        title='End Index',
        calc_func=<function Ranges.<lambda> at 0x132596980>,
        agg_func=None,
        tags='wrapper'
    ),
    total_duration=dict(
        title='Total Duration',
        calc_func=<function Ranges.<lambda> at 0x132596a20>,
        apply_to_timedelta=True,
        agg_func=None,
        tags='wrapper'
    ),
    total_records=dict(
        title='Total Records',
        calc_func='count',
        tags='records'
    ),
    coverage=dict(
        title='Coverage',
        calc_func='coverage',
        overlapping=False,
        tags=[
            'ranges',
            'coverage'
        ]
    ),
    overlap_coverage=dict(
        title='Overlap Coverage',
        calc_func='coverage',
        overlapping=True,
        tags=[
            'ranges',
            'coverage'
        ]
    ),
    duration=dict(
        title='Duration',
        calc_func='duration.describe',
        post_calc_func=<function Ranges.<lambda> at 0x132596ac0>,
        apply_to_timedelta=True,
        tags=[
            'ranges',
            'duration'
        ]
    )
)

Returns Ranges._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 Ranges._metrics.


overlap_coverage property

Ranges.get_coverage() with arguments {'overlapping': True}.


plot method

Ranges.plot(
    column=None,
    top_n=None,
    plot_ohlc=True,
    plot_close=True,
    plot_markers=True,
    plot_zones=True,
    ohlc_type=None,
    ohlc_trace_kwargs=None,
    close_trace_kwargs=None,
    start_trace_kwargs=None,
    end_trace_kwargs=None,
    open_shape_kwargs=None,
    closed_shape_kwargs=None,
    add_trace_kwargs=None,
    xref='x',
    yref='y',
    fig=None,
    return_close=False,
    **layout_kwargs
)

Plot ranges.

Args

column : str
Name of the column to plot.
top_n : int
Filter top N range records by maximum duration.
plot_ohlc : bool or DataFrame
Whether to plot OHLC.
plot_close : bool or Series
Whether to plot close.
plot_markers : bool
Whether to plot markers.
plot_zones : bool
Whether to plot zones.
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 Ranges.close.
start_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for start values.
end_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for end values.
open_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for open zones.
closed_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for closed 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.
return_close : bool
Whether to return the close series along with the figure.
**layout_kwargs
Keyword arguments for layout.

Usage

>>> price = pd.Series(
...     [1, 2, 1, 2, 3, 2, 1, 2, 3],
...     index=pd.date_range("2020", periods=9),
... )
>>> vbt.Ranges.from_array(price >= 2).plot().show()


plot_projections method

Ranges.plot_projections(
    column=None,
    min_duration=None,
    max_duration=None,
    last_n=None,
    top_n=None,
    random_n=None,
    seed=None,
    proj_start='current_or_0',
    proj_period='max',
    incl_end_idx=True,
    extend=False,
    ffill=False,
    plot_past_period='current_or_proj_period',
    plot_ohlc=True,
    plot_close=True,
    plot_projections=True,
    plot_bands=True,
    plot_lower=True,
    plot_middle=True,
    plot_upper=True,
    plot_aux_middle=True,
    plot_fill=True,
    colorize=True,
    ohlc_type=None,
    ohlc_trace_kwargs=None,
    close_trace_kwargs=None,
    projection_trace_kwargs=None,
    lower_trace_kwargs=None,
    middle_trace_kwargs=None,
    upper_trace_kwargs=None,
    aux_middle_trace_kwargs=None,
    add_trace_kwargs=None,
    fig=None,
    **layout_kwargs
)

Plot projections.

Combines generation of projections using Ranges.get_projections() and their plotting using GenericDFAccessor.plot_projections().

Args

column : str
Name of the column to plot.
min_duration : str, int, or frequency_like
Filter range records by minimum duration.
max_duration : str, int, or frequency_like
Filter range records by maximum duration.
last_n : int
Select last N range records.
top_n : int
Select top N range records by maximum duration.
random_n : int
Select N range records randomly.
seed : int
Seed to make output deterministic.
proj_start : str, int, or frequency_like

See Ranges.get_projections().

Allows an additional option "current_or_{value}", which sets proj_start to the duration of the current open range, and to the specified value if there is no open range.

proj_period : str, int, or frequency_like

See Ranges.get_projections().

Allows additional options "current_or_{option}", "mean", "min", "max", "median", or a percentage such as "50%" representing a quantile. All of those options are based on the duration of all the closed ranges filtered by the arguments above.

incl_end_idx : bool
See Ranges.get_projections().
extend : bool
See Ranges.get_projections().
ffill : bool
See Ranges.get_projections().
plot_past_period : str, int, or frequency_like

Past period to plot.

Allows the same options as proj_period plus "proj_period" and "current_or_proj_period".

plot_ohlc : bool or DataFrame
Whether to plot OHLC.
plot_close : bool or Series
Whether to plot close.
plot_projections : bool
See GenericDFAccessor.plot_projections().
plot_bands : bool
See GenericDFAccessor.plot_projections().
plot_lower : bool, str, or callable
See GenericDFAccessor.plot_projections().
plot_middle : bool, str, or callable
See GenericDFAccessor.plot_projections().
plot_upper : bool, str, or callable
See GenericDFAccessor.plot_projections().
plot_aux_middle : bool, str, or callable
See GenericDFAccessor.plot_projections().
plot_fill : bool
See GenericDFAccessor.plot_projections().
colorize : bool, str, or callable
See GenericDFAccessor.plot_projections().
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 Ranges.close.
projection_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for projections.
lower_trace_kwargs : dict
Keyword arguments passed to plotly.plotly.graph_objects.Scatter for lower band.
middle_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for middle band.
upper_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for upper band.
aux_middle_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for auxiliary middle band.
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

>>> price = pd.Series(
...     [11, 12, 13, 14, 11, 12, 13, 12, 11, 12],
...     index=pd.date_range("2020", periods=10),
... )
>>> vbt.Ranges.from_array(
...     price >= 12,
...     attach_as_close=False,
...     close=price,
... ).plot_projections(
...     proj_start=0,
...     proj_period=4,
...     extend=True,
...     plot_past_period=None
... ).show()


plot_shapes method

Ranges.plot_shapes(
    column=None,
    plot_ohlc=True,
    plot_close=True,
    ohlc_type=None,
    ohlc_trace_kwargs=None,
    close_trace_kwargs=None,
    shape_kwargs=None,
    add_trace_kwargs=None,
    xref='x',
    yref='y',
    fig=None,
    **layout_kwargs
)

Plot range shapes.

Args

column : str
Name of the column to plot.
plot_ohlc : bool or DataFrame
Whether to plot OHLC.
plot_close : bool or Series
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 Ranges.close.
shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for shapes.
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

  • Plot zones colored by duration:
>>> price = pd.Series(
...     [1, 2, 1, 2, 3, 2, 1, 2, 3],
...     index=pd.date_range("2020", periods=9),
... )

>>> def get_opacity(self_col, i):
...     real_duration = self_col.get_real_duration().values
...     return real_duration[i] / real_duration.max() * 0.5

>>> vbt.Ranges.from_array(price >= 2).plot_shapes(
...     shape_kwargs=dict(fillcolor="teal", opacity=vbt.RepFunc(get_opacity))
... ).show()


plots_defaults property

Defaults for PlotsBuilderMixin.plots().

Merges Records.plots_defaults and plots from ranges.


projections property

Ranges.get_projections() with default arguments.


ranges_pd_mask property

Ranges.get_ranges_pd_mask() with default arguments.


real_duration property

Ranges.get_real_duration() with default arguments.


start_idx property

Mapped array of the field start_idx.


stats_defaults property

Defaults for StatsBuilderMixin.stats().

Merges Records.stats_defaults and stats from ranges.


status property

Mapped array of the field status.


status_closed property

Records filtered by status == 1.


status_open property

Records filtered by status == 0.


subplots class variable

Subplots supported by Ranges.

HybridConfig(
    plot=dict(
        title='Ranges',
        check_is_not_grouped=True,
        plot_func='plot',
        tags='ranges'
    )
)

Returns Ranges._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 Ranges._subplots.


valid property

Ranges.get_valid() with default arguments.


with_delta method

Ranges.with_delta(
    *args,
    **kwargs
)

Pass self to Ranges.from_delta().