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

# indexing module

Classes and functions for indexing.

## build_param_indexer function

    build_param_indexer(
        param_names,
        class_name='ParamIndexer',
        module_name=None
    )

A factory to create a class with parameter indexing.

Parameter indexer enables accessing a group of rows and columns by a parameter array (similar to `loc`). This way, one can query index/columns by another Series called a parameter mapper, which is just a `pd.Series` that maps columns (its index) to params (its values).

Parameter indexing is important, since querying by column/index labels alone is not always the best option. For example, `pandas` doesn't let you query by list at a specific index/column level.

Args

`param_names` :`list` of `str`
  Names of the parameters.
`class_name` :`str`
  Name of the generated class.
`module_name` :`str`
  Name of the module to which the class should be bound.

Usage

    >>> from vectorbtpro import *
    >>> from vectorbtpro.base.indexing import build_param_indexer, indexing_on_mapper

    >>> MyParamIndexer = build_param_indexer(['my_param'])
    >>> class C(MyParamIndexer):
    ...     def __init__(self, df, param_mapper):
    ...         self.df = df
    ...         self._my_param_mapper = param_mapper
    ...         super().__init__([param_mapper])
    ...
    ...     def indexing_func(self, pd_indexing_func):
    ...         return type(self)(
    ...             pd_indexing_func(self.df),
    ...             indexing_on_mapper(self._my_param_mapper, self.df, pd_indexing_func)
    ...         )

    >>> df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
    >>> param_mapper = pd.Series(['First', 'Second'], index=['a', 'b'])
    >>> c = C(df, param_mapper)

    >>> c.my_param_loc['First'].df
    0    1
    1    2
    Name: a, dtype: int64

    >>> c.my_param_loc['Second'].df
    0    3
    1    4
    Name: b, dtype: int64

    >>> c.my_param_loc[['First', 'First', 'Second', 'Second']].df
          a     b
    0  1  1  3  3
    1  2  2  4  4

## get_idxs function

    get_idxs(
        idxr,
        index=None,
        columns=None,
        freq=None,
        template_context=None,
        **kwargs
    )

Translate indexer to row and column indices.

If `idxr` is not an indexer class, wraps it with Idxr.

Keyword arguments are passed when constructing a new Idxr.

## get_index_points function

    get_index_points(
        index,
        every=None,
        normalize_every=False,
        at_time=None,
        start=None,
        end=None,
        exact_start=False,
        on=None,
        add_delta=None,
        kind=None,
        indexer_method='bfill',
        indexer_tolerance=None,
        skip_not_found=True
    )

Translate indices or labels into index points.

See PointIdxr for arguments.

Usage

- Provide nothing to generate at the beginning:

    >>> from vectorbtpro import *

    >>> index = pd.date_range("2020-01", "2020-02", freq="1d")

    >>> vbt.get_index_points(index)
    array([0])

- Provide `every` as an integer frequency to generate index points using NumPy:

    >>> # Generate a point every five rows
    >>> vbt.get_index_points(index, every=5)
    array([ 0,  5, 10, 15, 20, 25, 30])

    >>> # Generate a point every five rows starting at 6th row
    >>> vbt.get_index_points(index, every=5, start=5)
    array([ 5, 10, 15, 20, 25, 30])

    >>> # Generate a point every five rows from 6th to 16th row
    >>> vbt.get_index_points(index, every=5, start=5, end=15)
    array([ 5, 10])

- Provide `every` as a time delta frequency to generate index points using Pandas:

    >>> # Generate a point every week
    >>> vbt.get_index_points(index, every="W")
    array([ 4, 11, 18, 25])

    >>> # Generate a point every second day of the week
    >>> vbt.get_index_points(index, every="W", add_delta="2d")
    array([ 6, 13, 20, 27])

    >>> # Generate a point every week, starting at 11th row
    >>> vbt.get_index_points(index, every="W", start=10)
    array([11, 18, 25])

    >>> # Generate a point every week, starting exactly at 11th row
    >>> vbt.get_index_points(index, every="W", start=10, exact_start=True)
    array([10, 11, 18, 25])

    >>> # Generate a point every week, starting at 2020-01-10
    >>> vbt.get_index_points(index, every="W", start="2020-01-10")
    array([11, 18, 25])

- Instead of using `every`, provide indices explicitly:

    >>> # Generate one point
    >>> vbt.get_index_points(index, on="2020-01-07")
    array([6])

    >>> # Generate multiple points
    >>> vbt.get_index_points(index, on=["2020-01-07", "2020-01-14"])
    array([ 6, 13])

