Skip to content

accessors module

Custom pandas accessors for returns data.

Methods can be accessed as follows:

Note

The underlying Series/DataFrame must already be a return series. To convert price to returns, use ReturnsAccessor.from_value().

Grouping is only supported by the methods that accept the group_by argument.

Accessors do not utilize caching.

There are three options to compute returns and get the accessor:

>>> import numpy as np
>>> import pandas as pd
>>> import vectorbt as vbt

>>> price = pd.Series([1.1, 1.2, 1.3, 1.2, 1.1])

>>> # 1. pd.Series.pct_change
>>> rets = price.pct_change()
>>> ret_acc = rets.vbt.returns(freq='d')

>>> # 2. vectorbt.generic.accessors.GenericAccessor.to_returns
>>> rets = price.vbt.to_returns()
>>> ret_acc = rets.vbt.returns(freq='d')

>>> # 3. vectorbt.returns.accessors.ReturnsAccessor.from_value
>>> ret_acc = pd.Series.vbt.returns.from_value(price, freq='d')

>>> # vectorbt.returns.accessors.ReturnsAccessor.total
>>> ret_acc.total()
0.0

The accessors extend vectorbt.generic.accessors.

>>> # inherited from GenericAccessor
>>> ret_acc.max()
0.09090909090909083

Defaults

ReturnsAccessor accepts defaults dictionary where you can pass defaults for arguments used throughout the accessor, such as

  • start_value: The starting value.
  • window: Window length.
  • minp: Minimum number of observations in a window required to have a value.
  • ddof: Delta Degrees of Freedom.
  • risk_free: Constant risk-free return throughout the period.
  • levy_alpha: Scaling relation (Levy stability exponent).
  • required_return: Minimum acceptance return of the investor.
  • cutoff: Decimal representing the percentage cutoff for the bottom percentile of returns.

Stats

>>> ret_acc.stats()
UserWarning: Metric 'benchmark_return' requires benchmark_rets to be set
UserWarning: Metric 'alpha' requires benchmark_rets to be set
UserWarning: Metric 'beta' requires benchmark_rets to be set

Start                                      0
End                                        4
Duration                     5 days 00:00:00
Total Return [%]                           0
Annualized Return [%]                      0
Annualized Volatility [%]            184.643
Sharpe Ratio                        0.691185
Calmar Ratio                               0
Max Drawdown [%]                     15.3846
Omega Ratio                          1.08727
Sortino Ratio                        1.17805
Skew                              0.00151002
Kurtosis                            -5.94737
Tail Ratio                           1.08985
Common Sense Ratio                   1.08985
Value at Risk                     -0.0823718
dtype: object

The missing benchmark_rets can be either passed to the contrustor of the accessor or as a setting to StatsBuilderMixin.stats():

>>> benchmark = pd.Series([1.05, 1.1, 1.15, 1.1, 1.05])
>>> benchmark_rets = benchmark.vbt.to_returns()

>>> ret_acc.stats(settings=dict(benchmark_rets=benchmark_rets))
Start                                      0
End                                        4
Duration                     5 days 00:00:00
Total Return [%]                           0
Benchmark Return [%]                       0
Annualized Return [%]                      0
Annualized Volatility [%]            184.643
Sharpe Ratio                        0.691185
Calmar Ratio                               0
Max Drawdown [%]                     15.3846
Omega Ratio                          1.08727
Sortino Ratio                        1.17805
Skew                              0.00151002
Kurtosis                            -5.94737
Tail Ratio                           1.08985
Common Sense Ratio                   1.08985
Value at Risk                     -0.0823718
Alpha                                0.78789
Beta                                 1.83864
dtype: object

Note

StatsBuilderMixin.stats() does not support grouping.

Plots

This class inherits subplots from GenericAccessor.


ReturnsAccessor class

ReturnsAccessor(
    obj,
    benchmark_rets=None,
    year_freq=None,
    defaults=None,
    **kwargs
)

Accessor on top of return series. For both, Series and DataFrames.

Accessible through pd.Series.vbt.returns and pd.DataFrame.vbt.returns.

Args

obj : pd.Series or pd.DataFrame
Pandas object representing returns.
benchmark_rets : array_like
Pandas object representing benchmark returns.
year_freq : any
Year frequency for annualization purposes.
defaults : dict
Defaults that override returns.defaults in settings.
**kwargs
Keyword arguments that are passed down to GenericAccessor.

Superclasses

Inherited members

Subclasses


alpha method

ReturnsAccessor.alpha(
    benchmark_rets=None,
    risk_free=None,
    wrap_kwargs=None
)

