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')
>>> 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¶
Hint
See StatsBuilderMixin.stats and Ranges.metrics.
>>> 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¶
Hint
See PlotsBuilderMixin.plots and Ranges.subplots.
Ranges class has a single subplot based on Ranges.plot:
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.
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¶
Class that represents a pattern search config.
Every field will be resolved into the format suitable for Numba.
Superclasses
Inherited members
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- DefineMixin.asdict
- DefineMixin.assert_field_not_missing
- DefineMixin.fields
- DefineMixin.fields_dict
- DefineMixin.get_field
- DefineMixin.hash
- DefineMixin.hash_key
- DefineMixin.is_field_missing
- DefineMixin.is_field_optional
- DefineMixin.is_field_required
- DefineMixin.merge_over
- DefineMixin.merge_with
- DefineMixin.replace
- DefineMixin.resolve
- DefineMixin.resolve_field
- Hashable.get_hash
distance_measure field¶
Distance measure. See DistanceMeasure.
error_type field¶
Error type. See ErrorType.
interp_mode field¶
Interpolation mode. See InterpMode.
invert field¶
Whether to invert the pattern vertically.
max_error field¶
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 field¶
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 field¶
Interpolation mode for PSC.max_error. See InterpMode.
If None, defaults to PSC.interp_mode.
max_error_strict field¶
Whether crossing PSC.max_error even once should yield the similarity of np.nan.
max_pct_change field¶
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 field¶
Maximum number of records expected to be filled.
Set to avoid creating empty arrays larger than needed.
max_window field¶
Maximum window (including).
min_pct_change field¶
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 field¶
Minimum similarity.
If any window doesn't cross this mark, its similarity becomes np.nan.
minp field¶
Minimum number of observations in price window required to have a value.
name field¶
Name of the config.
overlap_mode field¶
Overlapping mode. See OverlapMode.
pattern field¶
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 field¶
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 field¶
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 field¶
Rescaling mode. See RescaleMode.
roll_forward field¶
Whether to roll windows to the left of the current row, otherwise to the right.
row_select_prob field¶
Row selection probability.
vmax field¶
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 field¶
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 field¶
Minimum window.
Defaults to the length of PSC.pattern.
window_select_prob field¶
Window selection probability.
PatternRanges class¶
Extends Ranges for working with range records generated from pattern search.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Ranges
- Records
- StatsBuilderMixin
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.indexing_func_meta
- PriceRecords.resample
- Ranges.avg_duration
- Ranges.bar_close
- Ranges.bar_close_time
- Ranges.bar_high
- Ranges.bar_low
- Ranges.bar_open
- Ranges.bar_open_time
- Ranges.close
- Ranges.cls_dir
- Ranges.col
- Ranges.col_arr
- Ranges.col_mapper
- Ranges.column_only_select
- Ranges.config
- Ranges.coverage
- Ranges.crop
- Ranges.duration
- Ranges.end_idx
- Ranges.field_names
- Ranges.filter_max_duration
- Ranges.filter_min_duration
- Ranges.first_idx
- Ranges.first_pd_mask
- Ranges.from_array
- Ranges.from_delta
- Ranges.get_avg_duration
- Ranges.get_coverage
- Ranges.get_duration
- Ranges.get_first_idx
- Ranges.get_first_pd_mask
- Ranges.get_invalid
- Ranges.get_last_idx
- Ranges.get_last_pd_mask
- Ranges.get_max_duration
- Ranges.get_projections
- Ranges.get_ranges_pd_mask
- Ranges.get_real_duration
- Ranges.get_valid
- Ranges.group_select
- Ranges.high
- Ranges.id
- Ranges.id_arr
- Ranges.idx_arr
- Ranges.iloc
- Ranges.indexing_kwargs
- Ranges.invalid
- Ranges.last_idx
- Ranges.last_pd_mask
- Ranges.loc
- Ranges.low
- Ranges.max_duration
- Ranges.open
- Ranges.overlap_coverage
- Ranges.pd_mask
- Ranges.plot_projections
- Ranges.plot_shapes
- Ranges.plots_defaults
- Ranges.projections
- Ranges.range_only_select
- Ranges.ranges_pd_mask
- Ranges.readable
- Ranges.real_duration
- Ranges.rec_state
- Ranges.recarray
- Ranges.records
- Ranges.records_arr
- Ranges.records_readable
- Ranges.self_aliases
- Ranges.start_idx
- Ranges.stats_defaults
- Ranges.status
- Ranges.status_closed
- Ranges.status_open
- Ranges.unwrapped
- Ranges.valid
- Ranges.values
- Ranges.wrapper
- Ranges.xloc
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
field_config property¶
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.
from_pattern_search class method¶
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¶
Perform indexing on PatternRanges.
metrics property¶
Metrics supported by PatternRanges.
HybridConfig(
start_index=dict(
title='Start Index',
calc_func=<function Ranges.<lambda> at 0x147fa44a0>,
agg_func=None,
tags='wrapper'
),
end_index=dict(
title='End Index',
calc_func=<function Ranges.<lambda> at 0x147fa4540>,
agg_func=None,
tags='wrapper'
),
total_duration=dict(
title='Total Duration',
calc_func=<function Ranges.<lambda> at 0x147fa45e0>,
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 0x147fa4680>,
apply_to_timedelta=True,
tags=[
'ranges',
'duration'
]
),
similarity=dict(
title='Similarity',
calc_func='similarity.describe',
post_calc_func=<function PatternRanges.<lambda> at 0x147fa6200>,
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 sequenceofint-
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:boolorarray_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.Scatterfor pattern. lower_max_error_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor lower max error. upper_max_error_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor upper max error. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
**kwargs- Keyword arguments passed to Ranges.plot.
resolve_column_stack_kwargs class method¶
Resolve keyword arguments for initializing PatternRanges after stacking along columns.
resolve_row_stack_kwargs class method¶
Resolve keyword arguments for initializing PatternRanges after stacking along columns.
resolve_search_config class method¶
Resolve search config for PatternRanges.from_pattern_search.
Converts array-like objects into arrays and enums into integers.
search_configs class property¶
List of PSC instances, one per column.
similarity cached_property¶
Mapped array of the field similarity.
with_delta method¶
Pass self to Ranges.from_delta but with the index set to the last index.
Ranges class¶
Extends PriceRecords for working with range records.
Requires records_arr to have all fields defined in range_dt.
Superclasses
- Analyzable
- AttrResolverMixin
- Base
- Cacheable
- Chainable
- Comparable
- Configured
- ExtPandasIndexer
- HasSettings
- HasWrapper
- IndexApplier
- IndexingBase
- ItemParamable
- Itemable
- PandasIndexer
- Paramable
- Pickleable
- PlotsBuilderMixin
- Prettified
- PriceRecords
- Records
- StatsBuilderMixin
- Wrapping
Inherited members
- AttrResolverMixin.deep_getattr
- AttrResolverMixin.post_resolve_attr
- AttrResolverMixin.pre_resolve_attr
- AttrResolverMixin.resolve_attr
- AttrResolverMixin.resolve_shortcut_attr
- Base.chat
- Base.find_api
- Base.find_assets
- Base.find_docs
- Base.find_examples
- Base.find_messages
- Cacheable.get_ca_setup
- Chainable.chain
- Chainable.pipe
- Configured.copy
- Configured.equals
- Configured.get_writeable_attrs
- Configured.prettify
- Configured.resolve_merge_kwargs
- Configured.update_config
- HasSettings.get_path_setting
- HasSettings.get_path_settings
- HasSettings.get_setting
- HasSettings.get_settings
- HasSettings.has_path_setting
- HasSettings.has_path_settings
- HasSettings.has_setting
- HasSettings.has_settings
- HasSettings.reset_settings
- HasSettings.resolve_setting
- HasSettings.resolve_settings_paths
- HasSettings.set_settings
- HasWrapper.chunk
- HasWrapper.chunk_apply
- HasWrapper.get_item_keys
- HasWrapper.items
- HasWrapper.select_col
- HasWrapper.select_col_from_obj
- HasWrapper.should_wrap
- HasWrapper.split
- HasWrapper.split_apply
- HasWrapper.ungroup
- IndexApplier.add_levels
- IndexApplier.drop_duplicate_levels
- IndexApplier.drop_levels
- IndexApplier.drop_redundant_levels
- IndexApplier.rename_levels
- IndexApplier.select_levels
- IndexingBase.indexing_setter_func
- ItemParamable.as_param
- PandasIndexer.xs
- Pickleable.decode_config
- Pickleable.decode_config_node
- Pickleable.dumps
- Pickleable.encode_config
- Pickleable.encode_config_node
- Pickleable.file_exists
- Pickleable.getsize
- Pickleable.load
- Pickleable.loads
- Pickleable.modify_state
- Pickleable.resolve_file_path
- Pickleable.save
- PlotsBuilderMixin.build_subplots_doc
- PlotsBuilderMixin.override_subplots_doc
- PlotsBuilderMixin.plots
- PlotsBuilderMixin.resolve_plots_setting
- Prettified.pprint
- PriceRecords.bar_close
- PriceRecords.bar_close_time
- PriceRecords.bar_high
- PriceRecords.bar_low
- PriceRecords.bar_open
- PriceRecords.bar_open_time
- PriceRecords.close
- PriceRecords.cls_dir
- PriceRecords.col_arr
- PriceRecords.col_mapper
- PriceRecords.column_only_select
- PriceRecords.config
- PriceRecords.field_names
- PriceRecords.from_records
- PriceRecords.get_bar_close
- PriceRecords.get_bar_close_time
- PriceRecords.get_bar_high
- PriceRecords.get_bar_low
- PriceRecords.get_bar_open
- PriceRecords.get_bar_open_time
- PriceRecords.group_select
- PriceRecords.high
- PriceRecords.id_arr
- PriceRecords.idx_arr
- PriceRecords.iloc
- PriceRecords.indexing_func
- PriceRecords.indexing_func_meta
- PriceRecords.indexing_kwargs
- PriceRecords.loc
- PriceRecords.low
- PriceRecords.open
- PriceRecords.pd_mask
- PriceRecords.range_only_select
- PriceRecords.readable
- PriceRecords.rec_state
- PriceRecords.recarray
- PriceRecords.records
- PriceRecords.records_arr
- PriceRecords.records_readable
- PriceRecords.resample
- PriceRecords.resolve_column_stack_kwargs
- PriceRecords.resolve_row_stack_kwargs
- PriceRecords.self_aliases
- PriceRecords.unwrapped
- PriceRecords.values
- PriceRecords.wrapper
- PriceRecords.xloc
- Records.apply
- Records.apply_mask
- Records.build_field_config_doc
- Records.column_stack
- Records.column_stack_records_arrs
- Records.count
- Records.coverage_map
- Records.first_n
- Records.get_apply_mapping_arr
- Records.get_apply_mapping_str_arr
- Records.get_column_stack_record_indices
- Records.get_field_arr
- Records.get_field_mapping
- Records.get_field_name
- Records.get_field_setting
- Records.get_field_title
- Records.get_map_field
- Records.get_map_field_to_columns
- Records.get_map_field_to_index
- Records.get_pd_mask
- Records.get_row_stack_record_indices
- Records.has_conflicts
- Records.is_sorted
- Records.last_n
- Records.map
- Records.map_array
- Records.map_field
- Records.override_field_config_doc
- Records.prepare_customdata
- Records.random_n
- Records.replace
- Records.resample_meta
- Records.resample_records_arr
- Records.row_stack
- Records.row_stack_records_arrs
- Records.select_cols
- Records.sort
- Records.to_readable
- StatsBuilderMixin.build_metrics_doc
- StatsBuilderMixin.override_metrics_doc
- StatsBuilderMixin.resolve_stats_setting
- StatsBuilderMixin.stats
- Wrapping.apply_to_index
- Wrapping.regroup
- Wrapping.resolve_self
- Wrapping.resolve_stack_kwargs
Subclasses
avg_duration cached_property¶
Ranges.get_avg_duration with default arguments.
col cached_property¶
Mapped array of the field col.
coverage cached_property¶
Ranges.get_coverage with default arguments.
crop method¶
Remove any data outside the minimum start index and the maximum end index.
duration cacheable_property¶
Ranges.get_duration with default arguments.
end_idx cached_property¶
Mapped array of the field end_idx.
field_config property¶
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¶
Filter out ranges that last more than a maximum duration.
filter_min_duration method¶
Filter out ranges that last less than a minimum duration.
first_idx cacheable_property¶
Ranges.get_first_idx with default arguments.
first_pd_mask cacheable_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.
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¶
Get the effective duration of each range in integer format.
get_first_idx method¶
Get the first index in each range.
get_first_pd_mask method¶
Get mask from Ranges.get_first_idx.
get_invalid method¶
Get invalid ranges.
An invalid range has the start and/or end index set to -1.
get_last_idx method¶
Get the last index in each range.
get_last_pd_mask method¶
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¶
Get mask from ranges.
See ranges_to_mask_nb.
get_real_duration method¶
Get the real duration of each range in timedelta format.
get_valid method¶
Get valid ranges.
A valid range doesn't have the start and end index set to -1.
id cached_property¶
Mapped array of the field id.
invalid cached_property¶
Ranges.get_invalid with default arguments.
last_idx cacheable_property¶
Ranges.get_last_idx with default arguments.
last_pd_mask cacheable_property¶
Ranges.get_last_pd_mask with default arguments.
max_duration cached_property¶
Ranges.get_max_duration with default arguments.
metrics property¶
Metrics supported by Ranges.
HybridConfig(
start_index=dict(
title='Start Index',
calc_func=<function Ranges.<lambda> at 0x147fa44a0>,
agg_func=None,
tags='wrapper'
),
end_index=dict(
title='End Index',
calc_func=<function Ranges.<lambda> at 0x147fa4540>,
agg_func=None,
tags='wrapper'
),
total_duration=dict(
title='Total Duration',
calc_func=<function Ranges.<lambda> at 0x147fa45e0>,
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 0x147fa4680>,
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 cached_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:boolorDataFrame- Whether to plot OHLC.
plot_close:boolorSeries- 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.Scatterfor Ranges.close. start_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor start values. end_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor end values. open_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor open zones. closed_shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor closed zones. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
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-
Allows an additional option "current_or_{value}", which sets
proj_startto 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-
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_periodplus "proj_period" and "current_or_proj_period". plot_ohlc:boolorDataFrame- Whether to plot OHLC.
plot_close:boolorSeries- 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.Scatterfor Ranges.close. projection_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor projections. lower_trace_kwargs:dict- Keyword arguments passed to
plotly.plotly.graph_objects.Scatterfor lower band. middle_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor middle band. upper_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor upper band. aux_middle_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor auxiliary middle band. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. fig:FigureorFigureWidget- 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:boolorDataFrame- Whether to plot OHLC.
plot_close:boolorSeries- Whether to plot close.
ohlc_type-
Either 'OHLC', 'Candlestick' or Plotly trace.
Pass None to use the default.
ohlc_trace_kwargs:dict- Keyword arguments passed to
ohlc_type. close_trace_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Scatterfor Ranges.close. shape_kwargs:dict- Keyword arguments passed to
plotly.graph_objects.Figure.add_shapefor shapes. add_trace_kwargs:dict- Keyword arguments passed to
add_trace. xref:str- X coordinate axis.
yref:str- Y coordinate axis.
fig:FigureorFigureWidget- Figure to add traces to.
**layout_kwargs- Keyword arguments for layout.
Usage
- 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 class property¶
Defaults for PlotsBuilderMixin.plots.
Merges Records.plots_defaults and plots from ranges.
projections cacheable_property¶
Ranges.get_projections with default arguments.
ranges_pd_mask cacheable_property¶
Ranges.get_ranges_pd_mask with default arguments.
real_duration cacheable_property¶
Ranges.get_real_duration with default arguments.
start_idx cached_property¶
Mapped array of the field start_idx.
stats_defaults class property¶
Defaults for StatsBuilderMixin.stats.
Merges Records.stats_defaults and stats from ranges.
status cached_property¶
Mapped array of the field status.
status_closed cached_property¶
Records filtered by status == 1.
status_open cached_property¶
Records filtered by status == 0.
subplots property¶
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 cached_property¶
Ranges.get_valid with default arguments.
with_delta method¶
Pass self to Ranges.from_delta.