## get_index_ranges function

    get_index_ranges(
        index,
        index_freq=None,
        every=None,
        normalize_every=False,
        split_every=True,
        start_time=None,
        end_time=None,
        lookback_period=None,
        start=None,
        end=None,
        exact_start=False,
        fixed_start=False,
        closed_start=True,
        closed_end=False,
        add_start_delta=None,
        add_end_delta=None,
        kind=None,
        skip_not_found=True,
        jitted=None
    )

Translate indices, labels, or bounds into index ranges.

See RangeIdxr for arguments.

Usage

- Provide nothing to generate one largest index range:

    >>> from vectorbtpro import *

    >>> index = pd.date_range("2020-01", "2020-02", freq="1d")

    >>> np.column_stack(vbt.get_index_ranges(index))
    array([[ 0, 32]])

- Provide `every` as an integer frequency to generate index ranges using NumPy:

    >>> # Generate a range every five rows
    >>> np.column_stack(vbt.get_index_ranges(index, every=5))
    array([[ 0,  5],
           [ 5, 10],
           [10, 15],
           [15, 20],
           [20, 25],
           [25, 30]])

    >>> # Generate a range every five rows, starting at 6th row
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every=5,
    ...     start=5
    ... ))
    array([[ 5, 10],
           [10, 15],
           [15, 20],
           [20, 25],
           [25, 30]])

    >>> # Generate a range every five rows from 6th to 16th row
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every=5,
    ...     start=5,
    ...     end=15
    ... ))
    array([[ 5, 10],
           [10, 15]])

- Provide `every` as a time delta frequency to generate index ranges using Pandas:

    >>> # Generate a range every week
    >>> np.column_stack(vbt.get_index_ranges(index, every="W"))
    array([[ 4, 11],
           [11, 18],
           [18, 25]])

    >>> # Generate a range every second day of the week
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     add_start_delta="2d"
    ... ))
    array([[ 6, 11],
           [13, 18],
           [20, 25]])

    >>> # Generate a range every week, starting at 11th row
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     start=10
    ... ))
    array([[11, 18],
           [18, 25]])

    >>> # Generate a range every week, starting exactly at 11th row
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     start=10,
    ...     exact_start=True
    ... ))
    array([[10, 11],
           [11, 18],
           [18, 25]])

    >>> # Generate a range every week, starting at 2020-01-10
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     start="2020-01-10"
    ... ))
    array([[11, 18],
           [18, 25]])

    >>> # Generate a range every week, each starting at 2020-01-10
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     start="2020-01-10",
    ...     fixed_start=True
    ... ))
    array([[11, 18],
           [11, 25]])

    >>> # Generate an expanding range that increments by week
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     start=0,
    ...     exact_start=True,
    ...     fixed_start=True
    ... ))
    array([[ 0,  4],
           [ 0, 11],
           [ 0, 18],
           [ 0, 25]])

- Use a look-back period (instead of an end index):

    >>> # Generate a range every week, looking 5 days back
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     lookback_period=5
    ... ))
    array([[ 6, 11],
           [13, 18],
           [20, 25]])

    >>> # Generate a range every week, looking 2 weeks back
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     every="W",
    ...     lookback_period="2W"
    ... ))
    array([[ 0, 11],
           [ 4, 18],
           [11, 25]])

- Instead of using `every`, provide start and end indices explicitly:

    >>> # Generate one range
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     start="2020-01-01",
    ...     end="2020-01-07"
    ... ))
    array([[0, 6]])

    >>> # Generate ranges between multiple dates
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     start=["2020-01-01", "2020-01-07"],
    ...     end=["2020-01-07", "2020-01-14"]
    ... ))
    array([[ 0,  6],
           [ 6, 13]])

    >>> # Generate ranges with a fixed start
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     start="2020-01-01",
    ...     end=["2020-01-07", "2020-01-14"]
    ... ))
    array([[ 0,  6],
           [ 0, 13]])

- Use `closed_start` and `closed_end` to exclude any of the bounds:

    >>> # Generate ranges between multiple dates
    >>> # by excluding the start date and including the end date
    >>> np.column_stack(vbt.get_index_ranges(
    ...     index,
    ...     start=["2020-01-01", "2020-01-07"],
    ...     end=["2020-01-07", "2020-01-14"],
    ...     closed_start=False,
    ...     closed_end=True
    ... ))
    array([[ 1,  7],
           [ 7, 14]])

## indexing_on_mapper function

    indexing_on_mapper(
        mapper,
        ref_obj,
        pd_indexing_func
    )

Broadcast `mapper` Series to `ref_obj` and perform pandas indexing using `pd_indexing_func`.