See alpha_nb().


ann_factor property

Get annualization factor.


annual method

ReturnsAccessor.annual(
    **kwargs
)

Annual returns.


annualized method

ReturnsAccessor.annualized(
    wrap_kwargs=None
)

See annualized_return_nb().


annualized_volatility method

ReturnsAccessor.annualized_volatility(
    levy_alpha=None,
    ddof=None,
    wrap_kwargs=None
)

See annualized_volatility_nb().


benchmark_rets property

Benchmark returns.


beta method

ReturnsAccessor.beta(
    benchmark_rets=None,
    wrap_kwargs=None
)

See beta_nb().


calmar_ratio method

ReturnsAccessor.calmar_ratio(
    wrap_kwargs=None
)

See calmar_ratio_nb().


capture method

ReturnsAccessor.capture(
    benchmark_rets=None,
    wrap_kwargs=None
)

See capture_nb().


common_sense_ratio method

ReturnsAccessor.common_sense_ratio(
    wrap_kwargs=None
)

Common Sense Ratio.


cond_value_at_risk method

ReturnsAccessor.cond_value_at_risk(
    cutoff=None,
    wrap_kwargs=None
)

See cond_value_at_risk_nb().


cumulative method

ReturnsAccessor.cumulative(
    start_value=None,
    wrap_kwargs=None
)

See cum_returns_nb().


daily method

ReturnsAccessor.daily(
    **kwargs
)

Daily returns.


defaults property

Defaults for ReturnsAccessor.

Merges returns.defaults from settings with defaults from ReturnsAccessor.


deflated_sharpe_ratio method

ReturnsAccessor.deflated_sharpe_ratio(
    risk_free=None,
    ddof=None,
    var_sharpe=None,
    nb_trials=None,
    bias=True,
    wrap_kwargs=None
)

Deflated Sharpe Ratio (DSR).

Expresses the chance that the advertised strategy has a positive Sharpe ratio.

If var_sharpe is None, is calculated based on all columns. If nb_trials is None, is set to the number of columns.


down_capture method

ReturnsAccessor.down_capture(
    benchmark_rets=None,
    wrap_kwargs=None
)

See down_capture_nb().


downside_risk method

ReturnsAccessor.downside_risk(
    required_return=None,
    wrap_kwargs=None
)

See downside_risk_nb().


drawdown method

ReturnsAccessor.drawdown(
    wrap_kwargs=None
)

Relative decline from a peak.


drawdowns property

ReturnsAccessor.get_drawdowns() with default arguments.


from_value class method

ReturnsAccessor.from_value(
    value,
    init_value=nan,
    broadcast_kwargs=None,
    wrap_kwargs=None,
    **kwargs
)

Returns a new ReturnsAccessor instance with returns calculated from value.


get_drawdowns method

ReturnsAccessor.get_drawdowns(
    wrapper_kwargs=None,
    **kwargs
)

Generate drawdown records of cumulative returns.

See Drawdowns.


indexing_func method

ReturnsAccessor.indexing_func(
    pd_indexing_func,
    **kwargs
)

Perform indexing on ReturnsAccessor.


information_ratio method

ReturnsAccessor.information_ratio(
    benchmark_rets=None,
    ddof=None,
    wrap_kwargs=None
)

See information_ratio_nb().


max_drawdown method

ReturnsAccessor.max_drawdown(
    wrap_kwargs=None
)

See max_drawdown_nb().

Yields the same result as max_drawdown of ReturnsAccessor.drawdowns.


metrics class variable

Metrics supported by ReturnsAccessor.

