Skip to main content

BaseStatArb

BaseStatArb()
Base Statistical Arbitrage class.

Ancestors

  • abc.ABC

Descendants

  • systematica.api.models.arbitrage_index.ArbitrageBaseIndex
  • systematica.api.models.arbitrage_index.ArbitrageClipIndex
  • systematica.api.models.arbitrage_index.ArbitrageCumulativeIndex
  • systematica.api.models.arbitrage_index.ArbitrageResetIndex
  • systematica.api.models.arbitrage_index.ArbitrageRollingZscoreIndex
  • systematica.api.models.meta_model.MetaModel
  • systematica.api.models.momentum.AverageMomentumFactorCV
  • systematica.api.models.momentum.RollingAverageMomentumFactor
  • systematica.api.models.ou_process.RollingOUProcess
  • systematica.api.models.range_breakout.RangeBreakout
  • systematica.api.models.range_breakout.RangeMeanReversion
  • systematica.api.models.volatility.RollingVolatilityFactor
  • systematica.api.models.volatility.VolatilityFactorCV
  • systematica.api.models.volume_profile.RollingVolumeProfileFactor
  • systematica.api.models.volume_profile.VolumeProfileFactorCV

Static methods

is_valid

is_valid(
    model_params: Dict[str, Any],
    signal_params: Dict[str, Any],
)
Validate model parameters. This method checks if the model parameters are valid for the statistical arbitrage model. It should be implemented in subclasses and decorated with staticmethod to allow calling it without an instance. If the model does not require validation, it can be implemented as a no-op method with the @staticmethod decorator. Examples: To implement this method, define it in the subclass and use the @staticmethod decorator like so:
>>> @staticmethod
>>> def is_valid(model_params: tp.Kwargs, signal_params: tp.Kwargs):
...     # Implement validation logic here
...     pass
Parameters:
NameTypeDefaultDescription
model_paramstp.Kwargs--Model parameters.
signal_paramstp.Kwargs--Signal parameters.

run_report

run_report(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    use_close: bool = True,
    freq: str = 'auto',
    use_rolling: bool = False,
    **model_params,
) ‑> systematica.api.base.BaseReportMixin
Analyzes model using rolling or cross-validation techniques. Parameters:
NameTypeDefaultDescription
datavbt.Data--Input data containing time series data.
s1str--First symbol.
s2str--Second symbol.
use_closeboolTrueWhether to use closing prices (True) or opening prices (False).
freqstrautoFrequency of the index used in BaseReportCV. If auto, try infer frequency from the index. Ignored in BaseRollingReport. Defaults to auto.
use_rollingboolFalseFlag to use rolling method via BaseRollingReport. Note that both rolling and cv models can be passed. Fallbacks to BaseReportCV if model is not using from_rolling splitter without error message. Defaults to False.
model_paramstp.Kwargs--Parameters to pass to the model constructor.
Returns:
TypeDescription
BaseReportMixinAn instance of BaseRollingReport or BaseReportCV depending on the model and parameters.

get_report_metrics