## normalize_idxs function

    normalize_idxs(
        idxs,
        target_len
    )

Normalize indexes into a 1-dim integer array.

## AutoIdxr class

    AutoIdxr(
        *args,
        **kwargs
    )

Class for resolving indices, datetime-like objects, frequency-like objects, and labels for one axis.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### closed_end class variable

Whether slice end should be inclusive.

### closed_start class variable

Whether slice start should be inclusive.

### idxr_kwargs class variable

Keyword arguments passed to the selected indexer.

### indexer_method class variable

Method for `pd.Index.get_indexer`.

### kind class variable

Kind of value.

Allowed are

- "position(s)" for PosIdxr
- "mask" for MaskIdxr
- "label(s)" for LabelIdxr
- "datetime" for DatetimeIdxr
- "dtc": for DTCIdxr
- "frequency" for PointIdxr

If None, will (try to) determine automatically based on the type of indices.

### level class variable

One or more levels.

If `level` is not None and `kind` is None, `kind` becomes "labels".

### value class variable

One or more integer indices, datetime-like objects, frequency-like objects, or labels.

Can also be an instance of PosSel holding position(s) and LabelSel holding label(s).

## ColIdxr class

    ColIdxr(
        idxr,
        **idxr_kwargs
    )

Class for resolving column indices.

Superclasses

- IdxrBase

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.get()
- IdxrBase.slice_indexer()

### idxr class variable

Indexer.

Can be an instance of UniIdxr, a custom template, or a value to be wrapped with AutoIdxr.

### idxr_kwargs class variable

Keyword arguments passed to AutoIdxr.

## DTCIdxr class

    DTCIdxr(
        value,
        parse_kwargs=None,
        closed_start=True,
        closed_end=False,
        jitted=None
    )

Class for resolving indices provided as datetime-like components.

Method generated by attrs for class DTCIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### closed_end class variable

Whether slice end should be inclusive.

### closed_start class variable

Whether slice start should be inclusive.

### get_dtc_namedtuple static method

    DTCIdxr.get_dtc_namedtuple(
        value=None,
        **parse_kwargs
    )

Convert a value to a DTCNT instance.

### jitted class variable

Jitting option passed to index_matches_dtc_nb() and index_within_dtc_range_nb().

### parse_kwargs class variable

Keyword arguments passed to DTC.parse().

### value class variable

One or more datetime-like components.

## DatetimeIdxr class

    DatetimeIdxr(
        value,
        closed_end=False,
        indexer_method='bfill'
    )

Class for resolving indices provided as datetime-like objects.

Method generated by attrs for class DatetimeIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### closed_end class variable

Whether slice end should be inclusive.

### indexer_method class variable

Method for `pd.Index.get_indexer`.

### value class variable

One or more datetime-like objects.

## ExtPandasIndexer class

    ExtPandasIndexer(
        **kwargs
    )

Extension of PandasIndexer that also implements indexing using xLoc.

Superclasses

- IndexingBase
- PandasIndexer

Inherited members

- IndexingBase.indexing_func()
- IndexingBase.indexing_setter_func()
- PandasIndexer.iloc
- PandasIndexer.indexing_kwargs
- PandasIndexer.loc
- PandasIndexer.xs()

Subclasses

- ArrayWrapper
- Wrapping

### xloc property

Subclass of iLoc that transforms an Idxr-based operation with get_idxs() to an iLoc operation.

## IdxDict class

    IdxDict(
        index_dct
    )

Class for building an index setter from a dict.

Method generated by attrs for class IdxDict.

Superclasses

- IdxSetterFactory

Inherited members

- IdxSetterFactory.get()

### index_dct class variable

Dict that contains indexer objects as keys and values to be set as values.

## IdxFrame class

    IdxFrame(
        df,
        split=False,
        rowidx_kwargs=None,
        colidx_kwargs=None
    )

Class for building an index setter from a DataFrame.

Method generated by attrs for class IdxFrame.

Superclasses

- IdxSetterFactory

Inherited members

- IdxSetterFactory.get()

### colidx_kwargs class variable

Keyword arguments passed to `colidx` if the indexer isn't an instance of ColIdxr.

### df class variable

DataFrame or any array-like object to create the DataFrame from.

### rowidx_kwargs class variable

Keyword arguments passed to `rowidx` if the indexer isn't an instance of RowIdxr.

### split class variable

Whether to split the setting operation.

If False, will set all values using a single operation. Otherwise, the following options are supported:

- 'columns': one operation per column
- 'rows': one operation per row
- True or 'elements': one operation per element