Config({
    "start": {
        "title": "Start",
        "calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f2e0>",
        "agg_func": null,
        "check_is_not_grouped": false,
        "tags": "wrapper"
    },
    "end": {
        "title": "End",
        "calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f380>",
        "agg_func": null,
        "check_is_not_grouped": false,
        "tags": "wrapper"
    },
    "period": {
        "title": "Period",
        "calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f420>",
        "apply_to_timedelta": true,
        "agg_func": null,
        "check_is_not_grouped": false,
        "tags": "wrapper"
    },
    "total_return": {
        "title": "Total Return [%]",
        "calc_func": "total",
        "post_calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f4c0>",
        "tags": "returns"
    },
    "benchmark_return": {
        "title": "Benchmark Return [%]",
        "calc_func": "benchmark_rets.vbt.returns.total",
        "post_calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f560>",
        "check_has_benchmark_rets": true,
        "tags": "returns"
    },
    "ann_return": {
        "title": "Annualized Return [%]",
        "calc_func": "annualized",
        "post_calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f600>",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "ann_volatility": {
        "title": "Annualized Volatility [%]",
        "calc_func": "annualized_volatility",
        "post_calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f6a0>",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "max_dd": {
        "title": "Max Drawdown [%]",
        "calc_func": "drawdowns.max_drawdown",
        "post_calc_func": "<function ReturnsAccessor.<lambda> at 0x12d42f740>",
        "tags": [
            "returns",
            "drawdowns"
        ]
    },
    "max_dd_duration": {
        "title": "Max Drawdown Duration",
        "calc_func": "drawdowns.max_duration",
        "fill_wrap_kwargs": true,
        "tags": [
            "returns",
            "drawdowns",
            "duration"
        ]
    },
    "sharpe_ratio": {
        "title": "Sharpe Ratio",
        "calc_func": "sharpe_ratio",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "calmar_ratio": {
        "title": "Calmar Ratio",
        "calc_func": "calmar_ratio",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "omega_ratio": {
        "title": "Omega Ratio",
        "calc_func": "omega_ratio",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "sortino_ratio": {
        "title": "Sortino Ratio",
        "calc_func": "sortino_ratio",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "skew": {
        "title": "Skew",
        "calc_func": "obj.skew",
        "tags": "returns"
    },
    "kurtosis": {
        "title": "Kurtosis",
        "calc_func": "obj.kurtosis",
        "tags": "returns"
    },
    "tail_ratio": {
        "title": "Tail Ratio",
        "calc_func": "tail_ratio",
        "tags": "returns"
    },
    "common_sense_ratio": {
        "title": "Common Sense Ratio",
        "calc_func": "common_sense_ratio",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "tags": "returns"
    },
    "value_at_risk": {
        "title": "Value at Risk",
        "calc_func": "value_at_risk",
        "tags": "returns"
    },
    "alpha": {
        "title": "Alpha",
        "calc_func": "alpha",
        "check_has_freq": true,
        "check_has_year_freq": true,
        "check_has_benchmark_rets": true,
        "tags": "returns"
    },
    "beta": {
        "title": "Beta",
        "calc_func": "beta",
        "check_has_benchmark_rets": true,
        "tags": "returns"
    }
})

Returns ReturnsAccessor._metrics, which gets (deep) 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 ReturnsAccessor._metrics.


omega_ratio method

ReturnsAccessor.omega_ratio(
    risk_free=None,
    required_return=None,
    wrap_kwargs=None
)

See omega_ratio_nb().


plots_defaults property

Defaults for PlotsBuilderMixin.plots().

Merges GenericAccessor.plots_defaults, defaults from ReturnsAccessor.defaults (acting as settings), and returns.plots from settings


qs property

Quantstats adapter.


resolve_self method

ReturnsAccessor.resolve_self(
    cond_kwargs=None,
    custom_arg_names=None,
    impacts_caching=True,
    silence_warnings=False
)

Resolve self.

See Wrapping.resolve_self().

Creates a copy of this instance year_freq is different in cond_kwargs.


rolling_alpha method

ReturnsAccessor.rolling_alpha(
    benchmark_rets=None,
    window=None,
    minp=None,
    risk_free=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.alpha().


rolling_annualized method

ReturnsAccessor.rolling_annualized(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.annualized().


rolling_annualized_volatility method

ReturnsAccessor.rolling_annualized_volatility(
    window=None,
    minp=None,
    levy_alpha=None,
    ddof=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.annualized_volatility().


rolling_beta method

ReturnsAccessor.rolling_beta(
    benchmark_rets=None,
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.beta().


rolling_calmar_ratio method

ReturnsAccessor.rolling_calmar_ratio(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.calmar_ratio().


rolling_capture method

ReturnsAccessor.rolling_capture(
    benchmark_rets=None,
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.capture().


rolling_common_sense_ratio method

ReturnsAccessor.rolling_common_sense_ratio(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.common_sense_ratio().


rolling_cond_value_at_risk method

ReturnsAccessor.rolling_cond_value_at_risk(
    window=None,
    minp=None,
    cutoff=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.cond_value_at_risk().


rolling_down_capture method

ReturnsAccessor.rolling_down_capture(
    benchmark_rets=None,
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.down_capture().


rolling_downside_risk method

ReturnsAccessor.rolling_downside_risk(
    window=None,
    minp=None,
    required_return=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.downside_risk().


rolling_information_ratio method

ReturnsAccessor.rolling_information_ratio(
    benchmark_rets=None,
    window=None,
    minp=None,
    ddof=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.information_ratio().


rolling_max_drawdown method

ReturnsAccessor.rolling_max_drawdown(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.max_drawdown().


rolling_omega_ratio method

ReturnsAccessor.rolling_omega_ratio(
    window=None,
    minp=None,
    risk_free=None,
    required_return=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.omega_ratio().


rolling_sharpe_ratio method

ReturnsAccessor.rolling_sharpe_ratio(
    window=None,
    minp=None,
    risk_free=None,
    ddof=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.sharpe_ratio().


rolling_sortino_ratio method

ReturnsAccessor.rolling_sortino_ratio(
    window=None,
    minp=None,
    required_return=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.sortino_ratio().


rolling_tail_ratio method

ReturnsAccessor.rolling_tail_ratio(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.tail_ratio().


rolling_total method

ReturnsAccessor.rolling_total(
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.total().


rolling_up_capture method

ReturnsAccessor.rolling_up_capture(
    benchmark_rets=None,
    window=None,
    minp=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.up_capture().


rolling_value_at_risk method

ReturnsAccessor.rolling_value_at_risk(
    window=None,
    minp=None,
    cutoff=None,
    wrap_kwargs=None
)

Rolling version of ReturnsAccessor.value_at_risk().


sharpe_ratio method

ReturnsAccessor.sharpe_ratio(
    risk_free=None,
    ddof=None,
    wrap_kwargs=None
)

See sharpe_ratio_nb().


sortino_ratio method

ReturnsAccessor.sortino_ratio(
    required_return=None,
    wrap_kwargs=None
)

See sortino_ratio_nb().


stats_defaults property

Defaults for StatsBuilderMixin.stats().

Merges GenericAccessor.stats_defaults, defaults from ReturnsAccessor.defaults (acting as settings), and returns.stats from settings


subplots class variable

Subplots supported by ReturnsAccessor.

Config({
    "plot": {
        "check_is_not_grouped": true,
        "plot_func": "plot",
        "pass_trace_names": false,
        "tags": "generic"
    }
})

Returns ReturnsAccessor._subplots, which gets (deep) 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 ReturnsAccessor._subplots.


tail_ratio method

ReturnsAccessor.tail_ratio(
    wrap_kwargs=None
)

See tail_ratio_nb().


total method

ReturnsAccessor.total(
    wrap_kwargs=None
)

See cum_returns_final_nb().


up_capture method

ReturnsAccessor.up_capture(
    benchmark_rets=None,
    wrap_kwargs=None
)

See up_capture_nb().


value_at_risk method

ReturnsAccessor.value_at_risk(
    cutoff=None,
    wrap_kwargs=None
)

See value_at_risk_nb().


year_freq property

Year frequency for annualization purposes.


ReturnsDFAccessor class

ReturnsDFAccessor(
    obj,
    benchmark_rets=None,
    year_freq=None,
    defaults=None,
    **kwargs
)

Accessor on top of return series. For DataFrames only.

Accessible through pd.DataFrame.vbt.returns.

Superclasses

Inherited members


ReturnsSRAccessor class

ReturnsSRAccessor(
    obj,
    benchmark_rets=None,
    year_freq=None,
    defaults=None,
    **kwargs
)

Accessor on top of return series. For Series only.

Accessible through pd.Series.vbt.returns.

Superclasses

Inherited members


plot_cumulative method

ReturnsSRAccessor.plot_cumulative(
    benchmark_rets=None,
    start_value=1,
    fill_to_benchmark=False,
    main_kwargs=None,
    benchmark_kwargs=None,
    hline_shape_kwargs=None,
    add_trace_kwargs=None,
    xref='x',
    yref='y',
    fig=None,
    **layout_kwargs
)

Plot cumulative returns.

Args

benchmark_rets : array_like
Benchmark return to compare returns against. Will broadcast per element.
start_value : float
The starting returns.
fill_to_benchmark : bool
Whether to fill between main and benchmark, or between main and start_value.
main_kwargs : dict
Keyword arguments passed to GenericAccessor.plot() for main.
benchmark_kwargs : dict
Keyword arguments passed to GenericAccessor.plot() for benchmark.
hline_shape_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Figure.add_shape for start_value line.
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

>>> import pandas as pd
>>> import numpy as np

>>> np.random.seed(0)
>>> rets = pd.Series(np.random.uniform(-0.05, 0.05, size=100))
>>> benchmark_rets = pd.Series(np.random.uniform(-0.05, 0.05, size=100))
>>> rets.vbt.returns.plot_cumulative(benchmark_rets=benchmark_rets)