get_report_metrics(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    use_close: bool = True,
    metrics: str | List[str= 'sharpe_ratio',
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    to_numpy: bool = False,
    validate_metrics: bool = True,
    validate_model: bool = True,
    use_rolling: bool = False,
    freq: str = 'auto',
    portfolio_kwargs: Dict[str, Any] = None,
    **model_params,
) ‑> pandas.core.frame.DataFrame | numpy.ndarray
Run report: Analyzes model using rolling or cross-validation techniques. Parameters:
NameTypeDefaultDescription
datavbt.Data--Input data containing time series data.
s1str--First symbol.
s2str--Second symbol.
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
use_closebool, optional--Whether to use ‘Close’ prices if True or ‘Open’ prices if False. Default to True`.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
to_numpyboolFalseIf True, returns a np.ndarray. Default is False, returning a pd.DataFrame.
validate_metricsboolTrueCheck if metric is valid in the registry. Defaults to True.
validate_modelboolTrueCheck if model parameters are valid. Defaults to True.
use_rollingboolFalseFlag to use rolling method via BaseRollingReport. Note that both rolling and cv models can be passed. Fallbacks to BaseReportCV if model is not using from_rolling splitter without error message. Defaults to False.
freqstrautoFrequency of the index used in BaseReportCV. If auto, try infer frequency from the index. Ignored in BaseRollingReport. Defaults to auto.
portfolio_kwargstp.KwargsNoneAdditional arguments for portfolio simulation.
model_paramstp.Kwargs--Parameters to pass to the model constructor.
Returns:
TypeDescription
pd.DataFrame | tp.ArrayDataFrame or array containing portfolio performance metrics.

run_analyzer

run_analyzer(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    use_close: bool = True,
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    portfolio_kwargs: Dict[str, Any] = None,
    validate_model: bool = True,
    **model_params,
) ‑> systematica.portfolio.analyzers.base.PortfolioAnalyzer
Executes the portfolio analyzer.
Combines scoring, signal generation, and portfolio simulation into a single pipeline for streamlined backtesting.
Parameters:
NameTypeDefaultDescription
datavbt.Data--Input vbt.Data containing time series data.
s1str--Symbol.
s2str--Symbol.
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
portfolio_kwargstp.KwargsNoneAdditional arguments for portfolio simulation.
to_numpyboolFalseIf True, returns a np.ndarray. Default is False, returning a pd.DataFrame.
validate_modelboolTrueCheck if model parameters are valid. Defaults to True.
model_paramstp.Kwargs--Additional parameters for model_func.
Returns:
TypeDescription
PortfolioAnalyzerAn instance of PortfolioAnalyzer containing the results of the backtest.

run_model

run_model(
    cls,
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    use_close: bool = True,
    **model_params,
) ‑> pandas.core.frame.DataFrame
Run parameterized scores generation.
The method utilizes parameterization to run scores over various parameter combinations. The results can be merged and accessed as a single output object.
Parameters:
NameTypeDefaultDescription
datavbt.Data--Input vbt.Data containing time series data.
s1str--First symbol.
s2str--Second symbol.
use_closeboolTrueUse close price if True, otherwise use open price.
model_paramstp.Kwargs--Model arguments.
Returns:
TypeDescription
pd.DataFrameScores for each parameter combination.

run_signals

run_signals(
    cls,
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int = None,
    use_close: bool = True,
    validate_model: bool = True,
    **model_params,
) ‑> pandas.core.frame.DataFrame
Run parametrized signals generation.
The method utilizes parameterization to run signal generation over various parameter combinations. The results can be merged and accessed as a single output object.
Parameters:
NameTypeDefaultDescription
datavbt.Data--Input vbt.Data containing time series data.
s1str--Symbol.
s2str--Symbol.
signal_modelstr--Model or parameter for generating trading signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
use_closeboolTrueUse close price if True, otherwise use open price.
validate_modelboolTrueValidate model parameters. Defaults to True.
model_paramstp.Kwargs--Model arguments.
Returns:
TypeDescription
pd.DataFrameSignals for each parameter combination.

run_pipeline

run_pipeline(
    cls,
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    metrics: str | List[str= None,
    use_rolling: bool = False,
    metric_registry_kwargs: Dict[str, Any] = None,
    use_close: bool = True,
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    portfolio_kwargs: Dict[str, Any] = None,
    to_numpy: bool = False,
    validate_metrics: bool = True,
    validate_model: bool = True,
    **model_params,
) ‑> vectorbtpro.portfolio.base.Portfolio | collections.OrderedDict | pandas.core.frame.DataFrame | numpy.ndarray
Executes the portfolio pipeline. Method is parametrizable.
Combines scoring, signal generation, and portfolio simulation into a single pipeline for streamlined backtesting.
Parameters:
NameTypeDefaultDescription
datavbt.Data--Input vbt.Data containing time series data.
s1str--First symbol.
s2str--Second symbol.
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
use_rollingboolFalseFlag to use rolling method via BaseRollingReport. Note that both rolling and cv models can be passed. Fallbacks to BaseReportCV if model is not using from_rolling splitter without error message. Defaults to False.
metric_registry_kwargstp.KwargsNoneParameters for metric registry. If None, uses default parameters based on the model type. This is used to specify parameters such as window or minp for rolling metrics. If using cross-validation, this should be set to None as it is not applicable. If using rolling metrics, this should be set to a dictionary with parameters for the metric registry. For example, {"window": 20}. Defaults to None.
use_closebool, optional--Whether to use ‘Close’ prices if True or ‘Open’ prices if False. Default to True`.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
portfolio_kwargstp.KwargsNoneAdditional keyword arguments for the portfolio simulation.
to_numpyboolFalseIf True, returns a np.ndarray. Default is False, returning a pd.DataFrame.
validate_metricsboolTrueCheck if metric is valid in the registry. Defaults to True.
validate_modelboolTrueCheck if model parameters are valid. Defaults to True.
model_paramstp.Kwargs--Additional parameters for model_func.
Returns:
TypeDescription
vbt.PF | OrderedDict | pd.DataFrame | tp.ArrayBacktested portfolio or requested metrics.

run_optuna_study

run_optuna_study(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    *,
    select_symbols: str | int | list[str | int= None,
    use_close: bool = True,
    metrics: str | List[str= 'sharpe_ratio',
    metric_registry_kwargs: Dict[str, Any] = None,
    pruner: optuna.pruners._base.BasePruner = None,
    sampler: optuna.samplers._base.BaseSampler = None,
    direction: str | List[str= 'maximize',
    create_study_kwargs: Dict[str, Any] = None,
    n_trials: int = 100,
    n_completed_trials: int = None,
    n_jobs: int = -1,
    gc_after_trial: bool = False,
    optimize_kwargs: Dict[str, Any] = None,
    verbose: bool = True,
    tracker: ~BaseTracker = None,
    cross_validate: bool = False,
    reduce_func: Callable = None,
    use_rolling: bool = False,
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    portfolio_kwargs: Dict[str, Any] = None,
    freq: str = None,
    **model_params,
) ‑> optuna.study.study.Study
Run hyperparameter optimization using optuna for a signal-based trading strategy.
  • Optuna is used for hyperparameter tuning and efficiently finds the best parameters.
  • The study prunes trials with poor results to accelerate the search process.
References: Parameters:
NameTypeDefaultDescription
datavbt.Data--Market data used for generating trading signals and backtesting.
s1str--First symbol.
s2str--Second symbol.
signal_modelstr--The signal generation model that determines entry and exit points.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
use_closebool, optional--Whether to use ‘Close’ prices if True or ‘Open’ prices if False. Default to True`.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
metric_registry_kwargstp.KwargsNoneParameters for metric registry. If None, uses default parameters based on the model type. This is used to specify parameters such as window or minp for rolling metrics. If using cross-validation, this should be set to None as it is not applicable. If using rolling metrics, this should be set to a dictionary with parameters for the metric registry. For example, {"window": 20}. Defaults to None.
pruneroptuna.pruners.BasePrunerNoneOptuna Pruner. If None, defaults to Asynchronous Successive Halving Algorithm. Defaults to None.
sampleroptuna.samplers.BaseSampler--Optuna Sampler. If None, defaults to TPE (Tree-structured Parzen Estimator) algorithm. Defaults to None.
directionstrmaximizeOptimization objective, either minimize or maximize, default is maximize.
create_study_kwargstp.KwargsNoneAdditional arguments for optuna.create_study, default is None.
n_trialsint100The number of trials for the optimization. This is the maximum number of trials that will be run. If n_completed_trials is set, the optimization will stop when the number of completed trials reaches this value. If n_completed_trials is not set, the optimization will run for n_trials trials. If n_trials is set to None, it will run indefinitely until n_completed_trials is reached. If n_trials is set to 0, it will not run any trials. If n_trials is set to a negative value, it will run indefinitely until n_completed_trials is reached. Defaults to 100.
n_completed_trialsintNoneThe number of successfully completed trials before stopping the optimization. If None, it will run for n_trials trials. TO be effective, the number of trials should be higher than the number of completed trials. default is None.
n_jobsint-1Number of parallel jobs for optimization (-1 for using all available CPUs cores), default is -1.
gc_after_trialboolFalseFlag to determine whether to automatically run garbage collection after each trial. Set to True to run the garbage collection, False otherwise. It runs a full collection by internally calling gc.collect. If you see an increase in memory consumption over several trials, try setting this flag to True. Defaults to False.
optimize_kwargsdictNoneAdditional arguments for study.optimize, default is None.
verboseboolTrueWhether to print Optuna logs during the optimization process. If True, prints logs to the console. Default is True.
trackerBaseTrackerNoneTracker instance for logging and monitoring the optimization process. If None, no tracking is performed. If you want to use a tracker, you can pass an instance of a tracker class that inherits from BaseTracker. For example, you can use NeptuneTracker. This tracker will log the optimization process and metrics to the tracker service. Default to None.
cross_validateboolFalseIf True, uses cross-validation analytics through run_report, wrapping BaseReportCV instead of _apply_pipeline. If False, uses data history as a whole. This is useful for optimizing the model using cross-validation. Defaults to False.
reduce_functp.CallableNoneFunction to reduce the results of the cross-validation. This function should take a 2D array of shape (n_trials, n_metrics) and return a 1D array of shape (n_metrics). This is used to reduce the results of the cross-validation to a single value for each metric. If None, defaults to vbt.nb.nanmedian_nb, which computes the median of the cross-validation results while ignoring NaN values. Defaults to None.
use_rollingboolFalseFlag to use rolling method via BaseRollingReport. Note that both rolling and cv models can be passed. Fallbacks to BaseReportCV if model is not using “from_rolling” splitter without error message. Defaults to False.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
portfolio_kwargstp.KwargsNoneAdditional keyword arguments for the portfolio simulation.
freqstrNoneFrequency of the data. Used when cross_validate is True. Defaults to None.
model_paramstp.Kwargs--Additional model parameters to optimize.
Returns:
TypeDescription
optuna.StudyThe Optuna study object containing optimization results.

Methods

get_signals

get_signals(
    self,
    model_output: numpy.ndarray,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
) ‑> systematica.signals.base.Signals
Generate trading signals based on scores. Parameters:
NameTypeDefaultDescription
model_outputtp.Array--Model output used for signal generation.
signal_modelstr--Signal model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
Returns:
TypeDescription
SignalsGenerated signals.

BaseReportMixin

BaseReportMixin()
Report mixin used in both rolling and cross-validated versions.

Ancestors

  • abc.ABC

Descendants

  • systematica.api.base.BaseReportCV
  • systematica.api.base.BaseRollingReport

Instance variables

  • all_metrics: List[str]: Get all available metrics
  • price_data: Retrieves price data for the specified symbols.
  • non_tunable_metrics: List[str]: Retrieves all non-tunable metrics from registry

Methods

get_annualized_return

get_annualized_return(
    self,
) ‑> pandas.core.frame.DataFrame
Computes the rolling (annualized) returns. Returns:
TypeDescription
pd.DataFrameDataFrame containing rolling annualized returns.

get_portfolio_metric

get_portfolio_metric(
    self,
    **kwargs,
) ‑> pandas.core.frame.DataFrame | numpy.ndarray
Computes portfolio performance metrics for different test sets. Parameters:
NameTypeDefaultDescription
kwargstp.Kwargs--Additional arguments to run the pipeline.
Returns:
TypeDescription
pd.DataFrame | tp.ArrayDataFrame or array containing portfolio performance metrics.

get_model_output

get_model_output(
    self,
    to_numpy: bool = False,
) ‑> numpy.ndarray | pandas.core.series.Series | pandas.core.frame.DataFrame
Computes the model output. Parameters:
NameTypeDefaultDescription
to_numpyboolFalseIf True, converts output to a np.array. Default is False, returning a pd.DataFrame.
Returns:
TypeDescription
np.ndarray or pd.DataFrameModel output data.

set_labels

set_labels(
    self,
    group_by: bool,
    metrics: str | List[str],
) ‑> List[str]
Generate column labels for the output DataFrame. Parameters:
NameTypeDefaultDescription
group_bybool--Whether to group results by symbol.
metricsstr--List of metrics to compute.
Returns:
TypeDescription
ListList of column names.

plot_annualized_return

plot_annualized_return(
    self,
    fig: vectorbtpro.utils.figure.FigureWidget = None,
    **layout_kwargs,
) ‑> vectorbtpro.utils.figure.FigureWidget
Plots total returns over time. Parameters:
NameTypeDefaultDescription
figvbt.FigureWidgetNoneExisting figure to update.
layout_kwargstp.Kwargs--Additional layout arguments for the plot.
Returns:
TypeDescription
vbt.FigureWidgetFigure with the plotted total returns.

plot_model_output

plot_model_output(
    self,
    fig: vectorbtpro.utils.figure.FigureWidget = None,
    **layout_kwargs,
) ‑> vectorbtpro.utils.figure.FigureWidget
Plots model output over time. Parameters:
NameTypeDefaultDescription
figvbt.FigureWidgetNoneExisting figure to update.
layout_kwargstp.Kwargs--Additional layout arguments for the plot.
Returns:
TypeDescription
vbt.FigureWidgetFigure with the plotted model output.

plot_portfolio_metric

plot_portfolio_metric(
    self,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    metrics: str | List[str= 'sharpe_ratio',
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    fig: vectorbtpro.utils.figure.FigureWidget = None,
    layout_kwargs: Dict[str, Any] = None,
    **portfolio_kwargs,
) ‑> vectorbtpro.utils.figure.FigureWidget
Plot portfolio performance metrics over time. Parameters:
NameTypeDefaultDescription
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
figvbt.FigureWidgetNoneExisting figure to update. If None, a new figure is created. Defaults to None.
layout_kwargsdictNoneAdditional layout arguments for the plot. If None, uses default layout settings. Defaults to None.
portfolio_kwargstp.Kwargs--Additional arguments for portfolio simulation.
Returns:
TypeDescription
vbt.FigureWidgetFigure with the plotted portfolio performance metrics.

BaseReportCV

BaseReportCV(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    model: ~BaseStatArb,
    use_close: bool = True,
    freq: str = 'auto',
)
Analyzes a statistical arbitrage model using cross-validation. Method generated by attrs for class BaseReportCV.

Ancestors

  • systematica.api.base.BaseReportMixin
  • abc.ABC

Descendants

  • systematica.api.reports.arbitrage_index.ArbitrageIndexReport
  • systematica.api.reports.meta_model.MetaModelCVReport
  • systematica.api.reports.momentum.AverageMomentumFactorCVReport
  • systematica.api.reports.momentum.MomentumFactorCVReport
  • systematica.api.reports.ou_process.OUProcessCVReport
  • systematica.api.reports.range_breakout.RangeBreakoutReport
  • systematica.api.reports.volatility.VolatilityFactorCVReport
  • systematica.api.reports.volume_profile.VolumeProfileFactorCVReport

Instance variables

  • splitter: systematica.utils.custom_splitter.CustomSplitter: Split arrays or matrices into specified train and test subsets.
  • splits: pandas.core.frame.DataFrame: Retrieves data splits based on the cross-validation splitter.
  • index_test: pandas.core.indexes.base.Index: Computes and returns the test set index of the dataset. The test set index is derived from the end bounds values returned by the splitter.
  • all_metrics: List[str]: Get available cross-validation metrics.
  • data: vectorbtpro.data.base.Data: Input data containing time series data.
  • freq: str: Set frequency. Default is auto, which infers frequency from the data index.
  • model: ~BaseStatArb: Model to analyse.
  • s1: str: Symbol.
  • s2: str: Symbol.
  • use_close: bool: Price close or open. Default is True, using close prices.

Methods

check

check(
    self,
    attribute: Type,
    value: Any,
)
Validates CV model. Parameters:
NameTypeDefaultDescription
attributetp.Type--The attribute being validated.
valuetp.Any--The model instance.
Raises:
TypeDescription
AttributeErrorIf the model does not use splitter as a parameter.

price_reset_stacked_by_set

price_reset_stacked_by_set(
    self,
) ‑> pandas.core.frame.DataFrame
Resets the price data stacked by set and attaches bounds to the index. This method uses the splitter to reset the price data, stacking it by set and attaching bounds to the index. Returns:
TypeDescription
pd.DataFrameThe reset price data stacked by set with bounds attached to the index.

model_reset_stacked_by_set

model_reset_stacked_by_set(
    self,
) ‑> pandas.core.frame.DataFrame
Resets the model output stacked by set and attaches bounds to the index. This method uses the splitter to reset the model output, stacking it by set and attaching bounds to the index. Returns:
TypeDescription
pd.DataFrameThe reset model output stacked by set with bounds attached to the index.

get_annualized_return

get_annualized_return(
    self,
) ‑> pandas.core.series.Series
Computes the annualized returns for the test set. Returns:
TypeDescription
pd.SeriesSeries containing the annualized returns for the test set.

get_portfolio_metric

get_portfolio_metric(
    self,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    metrics: str | List[str= 'sharpe_ratio',
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    to_numpy: bool = False,
    validate_metrics: bool = True,
    validate_model: bool = True,
    **portfolio_kwargs,
) ‑> pandas.core.frame.DataFrame | numpy.ndarray
Computes portfolio performance metrics for different test sets. Parameters:
NameTypeDefaultDescription
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
to_numpyboolFalseIf True, returns a np.ndarray. Default is False, returning a pd.DataFrame.
validate_metricsboolTrueCheck if metric is valid in the registry. Defaults to True.
validate_modelboolTrueCheck if model parameters are valid. Defaults to True.
portfolio_kwargstp.Kwargs--Additional arguments for portfolio simulation.
Returns:
TypeDescription
pd.DataFrame | tp.ArrayPortfolio performance metrics.

BaseRollingReport

BaseRollingReport(
    data: vectorbtpro.data.base.Data,
    s1: str,
    s2: str,
    model: ~BaseStatArb,
    use_close: bool = True,
    freq: str = 'auto',
)
Analyzes a statistical arbitrage model using rolling metrics. Method generated by attrs for class BaseRollingReport.

Ancestors

  • systematica.api.base.BaseReportMixin
  • abc.ABC

Descendants

  • systematica.api.reports.meta_model.RollingMetaModelReport
  • systematica.api.reports.momentum.RollingAverageMomentumFactorReport
  • systematica.api.reports.momentum.RollingMomentumFactorReport
  • systematica.api.reports.ou_process.RollingOUProcessReport
  • systematica.api.reports.volatility.RollingVolatilityFactorReport
  • systematica.api.reports.volume_profile.RollingVolumeProfileFactorReport

Instance variables

  • window: int: Window size.
  • minp: None | int: Minimum number of observations required.
  • all_metrics: List[str]: Get available rolling metrics.
  • data: vectorbtpro.data.base.Data: Input data containing time series data.
  • freq: str: Set frequency.
  • model: ~BaseStatArb: Model to analyse.
  • s1: str: Symbol.
  • s2: str: Symbol.
  • use_close: bool: Price close or open.

Methods

check

check(
    self,
    attribute: Type,
    value: Any,
)
Validates that the model has the necessary parameters for the strategy. Specifically, the model must have either:
  • Both window and minp attributes, or
  • Both train_window and splitter (set to *_rolling).
Parameters:
NameTypeDefaultDescription
attributetp.Type--The attribute being validated.
valuetp.Any--The value being set (not used in this validator).
Raises:
TypeDescription
ValueErrorIf the model does not have either window and minp or train_window and splitter=="*_rolling").

get_portfolio_metric

get_portfolio_metric(
    self,
    signal_model: str,
    long_entries: float,
    long_exits: float,
    short_entries: float,
    short_exits: float,
    select_symbols: str | int | list[str | int= None,
    metrics: str | List[str= 'sharpe_ratio',
    size: float | numpy.ndarray = 50,
    size_type: str | numpy.ndarray = 'valuepercent100',
    allow_partial: float | numpy.ndarray = None,
    fees: float | numpy.ndarray = None,
    fixed_fees: float | numpy.ndarray = None,
    slippage: float | numpy.ndarray = None,
    min_size: float | numpy.ndarray = None,
    max_size: float | numpy.ndarray = None,
    size_granularity: float | numpy.ndarray = None,
    sl_stop: float | numpy.ndarray = None,
    tsl_stop: float | numpy.ndarray = None,
    tp_stop: float | numpy.ndarray = None,
    accumulate: bool | str | numpy.ndarray = None,
    init_cash: float | numpy.ndarray = None,
    cash_sharing: bool = True,
    group_by: bool = True,
    call_seq: str | bool = 'auto',
    fill_pos_info: bool = False,
    log: bool | numpy.ndarray = None,
    to_numpy: bool = False,
    validate_metrics: bool = True,
    validate_model: bool = True,
    **portfolio_kwargs,
) ‑> pandas.core.frame.DataFrame | numpy.ndarray
Computes portfolio performance metrics on a rolling basis. Parameters:
NameTypeDefaultDescription
signal_modelstr--Model used for generating signals.
long_entriesfloat--Long entry signals.
long_exitsfloat--Long exit signals.
short_entriesfloat--Short entry signals.
short_exitsfloat--Short exit signals.
select_symbolsstrNoneSymbol name (e.g., BTCUSDT or ETHUSDT) or column index (e.g., 0 or 1) to keep. If None, no filtering.
metricsstrsharpe_ratioPerformance metrics to compute. Defaults to sharpe_ratio.
sizefloat50Size of each order. Defaults to 50.
size_typestrvaluepercent100Type of size. Defaults to valuepercent100.
allow_partialfloatNoneWhether to allow partial fills. Defaults to None.
feesfloatNoneFees per order. Defaults to None.
fixed_feesfloatNoneFixed fees per order. Defaults to None.
slippagefloatNoneSlippage per order. Defaults to None.
min_sizefloatNoneMinimum size of each order. Defaults to None.
max_sizefloatNoneMaximum size of each order. Defaults to None.
size_granularityfloatNoneGranularity of size. Defaults to None.
sl_stopfloatNoneStop-loss level. Defaults to None.
tsl_stopfloatNoneTrailing stop-loss level. Defaults to None.
tp_stopfloatNoneTake-profit level. Defaults to None.
accumulateboolNoneWhether to accumulate orders. Defaults to None.
init_cashfloatNoneInitial cash. Defaults to None.
cash_sharingboolTrueWhether to share cash between assets. Defaults to True.
group_byboolTrueWhether to group by symbol. Defaults to True.
call_seqboolautoCall sequence. Defaults to auto.
fill_pos_infoboolFalseWhether to fill position info. Defaults to False.
logboolNoneWhether to log orders. Defaults to None.
to_numpyboolFalseIf True, returns a np.ndarray. Default is False, returning a pd.DataFrame.
validate_metricsboolTrueCheck if metric is valid in the registry. Defaults to True.
validate_modelboolTrueCheck if model parameters are valid. Defaults to True.
portfolio_kwargstp.Kwargs--Additional arguments for portfolio simulation.
Returns:
TypeDescription
pd.DataFrame | tp.ArrayDataFrame or array containing portfolio performance metrics.

BaseSignal

BaseSignal()
Abstract base class for signal generation.

Ancestors

  • abc.ABC

Descendants

  • systematica.api.signals.cross_spread.CrossSpread
  • systematica.api.signals.crossover.Crossover
  • systematica.api.signals.crossover.Crossover1d
  • systematica.api.signals.spread.Spread
  • systematica.api.signals.twin_spread.TwinSpread

Static methods

run

run(
    *arg,
    **kwargs,
)
Run the signal generation process. Parameters:
NameTypeDefaultDescription
argtuple--Positional arguments.
kwargstp.Kwargs--Keyword arguments.