## IdxRecords class

    IdxRecords(
        records,
        row_field=None,
        col_field=None,
        rowidx_kwargs=None,
        colidx_kwargs=None
    )

Class for building index setters from records - one per field.

Method generated by attrs for class IdxRecords.

Superclasses

- IdxSetterFactory

Inherited members

- IdxSetterFactory.get()

### col_field class variable

Column field.

If None or True, will search for "col", "column", and "symbol" (case-insensitive).

If a record doesn't have a column field, all columns will be set. If there's no row and column field, the field value will become the default of the entire array.

### colidx_kwargs class variable

Keyword arguments passed to `colidx` if the indexer isn't an instance of ColIdxr.

### records class variable

Series, DataFrame, or any sequence of mapping-like objects.

If a Series or DataFrame and the index is not a default range, the index will become a row field. If a custom row field is provided, the index will be ignored.

### row_field class variable

Row field.

If None or True, will search for "row", "index", "open time", and "date" (case-insensitive). If IdxRecords.records is a Series or DataFrame, will also include the index name if the index is not a default range.

If a record doesn't have a row field, all rows will be set. If there's no row and column field, the field value will become the default of the entire array.

### rowidx_kwargs class variable

Keyword arguments passed to `rowidx` if the indexer isn't an instance of RowIdxr.

## IdxSeries class

    IdxSeries(
        sr,
        split=False,
        idx_kwargs=None
    )

Class for building an index setter from a Series.

Method generated by attrs for class IdxSeries.

Superclasses

- IdxSetterFactory

Inherited members

- IdxSetterFactory.get()

### idx_kwargs class variable

Keyword arguments passed to `idx` if the indexer isn't an instance of Idxr.

### split class variable

Whether to split the setting operation.

If False, will set all values using a single operation. Otherwise, will do one operation per element.

### sr class variable

Series or any array-like object to create the Series from.

## IdxSetter class

    IdxSetter(
        idx_items
    )

Class for setting values based on indexing.

Method generated by attrs for class IdxSetter.

### fill_and_set method

    IdxSetter.fill_and_set(
        shape,
        keep_flex=False,
        fill_value=nan,
        **kwargs
    )

Fill a new array and set its values based on IdxSetter.get_set_meta().

If `keep_flex` is True, will return the most memory-efficient array representation capable of flexible indexing.

If `fill_value` is None, will search for the `_def` key in IdxSetter.idx_items. If there's none, will be set to NaN.

### get_set_meta method

    IdxSetter.get_set_meta(
        shape,
        index=None,
        columns=None,
        freq=None,
        template_context=None
    )

Get meta of setting operations in IdxSetter.idx_items.

### idx_items class variable

Items where the first element is an indexer and the second element is a value to be set.

### set method

    IdxSetter.set(
        arr,
        set_funcs=None,
        **kwargs
    )

Set values of a NumPy array based on IdxSetter.get_set_meta().

### set_col_idxs class method

    IdxSetter.set_col_idxs(
        arr,
        idxs,
        v
    )

Set column indices in an array.

### set_pd method

    IdxSetter.set_pd(
        pd_arr,
        **kwargs
    )

Set values of a Pandas array based on IdxSetter.get_set_meta().

### set_row_and_col_idxs class method

    IdxSetter.set_row_and_col_idxs(
        arr,
        row_idxs,
        col_idxs,
        v
    )

Set row and column indices in an array.

### set_row_idxs class method

    IdxSetter.set_row_idxs(
        arr,
        idxs,
        v
    )

Set row indices in an array.

## IdxSetterFactory class

    IdxSetterFactory()

Class for building index setters.

Subclasses

- IdxDict
- IdxFrame
- IdxRecords
- IdxSeries

### get method

    IdxSetterFactory.get()

Get an instance of IdxSetter or a dict of such instances - one per array name.

## Idxr class

    Idxr(
        *idxrs,
        **idxr_kwargs
    )

Class for resolving indices.

Superclasses

- IdxrBase

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.get()
- IdxrBase.slice_indexer()

### idxr_kwargs class variable

Keyword arguments passed to RowIdxr and ColIdxr.

### idxrs class variable

A tuple of one or more indexers.

If one indexer is provided, can be an instance of RowIdxr or ColIdxr, a custom template, or a value to wrapped with RowIdxr.

If two indexers are provided, can be an instance of RowIdxr and ColIdxr respectively, or a value to wrapped with RowIdxr and ColIdxr respectively.

## IdxrBase class

    IdxrBase()

Abstract class for resolving indices.

Subclasses

