### Python Suggestion Example Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/tuners/utils Illustrative Python code demonstrating how the 'suggest' method might be used within an Optuna optimization loop to get a suggested value for a parameter. ```Python import optuna def objective(trial: optuna.trial._trial.Trial): # Example: Suggest a learning rate learning_rate = trial.suggest_float('learning_rate', 1e-5, 1e-1, log=True) # Example: Suggest a batch size batch_size = trial.suggest_int('batch_size', 16, 128, step=16) # Example: Suggest an activation function activation = trial.suggest_categorical('activation', ['relu', 'tanh', 'sigmoid']) # ... use these suggested hyperparameters to train a model ... accuracy = 0.9 # Placeholder for actual model performance return accuracy # In a real scenario, you would create a study and optimize the objective function # study = optuna.create_study(direction='maximize') # study.optimize(objective, n_trials=100) ``` -------------------------------- ### OptunaTuner Methods Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/tuners/optuna_tuner Documentation for the OptunaTuner class methods, covering objective function creation and Optuna study execution. ```APIDOC OptunaTuner: create_objective(self, feature_config: FeatureConfig) -> Callable Creates an optimized objective function for Optuna by separating fixed and tunable parameters once. Parameters: feature_config (FeatureConfig): Feature configurations. Returns: tp.Callable: A callable objective function for Optuna optimization. run_feature(self, feature_config: FeatureConfig) -> optuna.study.study.Study Run feature config. Parameters: feature_config (FeatureConfig): feature configuration. Returns: optuna.Study: Optuna study. run(self, objective: Callable) -> optuna.study.study.Study Run optuna study or tracker. Parameters: objective (tp.Callable): Objective function. Returns: study : optuna.Study: Optuna Study. run_tracker(self, objective: Callable) -> optuna.study.study.Study Run tracker. Parameters: objective (tp.Callable): Objective function. Returns: study : optuna.Study: Optuna Study. run_optuna(self, objective: Callable) -> optuna.study.study.Study Run optuna. Parameters: objective (tp.Callable): Objective function. Returns: study : optuna.Study: Optuna Study. ``` -------------------------------- ### Sandbox Class Constructor and Parameters Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/sandbox/sandbox Initializes the Sandbox class, which manages feature calculation and strategy optimization. It accepts various configurations for Optuna samplers, pruners, metrics, and parallel job execution. Instance variables detail the configurable aspects of the Sandbox. ```APIDOC Sandbox: __init__(feature_registry: List[~FeatureConfig], pruner: optuna.pruners._base.BasePruner = , sampler: optuna.samplers._base.BaseSampler = , direction: str | List[str] = 'maximize', create_study_kwargs: Dict[str, Any] = _Nothing.NOTHING, n_trials: int = 100, n_completed_trials: int = None, n_jobs: int = -1, gc_after_trial: bool = False, optimize_kwargs: Dict[str, Any] = _Nothing.NOTHING, verbose: bool = True, tracker: systematica.portfolio.trackers.base.BaseTracker = None, metrics: str | List[str] = 'sharpe_ratio', metric_registry_kwargs: Dict[str, Any] = _Nothing.NOTHING, cross_validate: bool = False, reduce_func: Callable = CPUDispatcher(), use_rolling: bool = False) Handles feature calculation and strategy optimization using a registry of feature configurations. Parameters: feature_registry: List of feature configurations. pruner: Optuna pruner. Defaults to SuccessiveHalvingPruner. sampler: Optuna sampler. Defaults to TPESampler. direction: Optimization direction for Optuna ('maximize' or 'minimize'). Can be a list. create_study_kwargs: Additional Optuna study parameters. n_trials: Number of optimization trials for Optuna (default: 100). n_completed_trials: Number of trials to complete before stopping (default: None). n_jobs: Parallel jobs for Optuna (default: -1). gc_after_trial: Flag to run garbage collection after each trial (default: False). optimize_kwargs: Additional arguments for Optuna optimization. verbose: Enable verbose output (default: True). tracker: Log and monitor Optuna hyperparameters using a tracker integration. metrics: Performance metrics to compute (default: 'sharpe_ratio'). Can be a list. metric_registry_kwargs: Additional arguments for metric registry (e.g., window for rolling metrics). cross_validate: Whether to use cross-validation analytics (default: False). reduce_func: Reduce function when using cross_validate. Defaults to nanmedian_nb. use_rolling: Flag to use rolling method via BaseRollingReport (default: False). ``` -------------------------------- ### Get Inputs (get_inputs) Source: https://systematica.mintlify.app/api-reference/systematica/models/meta_model/base Retrieves the state representation, specifically the input (X) variables, for model training. It supports downsampling for performance optimization and can return results as a NumPy array or Pandas DataFrame. An example demonstrates how to add features to a vbt.Data object. ```APIDOC get_inputs(self, downsample: str = '1d', to_numpy: bool = False, state_registry: List[systematica.models.meta_model.state_registries.StateConfig] = None) -> pandas.core.frame.DataFrame | numpy.ndarray Parameters: - downsample (str, optional): Resample data before state computation to speed up the process. If None, no resampling is performed. Defaults to '1d' (daily). - to_numpy (bool, optional): Output Numpy array if True. Pandas DataFrame object otherwise. The default is False. - state_registry (List[systematica.models.meta_model.state_registries.StateConfig], optional): State registry to use. If None, defaults to STATE_REGISTRY. The default is None. Returns: pd.DataFrame | tp.Array2d: Input (exogenous) variables. Example: ```python data = sma.load_clean_data("1d") rets = sma.get_returns(data.close) data = data.add_feature("rets", rets, missing_index="drop") ``` ``` -------------------------------- ### OptunaTuner Constructor Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/tuners/optuna_tuner Initializes the OptunaTuner class, configuring parameters for hyperparameter optimization using Optuna. It accepts various settings for samplers, pruners, optimization direction, trial counts, parallel jobs, and metrics. ```APIDOC OptunaTuner: __init__( pruner: optuna.pruners._base.BasePruner = , sampler: optuna.samplers._base.BaseSampler = , direction: str | List[str] = 'maximize', create_study_kwargs: Dict[str, Any] = _Nothing.NOTHING, n_trials: int = 100, n_completed_trials: int | None = None, n_jobs: int = -1, gc_after_trial: bool = False, optimize_kwargs: Dict[str, Any] = _Nothing.NOTHING, verbose: bool = True, tracker: systematica.portfolio.trackers.base.BaseTracker | None = None, metrics: str | List[str] = 'sharpe_ratio', metric_registry_kwargs: Dict[str, Any] = _Nothing.NOTHING, cross_validate: bool = False, reduce_func: Callable = CPUDispatcher(), use_rolling: bool = False, ) Parameters: pruner: The pruner strategy for Optuna. sampler: The sampler strategy for Optuna. direction: The optimization direction ('maximize' or 'minimize'). Can be a list for multiple directions. create_study_kwargs: Additional keyword arguments for creating an Optuna study. n_trials: The total number of trials to run. n_completed_trials: Number of trials to complete before stopping. If None, n_trials is used. n_jobs: Number of parallel jobs for Optuna. -1 means using all available CPU cores. gc_after_trial: If True, runs garbage collection after each trial to manage memory. optimize_kwargs: Additional keyword arguments for the Optuna optimization process. verbose: If True, enables verbose output during optimization. tracker: An optional tracker for logging Optuna hyperparameter progress. metrics: The performance metric(s) to optimize. Defaults to 'sharpe_ratio'. metric_registry_kwargs: Additional arguments for the metric registry, e.g., window size. cross_validate: If True, uses cross-validation for optimization. reduce_func: Function to reduce results when cross_validate is True. use_rolling: Flag to use rolling window calculations for metrics. Instance Variables: target_names: List[str] - Normalized metric names. create_study_kwargs: Dict[str, Any] - Additional optuna study parameters. cross_validate: bool - Whether to use cross-validation analytics. direction: str | List[str] - Optimization direction for Optuna. gc_after_trial: bool - Flag to determine whether to run garbage collection after each trial. metric_registry_kwargs: Dict[str, Any] - Additional arguments for metric registry. metrics: str | List[str] - Performance metrics to compute. n_completed_trials: int - Number of trials to complete before stopping. n_jobs: int - Parallel jobs for Optuna. n_trials: int - Number of optimization trials for Optuna. optimize_kwargs: Dict[str, Any] - Additional arguments for Optuna optimization. pruner: optuna.pruners._base.BasePruner - Pruner strategy. reduce_func: Callable - Reduce function when using cross_validate. sampler: optuna.samplers._base.BaseSampler - Sampler strategy. tracker: systematica.portfolio.trackers.base.BaseTracker - Tracker for logging Optuna hyperparameter. use_rolling: bool - Flag to use rolling method via BaseRollingReport. verbose: bool - Enable verbose output. ``` -------------------------------- ### Get TradingView Data Source: https://systematica.mintlify.app/api-reference/systematica/data/loader Extracts stock data from TradingView based on market capitalization filter. It uses `vbt.TVData.list_symbols` and `vbt.TVData.pull` to retrieve data for symbols matching an exchange pattern, filtering by market cap (>= 10 billion) and start date. Returns a `vbt.TVData` object. ```python get_tradingview_data( exchange_pattern: str, **pull_kwargs, ) -> vectorbtpro.data.custom.tv.TVData Extract stock data from TradingView based on market capitalization filter. This function uses the `vbt.TVData.list_symbols` and `vbt.TVData.pull` methods to retrieve market data from TradingView for symbols matching a specified exchange pattern. The data is filtered by market capitalization (e.i. greater than or equal to 10 billion), and the symbol names are cleaned up. The data is also filtered by the provided start date. Parameters: - `exchange_pattern` (str): A pattern for the exchange symbols (e.g., “NASDAQ”). - `pull_kwargs` (tp.Kwargs): Additional arguments passed to `vbt.TVData.pull` to customize the data fetching. Returns: - `vbt.TVData`: A `vbt.TVData` object containing the filtered stock data from TradingView. ``` -------------------------------- ### Cross-Validation Loop Example Source: https://systematica.mintlify.app/api-reference/systematica/models/meta_model/clf_model This example demonstrates a typical cross-validation loop, fitting a scikit-learn pipeline on training data slices and predicting on test data slices obtained from the splitter. ```python >>> X_slices, y_slices = splitter.take(X), splitter.take(y) >>> y_tests = [] >>> y_preds = [] >>> for split in X_slices.index.unique(level="split"): ... X_train_slice = X_slices[(split, "train")] ... y_train_slice = y_slices[(split, "train")] ... X_test_slice = X_slices[(split, "test")] ... y_test_slice = y_slices[(split, "test")] ... try: ... fitted_pipe = pipeline.fit(X_train_slice, y_train_slice) ... test_pred = fitted_pipe.predict(X_test_slice) ... test_pred_ser = pd.Series(test_pred, index=y_test_slice.index) ``` -------------------------------- ### Get Symbol Parameters Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/composers/models Retrieves symbol parameters for the current context. Returns a dictionary containing symbol parameters. ```APIDOC get_symbol_params: signature: get_symbol_params(self,) -> Dict[str, Any] description: Get symbol params. returns: - type: tp.Kwargs description: Symbol params. ``` -------------------------------- ### run Method - Systematica PortfolioAnalyzer Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/composers/models Executes a pipeline with the given data and symbols. This method is part of the Systematica PortfolioAnalyzer and requires input data, two symbols, and an optional flag to use closing prices. ```APIDOC run Method: Signature: run( self, data: vectorbtpro.data.base.Data, s1: str, s2: str, use_close: bool = True, ) -> systematica.portfolio.analyzers.base.PortfolioAnalyzer Description: Execute the pipeline with the given data and symbols. Parameters: data (vbt.Data): Input data for the pipeline. s1 (str): First symbol. s2 (str): Second symbol. use_close (bool, optional): Whether to use ‘Close’ prices. Defaults to True. Returns: PortfolioAnalyzer: Portfolio analyzer object with the pipeline results. ``` -------------------------------- ### Instance Variables Source: https://systematica.mintlify.app/api-reference/systematica/api/models/volume_profile Describes the configurable instance variables for volatility models, covering data partitioning, scoring, and window settings. ```APIDOC Instance Variables: - custom_splitter: str | None - Description: Custom splitter to use for data partitioning. - Defaults to: None - Notes: If set, it should be a string that matches a custom splitter function. - custom_splitter_kwargs: dict | None - Description: Additional keyword arguments for the custom splitter. - Defaults to: None - Notes: If `custom_splitter` is set, this should contain any necessary parameters for the custom splitter function. - score_scale: float - Description: Score scale coefficient. - Defaults to: 2.0 - Notes: This factor scales the final score output. - short_term_window: int - Description: Short term window. - Defaults to: 30 - Notes: This is the window size used for short-term volume calculations. - splitter: str - Description: Default splitter to be used if `custom_splitter` is not passed. - Choices: `from_rolling`, `from_expanding`, `from_custom_rolling`, `from_custom_expanding` - Defaults to: "from_custom_rolling" - surge_scale: float - Description: Volume surge scale coefficient. - Defaults to: 5.0 - Notes: This factor amplifies the volume surge detection. - testing_window: int - Description: The size of the testing window. - Defaults to: 60 - Notes: This is the window size used for testing the model. - training_window: int - Description: The size of the training window. - Defaults to: 365 - Notes: This is the window size used for training the model. ``` -------------------------------- ### Get Plants API Source: https://systematica.mintlify.app/api-reference/post-plants Retrieves a list of plants from the store. This endpoint is available for querying plant data. ```APIDOC GET /plants Retrieves a list of plants from the store. ``` -------------------------------- ### Systematica Portfolio Tuners API Documentation Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/tuners/optuna_tuner Documentation for the Tuners module within the Systematica Portfolio, specifically detailing the Optuna Tuner. This section outlines the components and functionalities related to hyperparameter tuning using Optuna. ```APIDOC Module: systematica.portfolio.tuners.optuna_tuner Optuna Tuner: Description: Integrates Optuna for hyperparameter optimization within the Systematica portfolio. Usage: Used for tuning model parameters to improve performance. Dependencies: Optuna library. Related Components: - Tuners (Base) - Tuners (Utils) ``` -------------------------------- ### Get Plants API Source: https://systematica.mintlify.app/api-reference/get-plants Retrieves all plants accessible to the user from the system. Supports filtering by a limit parameter. ```APIDOC GET /plants Returns all plants from the system that the user has access to. Parameters: - Authorization (string, header, required): Bearer authentication header of the form `Bearer `, where `` is your auth token. - limit (integer, query): The maximum number of results to return. Responses: - 200 (application/json): Plant response. The response is of type `object[]`. Example: [ { "name": "", "tag": "" } ] - 400: Bad Request ``` ```cURL curl --request GET \ --url http://sandbox.mintlify.com/plants \ --header 'Authorization: Bearer ' ``` -------------------------------- ### Get Annualization Factor Source: https://systematica.mintlify.app/api-reference/systematica/utils/custom_datetime Calculates the annualization factor based on a given frequency. This is useful for converting periodic data to an annual basis. ```Python import pandas as pd def get_ann_factor(freq: pd.Timedelta) -> float: """ Get annualization factor Parameters: freq (pd.Timedelta): Frequency. Returns: float: Annualization factor. """ # Implementation details would go here pass # Example Usage: # from datetime import timedelta # daily_freq = timedelta(days=1) # ann_factor = get_ann_factor(daily_freq) # print(ann_factor) ``` -------------------------------- ### Initialize Blockforce Theme Source: https://systematica.mintlify.app/api-reference/systematica/utils/blockforce_theme Initializes and registers the Blockforce Capital theme with Plotly and vectorbtpro. This function sets up the theme with the Blockforce color palette, layout defaults, and trace styles for consistent visualizations. ```python init_theme() ``` -------------------------------- ### Load Binance Data (Raw & Clean) Source: https://systematica.mintlify.app/api-reference/systematica/data/loader Enables loading of historical Binance data, supporting both raw and cleaned datasets. Users can specify the timeframe, file suffix, and date range for data retrieval. ```APIDOC load_binance_data(timeframe: str = '1d', suffix: str = 'h5', start: str = '2018-01-01 UTC', end: str = None) -> vectorbtpro.data.base.Data Loads raw Binance data from files. Parameters: timeframe: Timeframe of the file to be loaded. suffix: Extension (suffix) of the file to load (e.g., 'h5'). start: The start date for the data in UTC string format (e.g., 'YYYY-MM UTC'). end: The end date for the data in UTC string format. Returns: A vbt.Data object containing the fetched price data. ``` ```APIDOC load_clean_data(timeframe: str = '1d', suffix: str = 'h5', start: str = '2018-01-01 UTC', end: str = None) -> vectorbtpro.data.base.Data Loads cleaned Binance data from files. Parameters: timeframe: Timeframe of the file to be loaded. suffix: Extension (suffix) of the file to load (e.g., 'h5'). start: The start date for the data in UTC string format (e.g., 'YYYY-MM UTC'). end: The end date for the data in UTC string format. Returns: A vbt.Data object containing the fetched price data. ``` -------------------------------- ### Metrics Registry: Get All Metrics Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/metrics/base Retrieves metric keys from the registry. Supports filtering by tunable status and specific function types (rolling, pf). ```APIDOC get_all_metrics(self, include_non_tunable: bool = False) -> List[str] Get a list of metric keys from the registry. Optionally include non-tunable metrics based on user choice. Parameters: include_non_tunable (bool, default False): Whether to include non-tunable metrics. Returns: List[str]: List of metric keys. ``` ```APIDOC get_all_rolling_metrics(self, include_non_tunable: bool = False) -> List[str] Get a list of metric keys from the registry that have a valid rolling_func. Optionally include non-tunable metrics based on user choice. Parameters: include_non_tunable (bool, default False): Whether to include non-tunable metrics. Returns: List[str]: List of metric keys with valid (non-NaNs) rolling_func values. ``` ```APIDOC get_all_pf_metrics(self, include_non_tunable: bool = False) -> List[str] Get a list of metric keys from the registry that have a valid pf_func. Optionally include non-tunable metrics based on user choice. Parameters: include_non_tunable (bool, default False): Whether to include non-tunable metrics. Returns: List[str]: List of metric keys with valid (non-NaNs) pf_func values. ``` ```APIDOC get_all_non_tunable_metrics(self) -> List[str] Get a list of non-tunable metric keys from the registry. Returns: List[str]: List of non-tunable metrics. ``` -------------------------------- ### Get Scikit-Learn Pipeline Object Source: https://systematica.mintlify.app/api-reference/systematica/models/meta_model/clf_model Shows how to create a scikit-learn Pipeline that chains a StandardScaler for preprocessing and a RandomForestClassifier for classification. ```python >>> pipeline = make_pipeline( ... StandardScaler(), ... RandomForestClassifier() ... ) ``` -------------------------------- ### Optimize Portfolio with run_from_optimize_func Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/simulation Sets up and returns a portfolio optimizer instance, enabling custom sampling and optimization functions. It takes historical market data, returns, signals, and a custom optimization function as input, returning a configured PortfolioOptimizer instance ready for backtesting. ```APIDOC run_from_optimize_func: Signature: run_from_optimize_func( data: vectorbtpro.data.base.Data, returns: numpy.ndarray, signals: systematica.signals.base.Signals, optimize_func: Callable, config: Dict[str, Any] = None, ) -> vectorbtpro.portfolio.pfopt.base.PortfolioOptimizer Description: Sets up and returns a portfolio optimizer instance, using custom sampling and optimization functions. Parameters: data (vectorbtpro.data.base.Data): Historical market data. returns (numpy.ndarray): Array of returns to be used for optimization. signals (systematica.signals.base.Signals): Generated trading signals. optimize_func (Callable): Custom optimization function that takes the returns and signals as input. This function should return a dictionary of optimized parameters or metrics. config (Dict[str, Any], optional): Dictionary with optimization parameters. Defaults to None. Returns: vbt.PortfolioOptimizer: Configured portfolio optimizer instance ready for backtesting. Examples: >>> strategy = ... >>> portfolio_optimizer = strategy.optimizer( ... ..., ... config={'obj': 'Sharpe', 'every': 'M'} ... ) >>> portfolio = portfolio_optimizer.simulate() ``` -------------------------------- ### Get Current UTC Time as String Source: https://systematica.mintlify.app/api-reference/systematica/utils/custom_datetime Retrieves the current time in UTC and formats it as a string. The string format is ISO 8601 compliant. ```python current_utc_str() -> str # Description: Current time in UTC in string format. # Returns: # str: Current time in UTC as a string in the format %Y-%m-%dT%H:%M:%S. ``` -------------------------------- ### Systematica Library Navigation Source: https://systematica.mintlify.app/api-reference/systematica/models/ou_process Provides a general overview of the Systematica library's API reference structure, listing key modules and sections. This helps users navigate to different parts of the documentation. ```APIDOC API Reference Navigation: - Configuration - API - Data - Models - Arbitrage Index - Meta Model - Momentum - Ou Process - Range Breakout - Volatility - Volume Profile - Portfolio - Preprocessing - Signals - Utils ``` -------------------------------- ### ArbitrageClipIndex Model API Documentation Source: https://systematica.mintlify.app/api-reference/systematica/api/models/arbitrage_index Detailed API documentation for the ArbitrageClipIndex model, including its constructor signature, parameter descriptions, and static methods like validation. ```APIDOC systematica.api.models.arbitrage_index ## `ArbitrageClipIndex` ``` ArbitrageClipIndex( training_window: int = 365, testing_window: int = 60, splitter: str = 'from_custom_rolling', custom_splitter: str | None = None, custom_splitter_kwargs: Dict[str, Any] | None = None, copula: str | type = 'auto', list_copulas: list[systematica.models.arbitrage_index.base.BaseCopula] | None = None, method: str = 'aic', lower: float = -1.0, upper: float = 1.0, center: float = 0.5, sequential: bool = False, ) ``` Arbitrage clip index: Marginal probability model. This model computes the accumulated sum of log returns and applies a clipping transformation to the accumulated index. It is useful for analyzing the performance of two assets over time, particularly in the context of arbitrage opportunities. The clipping transformation ensures that the accumulated index remains within specified bounds, preventing extreme values that could skew the analysis. Method generated by attrs for class ArbitrageClipIndex. ### Ancestors * `systematica.api.base.BaseStatArb` * `abc.ABC` ### Static methods #### `is_valid` ``` is_valid( model_params: Dict[str, Any], signal_params: Dict[str, Any], ) ``` Validate model parameters. **Parameters**: | Name | Type | Default | Description | | --- | --- | --- | --- | | `model_params` | `tp.Kwargs` | `--` | Model parameters. | | `signal_params` | `tp.Kwargs` | `--` | Signal parameters. | **Raises**: | Type | Description | | --- | --- | | `ValueError` | If `long_entries` or `short_entries` are not within the specified bounds. | ``` -------------------------------- ### PortfolioComposer Methods Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/composers/models PortfolioComposer is used to compose portfolios from trials. It includes methods to retrieve data using a specified loader and to get the parameters used for composition. ```APIDOC PortfolioComposer: Constructor: PortfolioComposer( feature_config: Dict[str, Any], model_params: Dict[str, Any], ) Description: Compose portfolio(s) from trials. Class variables: feature_config (Dict[str, Any]): Configuration for a feature calculation. model_params (Dict[str, Any]): A dictionary of optional keyword arguments needed to compose the portfolio. Instance variables: all_params (Dict[str, Any]): All parameters. get_data Method: Signature: get_data( self, loader: vectorbtpro.data.base.Data | Callable = None, loader_kwargs: Dict[str, Any] = None, ) -> vectorbtpro.data.base.Data Description: Get data. Parameters: loader (vbt.Data | Callable, optional): Data loader function or object. If None, uses `load_clean_data`. loader_kwargs (tp.Kwargs, optional): Additional keyword arguments for the loader function. If None, uses `config.LOADER_PARAMS`. Returns: tp.Kwargs: Data params. get_compose_params Method: Signature: get_compose_params( self, ) -> Dict[str, Any] Description: Get compose parameters. Returns: tp.Kwargs: Compose params. ``` -------------------------------- ### Systematica API Reference Navigation Source: https://systematica.mintlify.app/api-reference/systematica/models/volatility Provides navigation links to various sections of the Systematica API reference, including configuration, data, models, portfolio, preprocessing, signals, and utilities. ```APIDOC /api-reference/systematica - Configuration - API - Data - Models - Portfolio - Preprocessing - Signals - Utils ``` -------------------------------- ### Get Current UTC Time Source: https://systematica.mintlify.app/api-reference/systematica/utils/custom_datetime Retrieves the current time in Coordinated Universal Time (UTC). Returns a datetime object representing the current UTC timestamp. ```python current_utc() -> datetime.datetime # Description: Current time in UTC. # Returns: # datetime: Current time in UTC as a datetime object. ``` -------------------------------- ### run_pipeline Method Source: https://systematica.mintlify.app/api-reference/systematica/api/models/meta_model Executes the portfolio pipeline for streamlined backtesting. This method is highly parametrizable, allowing users to configure various aspects of the simulation, from symbol selection and metric computation to order execution details and risk management parameters. ```APIDOC run_pipeline( cls, select_symbols: str | int | list[str | int] = None, metrics: str | List[str] = None, use_rolling: bool = False, metric_registry_kwargs: Dict[str, Any] = None, 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, **model_params ) -> vectorbtpro.portfolio.base.Portfolio | collections.OrderedDict | pandas.core.frame.DataFrame | numpy.ndarray Description: Executes the portfolio pipeline. Method is parametrizable. See `BaseStatArb.run_pipeline` Combines scoring, signal generation, and portfolio simulation into a single pipeline for streamlined backtesting. Parameters: - cls: The class instance. - select_symbols: Symbol name (e.g., `BTCUSDT` or `ETHUSDT`) or column index (e.g., `0` or `1`) to keep. If `None`, no filtering. - metrics: Performance metrics to compute. Defaults to `sharpe_ratio`. - use_rolling: Flag 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_kwargs: Parameters 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}`. - size: Size of each order. Defaults to `50`. - size_type: Type of size. Defaults to `valuepercent100`. - allow_partial: Whether to allow partial fills. Defaults to `None`. - fees: Fees per order. Defaults to `None`. - fixed_fees: Fixed fees per order. Defaults to `None`. - slippage: Slippage per order. Defaults to `None`. - min_size: Minimum size of each order. Defaults to `None`. - max_size: Maximum size of each order. Defaults to `None`. - size_granularity: Granularity of size. Defaults to `None`. - sl_stop: Stop-loss level. Defaults to `None`. - tsl_stop: Trailing stop-loss level. Defaults to `None`. - tp_stop: Take-profit level. Defaults to `None`. - accumulate: Whether to accumulate orders. Defaults to `None`. - init_cash: Initial cash. Defaults to `None`. - cash_sharing: Whether to share cash between assets. Defaults to `True`. - group_by: Whether to group by symbol. Defaults to `True`. - call_seq: Call sequence. Defaults to `auto`. - fill_pos_info: Whether to fill position info. Defaults to `False`. - log: Whether to log orders. Defaults to `None`. - portfolio_kwargs: Additional keyword arguments for the portfolio simulation. - to_numpy: If `True`, returns a `np.ndarray`. Default is `False`, returning a `pd.DataFrame`. - validate_metrics: Check if `metric` is valid in the registry. Defaults to `True`. - model_params: Additional parameters for `model_func`. Returns: - Backtested portfolio or requested metrics. Types can be `vbt.PF`, `OrderedDict`, `pd.DataFrame`, or `tp.Array`. ``` -------------------------------- ### Pie Class Example Usage Source: https://systematica.mintlify.app/api-reference/systematica/utils/custom_plots Demonstrates how to instantiate the Pie class with sample data and trace names, and then display the generated figure. Requires numpy and systematica libraries. ```python >>> import numpy as np >>> import systematica as sma >>> pie = sma.Pie( ... data=np.array([0.06, 0.02, 0.05, 0.09]), ... trace_names=['SPY', 'TLT', 'XLF', 'XLE'], ... ) >>> pie.fig.show() ``` -------------------------------- ### Systematica run() Method Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/trial_selectors/models Executes the efficient frontier projection selection algorithm. This method is common across various portfolio optimization strategies within the Systematica library. It requires a pandas DataFrame as input and returns a pandas Series representing the optimal parameter combination. ```APIDOC run(self, df: pandas.core.frame.DataFrame) -> pandas.core.series.Series Description: Execute the efficient frontier projection selection algorithm. Parameters: - df (pd.DataFrame): DataFrame containing parameters to select from. Returns: - pd.Series: The parameter combination with maximum Sharpe ratio. Dependencies: - pandas Usage: This method is typically called on an instance of a specific optimization strategy class (e.g., ElbowPoint, ClosestIdealPoint, etc.) after initialization. ``` -------------------------------- ### Get Classification Report Source: https://systematica.mintlify.app/api-reference/systematica/models/meta_model/base Generates a comprehensive classification report that includes precision, recall, F1-score, and support for each class. This is useful for evaluating the performance of a classification model across different classes. ```APIDOC get_report(self, y_pred: pandas.core.series.Series) -> pandas.core.frame.DataFrame Description: Build a report showing the main classification metrics. Parameters: - y_pred (pd.Series): Estimated targets as returned by a classifier. Returns: pd.DataFrame: DataFrame summary of the precision, recall, F1 score for each class. See Also: - precision_recall_fscore_support - confusion_matrix - multilabel_confusion_matrix ``` -------------------------------- ### Anthropic Integration Example Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/analyzers Indicates potential integration with Anthropic's Claude AI model within the Systematica framework, likely for natural language processing or analysis tasks. ```Python # Example of how Anthropic's Claude might be used within Systematica # This is a conceptual representation based on the text. # Assuming a class structure like: # class AnthropicAnalyzer(systematica.portfolio.analyzers.base.BaseAnalyzer): # def __init__(self, model_name: str = 'claude-3-opus-20240229'): # super().__init__() # self.model_name = model_name # # Initialize Anthropic client here # # self.client = AnthropicClient(api_key='YOUR_API_KEY') # def analyze(self, data: dict) -> dict: # # Prepare prompt for Claude # prompt = f"Analyze the following portfolio data: {data}" # # Call Anthropic API # # response = self.client.messages.create( # # model=self.model_name, # # max_tokens=1000, # # messages=[ # # {"role": "user", "content": prompt} # # ] # # ) # # Process Claude's response # # return {'analysis': response.content[0].text} # pass # Example Usage (conceptual): # analyzer = AnthropicAnalyzer() # portfolio_data = {'returns': [0.01, 0.02, -0.005], 'volatility': 0.05} # result = analyzer.analyze(portfolio_data) # print(result) # The text 'AnthropicOpen in Claude' suggests this capability exists or is being documented. ``` -------------------------------- ### Run Study Method - Python API Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/trackers/base Executes an optimization study using a provided objective function and configuration. It takes keyword arguments for study creation and optimization, returning the completed Optuna study object. ```APIDOC run_study: signature: run_study(self, objective: Callable, create_study_kwargs: Dict[str, Any], optimize_kwargs: Dict[str, Any]) -> optuna.study.study.Study description: Run study. parameters: - name: objective type: tp.Callable description: The objective function to be optimized. - name: create_study_kwargs type: tp.Kwargs description: Keyword arguments for creating the Optuna study. - name: optimize_kwargs type: tp.Kwargs description: Keyword arguments for the optimization process. returns: - type: optuna.Study description: The Optuna study object containing optimization results. ``` -------------------------------- ### Get Target (get_target) Source: https://systematica.mintlify.app/api-reference/systematica/models/meta_model/base Converts categorical labels into their numeric code representations. This is useful for preparing target variables for machine learning models. The output can be returned as a NumPy array or a Pandas Series. ```APIDOC get_target(self, to_numpy: bool = False) -> numpy.ndarray | pandas.core.series.Series Parameters: - to_numpy (bool, optional): Output numpy array if True. Pandas DataFrame otherwise. Default to False. Returns: tp.Array1d | pd.Series: Array or Series containing the numeric encoding of categories. ``` -------------------------------- ### Systematica Models - Ou Process Module Source: https://systematica.mintlify.app/api-reference/systematica/models/volatility Documentation for the Ou Process model within the Systematica project. This section outlines the Ou Process model and its core implementation. ```APIDOC systematica.models.ou_process ## Sub-modules * systematica.models.ou_process.ou_process This module implements the Ornstein-Uhlenbeck (OU) process, a mathematical model often used in finance for modeling interest rates or asset prices. It captures mean reversion properties. ``` -------------------------------- ### ColumnStackComposer Constructor and run Method Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/composers/models ColumnStackComposer combines trial strategies using the column_stack method from vectorbtpro. The run method executes and combines these strategies using column stacking, with an option to group results. ```APIDOC ColumnStackComposer: Constructor: ColumnStackComposer( model_name: str, signal_params=_Nothing.NOTHING, portfolio_params: Dict[str, Any] = _Nothing.NOTHING, model_params: Dict[str, Any] = _Nothing.NOTHING, ) Description: Combine trial strategies via colum_stack method. A composer that combines multiple trial strategies using the column_stack method from vectorbtpro. Ancestors: * systematica.portfolio.composers.base.BaseComposer run Method: Signature: run( self, data: vectorbtpro.data.base.Data, s1: str, s2: str, group_by: bool = True, use_close: bool = True, ) -> systematica.portfolio.analyzers.base.PortfolioAnalyzer Description: Execute and combine multiple strategies using column stacking. Parameters: data (vbt.Data): Input data for the pipeline. s1 (str): First symbol. s2 (str): Second symbol. group_by (bool, optional): Whether to group the results, by default True. use_close (bool, optional): Whether to use ‘Close’ prices (default is True). Returns: PortfolioAnalyzer: Portfolio analyzer object with column-stacked strategy results. ``` -------------------------------- ### Plot Cash Report (Python) Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/analyzers/base Plots the cash balance of the portfolio over a specified period. It accepts start and end dates and allows for additional plot-specific keyword arguments for customization. ```Python plot_cash_report( self, start: str | pandas._libs.tslibs.timestamps.Timestamp = None, end: str | pandas._libs.tslibs.timestamps.Timestamp = None, **plot_kwargs, ) ‑> vectorbtpro.utils.figure.FigureWidget Plot the cash balance of the portfolio. Parameters: | Name | Type | Default | Description | | --- | --- | --- | --- | | `start` | `str` | `None` | The start date. Defaults to `None`. | | `end` | `str` | `None` | The end date. Defaults to `None`. | | `plot_kwargs` | `tp.Kwargs` | `--` | Additional plot keyword arguments. | Returns: | Type | Description | | --- | --- | | `vbt.FigureWidget` | Figure widget of the cash balance. | ``` -------------------------------- ### Portfolio Composer Class API Source: https://systematica.mintlify.app/api-reference/systematica/portfolio/composers/base Documentation for Systematica portfolio composer classes, covering class variables and the 'run' method. Class variables define model parameters and portfolio simulation arguments. The 'run' method executes the composer with specified data, symbols, and portfolio configurations, returning a PortfolioAnalyzer. ```APIDOC Class Variables: model_name: str Name of the model to use. Should match to a model in systematica.api.models. portfolio_params: Dict[str, Any] Additional keyword arguments for portfolio simulation. model_params: Dict[str, Any] A dictionary of optional keyword arguments needed to compute the model. Method: run Signature: run( self, data: vectorbtpro.data.base.Data, s1: str, s2: str, portfolio_kwargs: Dict[str, Any], **kwargs, ) -> systematica.portfolio.analyzers.base.PortfolioAnalyzer Description: Run the portfolio composer with the specified data. Parameters: data: vbt.Data Vector BT data object containing the input data. s1: str First symbol or identifier for the data. s2: str Second symbol or identifier for the data. portfolio_kwargs: tp.Kwargs Keyword arguments for portfolio configuration. kwargs: tp.Kwargs Additional keyword arguments passed to the model. Returns: PortfolioAnalyzer Portfolio analyzer instance containing the results of the composition. ```