- ColIdxr
- Idxr
- RowIdxr
- UniIdxr

### check_idxs method

    IdxrBase.check_idxs(
        idxs,
        check_minus_one=False
    )

Check indices after resolving them.

### get method

    IdxrBase.get(
        *args,
        **kwargs
    )

Get indices.

### slice_indexer method

    IdxrBase.slice_indexer(
        index,
        slice_,
        closed_end=False
    )

Compute the slice indexer for input labels and step.

## IndexingBase class

    IndexingBase()

Class that supports indexing through IndexingBase.indexing_func().

Subclasses

- PandasIndexer
- `vectorbtpro.indicators.custom.adx.ParamIndexer`
- `vectorbtpro.indicators.custom.atr.ParamIndexer`
- `vectorbtpro.indicators.custom.bbands.ParamIndexer`
- `vectorbtpro.indicators.custom.ma.ParamIndexer`
- `vectorbtpro.indicators.custom.macd.ParamIndexer`
- `vectorbtpro.indicators.custom.msd.ParamIndexer`
- `vectorbtpro.indicators.custom.obv.ParamIndexer`
- `vectorbtpro.indicators.custom.ols.ParamIndexer`
- `vectorbtpro.indicators.custom.patsim.ParamIndexer`
- `vectorbtpro.indicators.custom.pivotinfo.ParamIndexer`
- `vectorbtpro.indicators.custom.rsi.ParamIndexer`
- `vectorbtpro.indicators.custom.sigdet.ParamIndexer`
- `vectorbtpro.indicators.custom.stoch.ParamIndexer`
- `vectorbtpro.indicators.custom.supertrend.ParamIndexer`
- `vectorbtpro.indicators.custom.vwap.ParamIndexer`
- `vectorbtpro.labels.generators.bolb.ParamIndexer`
- `vectorbtpro.labels.generators.fixlb.ParamIndexer`
- `vectorbtpro.labels.generators.fmax.ParamIndexer`
- `vectorbtpro.labels.generators.fmean.ParamIndexer`
- `vectorbtpro.labels.generators.fmin.ParamIndexer`
- `vectorbtpro.labels.generators.fstd.ParamIndexer`
- `vectorbtpro.labels.generators.meanlb.ParamIndexer`
- `vectorbtpro.labels.generators.pivotlb.ParamIndexer`
- `vectorbtpro.labels.generators.trendlb.ParamIndexer`
- `vectorbtpro.signals.generators.ohlcstx.ParamIndexer`
- `vectorbtpro.signals.generators.ohlcstx.ParamIndexer`
- `vectorbtpro.signals.generators.rand.ParamIndexer`
- `vectorbtpro.signals.generators.randnx.ParamIndexer`
- `vectorbtpro.signals.generators.randx.ParamIndexer`
- `vectorbtpro.signals.generators.rprob.ParamIndexer`
- `vectorbtpro.signals.generators.rprobnx.ParamIndexer`
- `vectorbtpro.signals.generators.rprobx.ParamIndexer`
- `vectorbtpro.signals.generators.rprobx.ParamIndexer`
- `vectorbtpro.signals.generators.stx.ParamIndexer`
- `vectorbtpro.signals.generators.stx.ParamIndexer`

### indexing_func method

    IndexingBase.indexing_func(
        pd_indexing_func,
        **kwargs
    )

Apply `pd_indexing_func` on all pandas objects in question and return a new instance of the class.

Should be overridden.

### indexing_setter_func method

    IndexingBase.indexing_setter_func(
        pd_indexing_setter_func,
        **kwargs
    )

Apply `pd_indexing_setter_func` on all pandas objects in question.

Should be overridden.

## IndexingError class

    IndexingError(
        *args,
        **kwargs
    )

Exception raised when an indexing error has occurred.

Superclasses

- `builtins.BaseException`
- `builtins.Exception`

## LabelIdxr class

    LabelIdxr(
        value,
        closed_end=True,
        level=None
    )

Class for resolving indices provided as labels.

Method generated by attrs for class LabelIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### closed_end class variable

Whether slice end should be inclusive.

### level class variable

One or more levels.

### value class variable

One or more labels.

## Loc class

    Loc(
        indexing_func,
        indexing_setter_func=None,
        **kwargs
    )

Forwards `pd.Series.loc`/`pd.DataFrame.loc` operation to each Series/DataFrame and returns a new class instance.

Superclasses

- LocBase
- pdLoc

Inherited members

- pdLoc.indexing_func
- pdLoc.indexing_kwargs
- pdLoc.indexing_setter_func
- pdLoc.pd_indexing_func()
- pdLoc.pd_indexing_setter_func()

## LocBase class

    LocBase(
        indexing_func,
        indexing_setter_func=None,
        **kwargs
    )

Class that implements location-based indexing.

Subclasses

- ParamLoc
- pdLoc

### indexing_func property

Indexing function.

### indexing_kwargs property

Keyword arguments passed to LocBase.indexing_func.

### indexing_setter_func property

Indexing setter function.

## MaskIdxr class

    MaskIdxr(
        value
    )

Class for resolving indices provided as a mask.

Method generated by attrs for class MaskIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### value class variable

Mask.

## PandasIndexer class

    PandasIndexer(
        **kwargs
    )

Implements indexing using `iloc`, `loc`, `xs` and `__getitem__`.

Usage

    >>> from vectorbtpro import *
    >>> from vectorbtpro.base.indexing import PandasIndexer

    >>> class C(PandasIndexer):
    ...     def __init__(self, df1, df2):
    ...         self.df1 = df1
    ...         self.df2 = df2
    ...         super().__init__()
    ...
    ...     def indexing_func(self, pd_indexing_func):
    ...         return type(self)(
    ...             pd_indexing_func(self.df1),
    ...             pd_indexing_func(self.df2)
    ...         )

    >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
    >>> df2 = pd.DataFrame({'a': [5, 6], 'b': [7, 8]})
    >>> c = C(df1, df2)

    >>> c.iloc[:, 0]
    <__main__.C object at 0x1a1cacbbe0>

    >>> c.iloc[:, 0].df1
    0    1
    1    2
    Name: a, dtype: int64

    >>> c.iloc[:, 0].df2
    0    5
    1    6
    Name: a, dtype: int64

Superclasses

- IndexingBase

Inherited members

- IndexingBase.indexing_func()
- IndexingBase.indexing_setter_func()

Subclasses

- ExtPandasIndexer

### iloc property

Forwards `pd.Series.iloc`/`pd.DataFrame.iloc` operation to each Series/DataFrame and returns a new class instance.

### indexing_kwargs property

Indexing keyword arguments.

### loc property

Forwards `pd.Series.loc`/`pd.DataFrame.loc` operation to each Series/DataFrame and returns a new class instance.

### xs method

    PandasIndexer.xs(
        *args,
        **kwargs
    )

Forwards `pd.Series.xs`/`pd.DataFrame.xs` operation to each Series/DataFrame and returns a new class instance.

## ParamLoc class

    ParamLoc(
        mapper,
        indexing_func,
        indexing_setter_func=None,
        level_name=None,
        **kwargs
    )

Access a group of columns by parameter using `pd.Series.loc`.

Uses `mapper` to establish link between columns and parameter values.

Superclasses

- LocBase

Inherited members

- LocBase.indexing_func
- LocBase.indexing_kwargs
- LocBase.indexing_setter_func

### get_idxs method

    ParamLoc.get_idxs(
        key
    )

Get array of indices affected by this key.

### level_name property

Level name.

### mapper property

Mapper.

## PointIdxr class

    PointIdxr(
        every=None,
        normalize_every=False,
        at_time=None,
        start=None,
        end=None,
        exact_start=False,
        on=None,
        add_delta=None,
        kind=None,
        indexer_method='bfill',
        indexer_tolerance=None,
        skip_not_found=True
    )

Class for resolving index points.

Method generated by attrs for class PointIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### add_delta class variable

Offset to be added to each in `on`.

If string, gets converted into an offset using to_offset.

### at_time class variable

Time of the day either as a (human-readable) string or `datetime.time`.

Every datetime in `on` gets floored to the daily frequency, while `at_time` gets converted into a timedelta using time_to_timedelta() and added to `add_delta`. Index must be datetime-like.

### end class variable

End index/date.

If (human-readable) string, gets converted into a datetime.

If `every` is None, gets used to filter the final index array.

### every class variable

Frequency either as an integer or timedelta.

Gets translated into `on` array by creating a range. If integer, an index sequence from `start` to `end` (exclusive) is created and 'indices' as `kind` is used. If timedelta-like, a date sequence from `start` to `end` (inclusive) is created and 'labels' as `kind` is used.

If `at_time` is not None and `every` and `on` are None, `every` defaults to one day.

### exact_start class variable

Whether the first index should be exactly `start`.

Depending on `every`, the first index picked by `pd.date_range` may happen after `start`. In such a case, `start` gets injected before the first index generated by `pd.date_range`.

### indexer_method class variable

Method for `pd.Index.get_indexer`.

Allows two additional values "before" and "after".

### indexer_tolerance class variable

Tolerance for `pd.Index.get_indexer`.

If `at_time` is set and `indexer_method` is neither exact nor nearest, `indexer_tolerance` becomes such that the next element must be within the current day.

### kind class variable

Kind of data in `on`: indices or labels.

If None, gets assigned to `indices` if `on` contains integer data, otherwise to `labels`.

If `kind` is 'labels', `on` gets converted into indices using `pd.Index.get_indexer`. Prior to this, gets its timezone aligned to the timezone of the index. If `kind` is 'indices', `on` gets wrapped with NumPy.

### normalize_every class variable

Normalize start/end dates to midnight before generating date range.

### on class variable

Index/label or a sequence of such.

Gets converted into datetime format whenever possible.

### skip_not_found class variable

Whether to drop indices that are -1 (not found).

### start class variable

Start index/date.

If (human-readable) string, gets converted into a datetime.

If `every` is None, gets used to filter the final index array.

## PosIdxr class

    PosIdxr(
        value
    )

Class for resolving indices provided as integer positions.

Method generated by attrs for class PosIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### value class variable

One or more integer positions.

## RangeIdxr class

    RangeIdxr(
        every=None,
        normalize_every=False,
        split_every=True,
        start_time=None,
        end_time=None,
        lookback_period=None,
        start=None,
        end=None,
        exact_start=False,
        fixed_start=False,
        closed_start=True,
        closed_end=False,
        add_start_delta=None,
        add_end_delta=None,
        kind=None,
        skip_not_found=True,
        jitted=None
    )

Class for resolving index ranges.

Method generated by attrs for class RangeIdxr.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### add_end_delta class variable

Offset to be added to each in `end`.

If string, gets converted into an offset using to_offset.

### add_start_delta class variable

Offset to be added to each in `start`.

If string, gets converted into an offset using to_offset.

### closed_end class variable

Whether `end` should be inclusive.

### closed_start class variable

Whether `start` should be inclusive.

### end class variable

End index/label or a sequence of such.

Gets converted into datetime format whenever possible.

Gets broadcasted together with `start`.

### end_time class variable

End time of the day either as a (human-readable) string or `datetime.time`.

Every datetime in `end` gets floored to the daily frequency, while `end_time` gets converted into a timedelta using time_to_timedelta() and added to `add_end_delta`. Index must be datetime-like.

### every class variable

Frequency either as an integer or timedelta.

Gets translated into `start` and `end` arrays by creating a range. If integer, an index sequence from `start` to `end` (exclusive) is created and 'indices' as `kind` is used. If timedelta-like, a date sequence from `start` to `end` (inclusive) is created and 'bounds' as `kind` is used.

If `start_time` and `end_time` are not None and `every`, `start`, and `end` are None, `every` defaults to one day.

### exact_start class variable

Whether the first index in the `start` array should be exactly `start`.

Depending on `every`, the first index picked by `pd.date_range` may happen after `start`. In such a case, `start` gets injected before the first index generated by `pd.date_range`.

Cannot be used together with `lookback_period`.

### fixed_start class variable

Whether all indices in the `start` array should be exactly `start`.

Works only together with `every`.

Cannot be used together with `lookback_period`.

### jitted class variable

Jitting option passed to Resampler.map_bounds_to_source_ranges().

### kind class variable

Kind of data in `on`: indices, labels or bounds.

If None, gets assigned to `indices` if `start` and `end` contain integer data, to `bounds` if `start`, `end`, and index are datetime-like, otherwise to `labels`.

If `kind` is 'labels', `start` and `end` get converted into indices using `pd.Index.get_indexer`. Prior to this, get their timezone aligned to the timezone of the index. If `kind` is 'indices', `start` and `end` get wrapped with NumPy. If kind` is 'bounds', Resampler.map_bounds_to_source_ranges() is used.

### lookback_period class variable

Lookback period either as an integer or offset.

If `lookback_period` is set, `start` becomes `end-lookback_period`. If `every` is not None, the sequence is generated from `start+lookback_period` to `end` and then assigned to `end`.

If string, gets converted into an offset using to_offset. If integer, gets multiplied by the frequency of the index if the index is not integer.

### normalize_every class variable

Normalize start/end dates to midnight before generating date range.

### skip_not_found class variable

Whether to drop indices that are -1 (not found).

### split_every class variable

Whether to split the sequence generated using `every` into `start` and `end` arrays.

After creation, and if `split_every` is True, an index range is created from each pair of elements in the generated sequence. Otherwise, the entire sequence is assigned to `start` and `end`, and only time and delta instructions can be used to further differentiate between them.

Forced to False if `every`, `start_time`, and `end_time` are not None and `fixed_start` is False.

### start class variable

Start index/label or a sequence of such.

Gets converted into datetime format whenever possible.

Gets broadcasted together with `end`.

### start_time class variable

Start time of the day either as a (human-readable) string or `datetime.time`.

Every datetime in `start` gets floored to the daily frequency, while `start_time` gets converted into a timedelta using time_to_timedelta() and added to `add_start_delta`. Index must be datetime-like.

## RowIdxr class

    RowIdxr(
        idxr,
        **idxr_kwargs
    )

Class for resolving row indices.

Superclasses

- IdxrBase

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.get()
- IdxrBase.slice_indexer()

### idxr class variable

Indexer.

Can be an instance of UniIdxr, a custom template, or a value to be wrapped with AutoIdxr.

### idxr_kwargs class variable

Keyword arguments passed to AutoIdxr.

## UniIdxr class

    UniIdxr()

Abstract class for resolving indices based on a single index.

Superclasses

- IdxrBase

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.get()
- IdxrBase.slice_indexer()

Subclasses

- AutoIdxr
- DTCIdxr
- DatetimeIdxr
- LabelIdxr
- MaskIdxr
- PointIdxr
- PosIdxr
- RangeIdxr
- UniIdxrOp

## UniIdxrOp class

    UniIdxrOp(
        op_func,
        *idxrs
    )

Class for applying an operation to one or more indexers.

Produces a single set of indices.

Superclasses

- IdxrBase
- UniIdxr

Inherited members

- IdxrBase.check_idxs()
- IdxrBase.slice_indexer()
- UniIdxr.get()

### idxrs class variable

A tuple of one or more indexers.

### op_func class variable

Operation function that takes the indices of each indexer (as `*args`), `index` (keyword argument), and `freq` (keyword argument), and returns new indices.

## hslice class

    hslice(
        start=vectorbtpro.base.indexing._DEF,
        stop=vectorbtpro.base.indexing._DEF,
        step=vectorbtpro.base.indexing._DEF
    )

Hashable slice.

### from_slice class method

    hslice.from_slice(
        slice_
    )

Construct from a slice.

### start class variable

Start.

### step class variable

Step.

### stop class variable

Stop.

### to_slice method

    hslice.to_slice()

Convert to a slice.

## iLoc class

    iLoc(
        indexing_func,
        indexing_setter_func=None,
        **kwargs
    )

Forwards `pd.Series.iloc`/`pd.DataFrame.iloc` operation to each Series/DataFrame and returns a new class instance.

Superclasses

- LocBase
- pdLoc

Inherited members

- pdLoc.indexing_func
- pdLoc.indexing_kwargs
- pdLoc.indexing_setter_func
- pdLoc.pd_indexing_func()
- pdLoc.pd_indexing_setter_func()

Subclasses

- xLoc

## index_dict class

    index_dict(
        *args,
        **kwargs
    )

Dict that contains indexer objects as keys and values to be set as values.

Each indexer object must be hashable. To make a slice hashable, use hslice. To make an array hashable, convert it into a tuple.

To set a default value, use the `_def` key (case-sensitive!).

Superclasses

- Comparable
- Pickleable
- Prettified
- `builtins.dict`
- pdict

Inherited members

- 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()
- pdict.equals()
- pdict.load_update()
- pdict.prettify()
- pdict.rec_state

## pdLoc class

    pdLoc(
        indexing_func,
        indexing_setter_func=None,
        **kwargs
    )

Forwards a Pandas-like indexing operation to each Series/DataFrame and returns a new class instance.

Superclasses

- LocBase

Inherited members

- LocBase.indexing_func
- LocBase.indexing_kwargs
- LocBase.indexing_setter_func

Subclasses

- Loc
- iLoc

### pd_indexing_func class method

    pdLoc.pd_indexing_func(
        obj,
        key
    )

Pandas-like indexing operation.

### pd_indexing_setter_func class method

    pdLoc.pd_indexing_setter_func(
        obj,
        key,
        value
    )

Pandas-like indexing setter operation.

## xLoc class

    xLoc(
        indexing_func,
        indexing_setter_func=None,
        **kwargs
    )

Subclass of iLoc that transforms an Idxr-based operation with get_idxs() to an iLoc operation.

Superclasses

- LocBase
- iLoc
- pdLoc

Inherited members

- iLoc.indexing_func
- iLoc.indexing_kwargs
- iLoc.indexing_setter_func
- iLoc.pd_indexing_func()
- iLoc.pd_indexing_setter_func()

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