8. Operator class
The Operator class, used to create Operator objects, the core object of qteasy.
Operator is a strategy container. It contains a series of trading strategies, stores the historical data required by each trading strategy, and can invoke all trading strategies to generate trading signals. At the same time, it mixes the signals generated by all trading strategies according to the saved rules to form a final set of trading signals—just like a trader’s behavior in real trading.
To create an Operator object, you need to give a set of trading strategies and set the trader’s trading and signaling modes, which are the most important attributes of the Operator object and together determine the trader’s behavioral pattern:.
- class qteasy.Operator(strategies: Optional[Union[str, BaseStrategy, type, list[Union[str, qteasy.strategy.BaseStrategy, type]]]] = None, *, name: Optional[str] = None, signal_type: str = 'pt', op_type: str = 'batch', group_merge_type: str = 'None', run_freq: str = 'd', run_timing: str = 'close')[source]
The core “trader” object in qteasy, used to hold a strategy group and generate trading signals on a unified schedule.
Operator is responsible for managing one or more strategy groups, preparing and caching the historical data required for execution, calling each strategy to generate signals according to the run frequency and timing, and merging signals into final trading instructions according to intra-group/inter-group merge rules. It can be used for backtesting, optimization, and live trading. For architectural details such as the relationship between Operator and Strategy / Group and the single source of truth for run_freq / run_timing, see the “Operator / Strategy / Group Architecture” section of the documentation.
- add_strategies(strategies: Union[str, list[Union[str, qteasy.strategy.BaseStrategy, type]]], run_freq: str = 'd', run_timing: str = 'close', **kwargs: Any)[source]
Add multiple Strategy trading strategies to the Operator object.
With this method, it is not possible to modify the basic properties of a trading strategy while adding a trading strategy. The input parameter strategies can be either a list or a comma-separated string. The elements of the list can be either strings representing the types of built-in strategies or a specific strategy object. The strings and strategy objects can be given as a mix.
- Parameters:
strategies (stg or list of str or list of Strategy) – The name of the trading strategy or the trading strategy object
run_freq (str, optional) – run_freq is the strategy’s execution frequency; it can be None, meaning no execution frequency is specified.
run_timing (str, optional) – run_timing is the strategy’s execution timing; it can be None, meaning no execution timing is specified.
**kwargs (Any) – Properties shared by the added trading strategies, such as run_timing, run_freq, window_length, use_latest_data_cycle, freq, asset_type, data_type_ids, etc. (passed into add_strategy).
- Return type:
None
Examples
>>> op = Operator() >>> op.add_strategies(['dma', 'macd']) >>> op.strategies [RULE-ITER(DMA), RULE-ITER(MACD)]
- add_strategy(stg: Union[str, BaseStrategy, type, tuple, list, Any], run_freq: str = 'd', run_timing: str = 'close', **kwargs)[source]
Add a strategy to the operator object.
If you call this method to add a trading strategy to Operator, you can modify or specify the basic properties of the trading strategy at the same time as adding it.
- Parameters:
stg (str or int or Strategy) – The trading strategy to be added, which can also be the strategy id or strategy name of the built-in trading strategy
run_freq (str, Optional) – run_freq is the strategy’s execution frequency; it can be None, meaning no execution frequency is specified.
run_timing (str, Optional) – run_timing is the strategy’s execution timing; it can be None, meaning no execution timing is specified.
kwargs – Any valid strategy attribute can be assigned directly when adding the strategy. You must explicitly specify the name of the attribute to modify, including - pars: dict or tuple, strategy tunable parameters - opt_tag: int, strategy optimization tag - stg_type: int, strategy type - par_count: int, number of strategy parameters - par_types: list, strategy parameter types - par_ranges: list, strategy parameter ranges - data_freq: str, strategy data frequency - window_length: int, strategy window length - run_freq: str, strategy sampling frequency - data_types: list, strategy data types - data_type_id: str, strategy data type ID (used for update_data_types) - freq: str or list or dict, frequency of the data type (modifying it will replace the corresponding DataType) - asset_type: str or list or dict, asset type of the data type (modifying it will replace the corresponding DataType) - group: str, strategy run timing - use_latest_data_cycle: bool, whether the strategy uses the latest data cycle
- Return type:
None
Examples
>>> op = Operator() >>> op.add_strategy('dma', opt_tag=1, pars=(50, 10, 20)) >>> op.strategies [RULE-ITER(DMA)] >>> op.strategies[0].opt_tag 1 >>> op.strategies[0].par_values (50, 10, 20)
- property all_dynamic_dtypes
Return the collection of “legacy” dynamic data types in the operator; deprecated, always returns empty.
Process data is now accessed uniformly via get_data(‘proc.xxx’) and is no longer declared via DataType. This attribute is kept only for caller compatibility and returns an empty dict.
- property all_strategy_data_types
Returns the set of backtest price types and trade list history data types for all strategies of the operator object from the object.
- check_dynamic_data()[source]
Check whether the operator object contains dynamic data types (i.e., historical data that depends on trading results) to generate trading signals.
If any strategy uses get_data(‘proc.xxx’) in realize(), it is considered to depend on dynamic process data and must use the dynamic backtesting branch.
- create_data_windows()[source]
Create data windows for each strategy and its data types. Also create data window indices for each strategy and its data types. Data window indices are created according to group schedules.
- disable_tracing()[source]
Disable tracking for all strategies in the Operator object.
After disabling tracking, the Operator object will not record debugging information during execution, thereby improving runtime efficiency.
- Return type:
None
- property empty
Check if operator contains any policies
- enable_tracing()[source]
Enable tracking for all strategies in the Operator object
After enabling tracking, the Operator object will record more debugging information during execution, making subsequent analysis and debugging easier.
- Return type:
None
- get_blender(group_name=None)[source]
Return the long/short mask blender in the operator object. If group_name is not specified, output the complete blender dictionary.
- Parameters:
group_name (str) – An available group_name
- Returns:
blender – If group_name is None, return a dictionary containing the blenders for all run_timing values. If group_name is not None, return a list containing the blenders for that run_timing.
- Return type:
dict or list
- get_group(group_idx: Union[str, int]) Group[source]
Get a Group object by group_idx, equivalent to the get_group_by_id method.
- Parameters:
group_idx (int or str) – The index number of the strategy group
- Return type:
Examples
>>> op = Operator('dma, macd') >>> op.get_group(0) Group(name=Group_1, members=[RULE-ITER(DMA), RULE-ITER(MACD)]) >>> op.get_group_by_id('Group_1') Group(name=Group_1, members=[RULE-ITER(DMA), RULE-ITER(MACD)])
- get_group_by_id(group_id: Union[str, int]) Group[source]
Get a Group object by group_id
- Parameters:
group_id (str or int) – The name ID or index number of the strategy group
- Return type:
Notes
1,当group_id为int时,返回的是序号为group_id的策略组 2,当group_id为str时,返回的是ID为group_id的组
Examples
>>> op = Operator('dma, macd') >>> op.get_group_by_id(0) Group(name=Group_1, members=[RULE-ITER(DMA), RULE-ITER(MACD)]) >>> op.get_group_by_id('Group_1') Group(name=Group_1, members=[RULE-ITER(DMA), RULE-ITER(MACD)])
- get_max_window_length_by_dtype_id(dtype: str) int[source]
Compute and return the maximum window length for a certain datatype of the operator object.
- Parameters:
dtype (str) – The dtype_id of the historical data type to query.
- Return type:
int, operator对象中所有子策略中某个dtype最长的窗口长度
Given a share (a string) return its corresponding index
- Parameters:
share (str) – share is a string representing the stock code.
- Returns:
Returns an integer representing the index of share.
- Return type:
int
- get_signal_count(steps=None) int[source]
Get the number of trading signals generated by all strategy groups in the current run schedule.
- Parameters:
steps (list of int, optional) – If steps is provided, only compute the number of trading signals for those steps. If None, compute the number of trading signals for all steps.
- Returns:
int
- Return type:
交易信号的数量
- get_stg(stg_id)[source]
Getting a strategy object, another use of Operator[item].
- Parameters:
stg_id (int or str) – Name or serial number of the strategy
- Return type:
Strategy, 子策略
Notes
1, when stg_id is int, the first stg_id strategy is returned 2, when stg_id is str, the strategy with name stg_id is returned 3, when stg_id does not match, the last strategy is returned
Examples
>>> op = Operator('dma, macd') >>> op[0] RULE-ITER(DMA) >>> op['dma'] RULE-ITER(DMA) >>> op[999] RULE-ITER(MACD) >>> op['invalid_strategy_name'] UserWarning: No such strategy with ID (invalid_strategy_name)!
See also
- get_strategies_by_group(group_id: str)[source]
Returns the strategy object in the operator object, with timing as an optional parameter, and if timing is given, returns the trading strategy that uses that timing.
- Parameters:
group_id (str) – An available timing, by default None
- get_strategy_by_id(stg_id)[source]
Getting a strategy object, another use of Operator[item].
- Parameters:
stg_id (int or str) – Name or serial number of the strategy
- Return type:
Strategy, 子策略
See also
- get_strategy_count_by_group(group_id: str)[source]
Return the total number of strategies in strategy group group_id
- get_strategy_id_pairs()[source]
Returns a generator containing all strategy and id pairs in op:
- Return type:
generator, 包含op中所有strategy和id对
Examples
>>> op = Operator('dma, macd') >>> list(op.get_strategy_id_pairs()) [('dma', RULE-ITER(DMA)), ('macd', RULE-ITER(MACD))]
- get_strategy_names_by_group(group_id: str)[source]
Return all strategy names in strategy group group_id
- property group_ids
Returns the runtime type of all strategy children of the operator object.
- property group_merge_type
Return the strategy combination method of the operator object
- property group_names
Returns the runtime type of all strategy children of the operator object.
- property groups
Return all strategy groups of the operator, as a dictionary indexed by strategy group name
- property groups_by_index
Return all strategy groups of the operator, as a dictionary indexed by strategy group index
- info(verbose=False)[source]
Print information about the Operator object, including strategy groups, strategies within each group, strategy blending method, and so on.
If the strategy contains more information, some specific details of the strategy will also be printed.
- Parameters:
verbose (bool, Default False) – Whether to print detailed information about the strategies. If True, detailed information about the strategies will be printed.
- is_ready(tell_me_why: bool = False, raise_error: bool = False) bool[source]
Check whether Operator meets the minimum requirements needed to generate trading signals.
Typical ready conditions include: strategies have been mounted, each strategy group has configured a blender, and key fields such as historical data types and the run schedule are ready (more fine-grained validity checks are completed in subsequent steps).
- Parameters:
tell_me_why (bool, default False) – If the Operator object does not meet the ready conditions, whether to print the specific reason; not printed by default.
raise_error (bool, default False) – If the Operator object does not meet the ready conditions, whether to throw an exception; no exception is thrown by default.
- Return type:
bool, Operator对象是否已经准备好,可以开始生成交易信号
- property max_window_length
Compute and return the longest window length among all sub-strategies of the operator object. When preparing historical data for backtesting or optimization, use this to ensure there is enough historical data for the strategies to form.
- Return type:
int, operator对象中所有子策略中最长的窗口长度
- property op_data_freq: dict
Returns the sampling frequency of the data required by all strategy subobjects of the operator object Gives this value if the data_freq is the same for all strategies, otherwise gives a sorted list
- property op_data_type_count
Returns the number of historical data types required by the operator object to generate a list of transactions
- property op_data_type_ids
Return the IDs of the historical data types required by all strategy sub-objects of the operator object.
- property op_data_types
Return the historical data type objects required by all strategy sub-objects of the operator object.
- property op_signal_index: Optional[Index]
Return the index at which the operator object generates trading signals.
- property op_signal_types: list
The signal_types of the generated trade list. Because the generated trading signals may be produced by different strategy groups, and different strategy groups have their own signal types (PT/ST/VT), each row of trading signals may have a different trading signal type. This property returns a list containing the signal_list of each row in op_signal_list.
- Return type:
list, 生成的交易清单的price_types,回测交易价格类型
- property op_type
Returns the run type of the operator object
- property opt_space_par
Return the parameter space information of sub-strategies participating in optimization, used to construct
Space.Iterate over each sub-strategy’s
opt_tag, aggregate fields such aspar_range/par_types, and output the(ranges, types)tuple, which can be used directly as input to constructSpace.- Returns:
Two lists,
rangesandtypes, corresponding to the value ranges and type markers of each optimization dimension involved, respectively.- Return type:
tuple[list, list]
- property opt_tags
Returns the optimized type labels of all strategies The return value of this attribute is a list of the optimized type labels of all trading strategies in order
- prepare_data_buffer(*, start_date: Union[str, Timestamp], end_date: Union[str, Timestamp], data_package: dict) None[source]
Prepare the data buffer and load all data required by all strategies.
The data buffer is a dictionary whose keys are data types and whose values are the corresponding data DataFrames. The input parameters include the start and end dates of the data package. Based on these two dates, the corresponding time range is sliced from each DataFrame in the data package and saved into the data buffer.
When saving the data buffer, also check and ensure the data has enough lookback to create the sliding window.
- Parameters:
start_date (str or pd.Timestamp) – The start date of the data. Defaults to None, meaning start from the data package’s initial date.
end_date (str or pd.Timestamp) – The end date of the data. Defaults to None, meaning up to the data package’s end date.
data_package (dict[]) – A dictionary containing all required data, with keys as data types and values as the corresponding data DataFrames. For example: {‘price’: price_df, ‘volume’: volume_df, …}. The index of each DataFrame is timestamps, and the columns are different instrument codes.
- prepare_dynamic_data_buffer(*, trade_records: ndarray, trade_prices: ndarray, own_cashes: ndarray, available_cashes: ndarray, holding_positions: ndarray, available_positions: ndarray) None[source]
Reserved interface: process data has been injected uniformly via proc.*; this method no longer performs any logic.
- prepare_running_schedule(start_date=None, end_date=None, **kwargs) None[source]
Running Schedule is the strategy run schedule, containing information such as each strategy’s run time and frequency.
Before running the strategy, you must first prepare the run schedule. This schedule is determined by the runtime timing parameters of each strategy group in the trader. The run schedule includes N rows, where each row represents a point in time. The number of columns equals the number of strategy groups, and each cell indicates whether that strategy group runs at that time point: 0 means do not run, 1 means run.
In this method, the values of the following two attributes will be set: - group_schedules: a dictionary whose keys are strategy group names and whose values are the run schedule for that group - group_timing_table: a DataFrame containing the run schedules of all strategy groups
- Parameters:
start_date (str or pd.Timestamp, optional) – Start date. Defaults to None, meaning start from the data source’s initial date.
end_date (str or pd.Timestamp, optional) – End date, default is None, meaning up to the end date of the data source
kwargs (dict, optional) – Other parameters, including those required during the process of generating the trading time series, such as trading start time, end time, etc. See the parameter description of the qteasy.trading_util.trade_time_index() function for details.
- Return type:
None
- property ready
Property, an alternative way of writing operator.is_ready()
- remove_strategy(id_or_pos: Optional[Union[str, int]] = None) None[source]
Removes a trading strategy from the Operator object, either by giving the strategy id or the strategy’s position in the Operator.
- reset()[source]
Reset the Operator object’s running state so that it can start generating trading signals again.
Notes
This method resets all runtime data of the Operator object, including historical data caches, data window views, data window indexes, trading signals, etc. After the reset, the Operator object can start generating trading signals again.
Examples
>>> op = Operator('dma, macd') >>> op.reset()
- run(config, datasource=None, logger=None)[source]
Run the operator according to the configuration parameters, supporting both live trading and backtesting modes.
- Parameters:
config (dict) – Run configuration parameter dictionary
datasource (DataSource, optional) – Data source object. Defaults to None, meaning the global default data source is used.
logger (Logger, optional) – Logger object. Defaults to None, meaning no logger is used.
- Returns:
backtest_result – If the run mode is backtesting, returns the backtest result object containing various backtest result data. If the run mode is live trading, no result is returned.
- Return type:
BacktestResult, optional
- run_backtest(config, datasource=None, logger=None) dict[source]
Run the operator in backtest mode, using historical data to backtest the trading strategy and generate backtest results.
- Parameters:
config (dict) – Backtest configuration parameter dictionary.
datasource (DataSource, optional) – Data source object. Defaults to None, meaning the global default data source is used.
logger (Logger, optional) – Logger object. Defaults to None, meaning no logger is used.
- Returns:
backtest_result – Backtest result object, containing various result data from the backtest.
- Return type:
BacktestResult
- run_live_trade(config, datasource=None, logger=None)[source]
Run the operator in live trading mode.
- run_optimization(config, datasource=None, logger=None) dict[source]
Run the operator in optimization mode.
- run_prediction(config, datasource=None, logger=None) dict[source]
Run the operator in paper trading mode.
- run_strategies(steps: Iterable) Iterable[source]
Run the Operator and return the run result; the semantics are close to the keyword-argument form passed to
qt.run(self, ...).- Parameters:
steps (Iterable) – An iterable object containing the indexes of the steps to run.
- Yields:
generator ((signal_type, step_index, signal)) – Returns a generator containing the trading signal for each step. signal_type: str, the signal type of the strategy group step_index: int, the index of the current step signal: np.ndarray, the trading signal, an array of numbers whose meaning differs under different signal_type modes.
- run_strategy(step_index) Generator[Union[tuple[Any, int, Any], tuple[Optional[Any], int, Union[int, Any]]], Any, None][source]
Run all strategy groups for the current step and generate trading signals.
This function is a generator function that returns the trading signals of each strategy group at the current step.
- Parameters:
step_index (int) – The index of the current step, indicating its position in the run schedule.
- Returns:
generator – Returns a generator containing the trading signal of each strategy group at the current step. signal_type: str, the signal type of the strategy group step_index: int, the index of the current step signal: np.ndarray, the trading signal, an array of numbers whose meaning differs under different signal_type modes.
- Return type:
(signal_type, step_index, signal)
- set_blender(blender: Union[str, list[str], dict[str, str]], group_id: Optional[str] = None)[source]
Unified entry for setting blender properties
- Parameters:
blender (str or list of str or dict of str, optional) – A valid blended expression for trading signals, when group is None, can accept a list as the argument and set the blended expression for all groups at once.
group_id (str, optional) – When a strategy group id is specified, only that group is updated; when
None, all strategy groups are updated. In the latter case, ifblenderis a string, it means all groups use the same expression; if it is a list, set items one by one in group order, and if the length is insufficient, reuse the last item.
- Return type:
None
- Raises:
TypeError – If the given price_type is not the correct one
Warning
If the given price_type does not exist, then give a warning and return the
Examples
>>> op = Operator() >>> op.add_strategy('dma', run_timing='close') # 添加策略时指定run_timing,自动分配到第一个策略组Group_1 >>> op.add_strategy('trix', run_timing='close') # 添加策略时指定run_timing,自动分配到第一个策略组Group_1 >>> op.add_strategy('macd', run_timing='open') # 添加策略时指定run_timing,自动分配到第二个策略组Group_2 >>> op.add_strategy('bband', run_timing='open') # 添加策略时指定run_timing,自动分配到第二个策略组Group_2
>>> # 设置策略组1的混合模式 >>> op.set_blender('s0+s1', 'Group_1') >>> op.get_blender() >>> {'Group_1': ['+', 's1', 's2']}
>>> # 给所有的交易价格策略设置同样的混合表达式 >>> op.set_blender('s0 + s1') >>> op.get_blender() >>> {'Group_1': ['+', 's2', 's1'], 'Group_2': ['+', 's2', 's1']}
>>> # 通过一个列表给不同的策略组设置不同的混合表达式(策略组按顺序排列) >>> op.set_blender(['s1 + s2', 's3*s4'], None) >>> op.get_blender() >>> {'close': ['+', 's2', 's1'], 'open': ['*', 's4', 's3']}
- set_group_parameters(group: Union[str, int], run_timing: Optional[str] = None, run_freq: Optional[str] = None, signal_type: Optional[str] = None, blender_str: Optional[str] = None, **kwargs)[source]
Set or modify the parameters of a strategy group :param group: the ID of the strategy group :type group: str :param run_timing: the execution timing of the strategy group; when modifying the execution timing, also modify the execution timing of all trading strategies in the group :type run_timing: str, optional :param run_freq: the execution frequency of the strategy group; when modifying the execution frequency, modify the strategy group :type run_freq: str, optional :param signal_type: the trading signal type of the strategy group; defaults to ‘PT’, i.e., percentage position target :type signal_type: str, optional :param blender_str: the trading signal blending expression of the strategy group; can be a string or a list of strings :type blender_str: str, optional :param kwargs: other parameters; can be any valid strategy group parameters, such as group_name, run_timing, run_freq, etc. :type kwargs: dict, optional
- Return type:
None
- Raises:
TypeError – If group is not of type string or integer.
ValueError – If group does not exist or cannot be found.
- set_opt_par_values(par_values)[source]
Optimizer-side entry point: slice a parameter vector by each sub-strategy
opt_tagand write it back.Unlike
set_parameter, this method targets an optimization workflow where “one vector corresponds to multiple strategy sub-blocks”; the caller must ensure thatpar_valuesis consistent with the flattening order ofopt_space_par.- Parameters:
par_values (tuple) – The parameter tuple corresponding to the optimizer’s current candidate point.
- Return type:
None
Notes
Internally calls
Strategy.update_par_values; no parameter validity checks are performed here.
- set_parameter(stg_id: Union[str, int], pars: Optional[Union[Parameter, tuple, list, dict]] = None, opt_tag: Optional[int] = None, data_types: Optional[Union[DataType, list[qteasy.datatypes.DataType], dict[str, qteasy.datatypes.DataType]]] = None, data_type_id: Optional[str] = None, window_length: Optional[Union[int, tuple[int, ...], list[int], dict[str, int]]] = None, use_latest_data_cycle: Optional[Union[bool, list[bool], tuple[bool, ...], dict[str, bool]]] = None, freq: Optional[Union[str, list[str], tuple[str, ...], dict[str, str]]] = None, asset_type: Optional[Union[str, list[str], tuple[str, ...], dict[str, str]]] = None, par_values: Optional[Union[tuple, list, dict[str, Any]]] = None, par_range: Optional[Union[tuple, list, dict[str, tuple]]] = None, run_freq: Optional[str] = None, run_timing: Optional[str] = None, **kwargs)[source]
Unified entry for setting policy parameters, stg_id identifies the specific member policy that accepts the parameter, assigns the policy parameter given in the function parameter to the corresponding policy
- Parameters:
stg_id (str,) – The name (ID) of the policy to locate the policy that requires parameter modification based on the ID
pars (tuple or dict, optional) – Adjustable policy parameters, in the format of tuple When creating a policy, you can set some of the policy parameters as “adjustable parameters”, the value range of these parameters can be adjusted in the process of policy optimization, by adjusting the combination of these parameters, you can find the optimal combination of policy parameters, so as to find the optimal policy.
opt_tag (int, optional) – Optimization type: 0: do not participate in the optimization, do not adjust the adjustable parameters of the strategy during the strategy optimization process 1: participate in the optimization, actively adjust the strategy parameters according to the optimization algorithm during the strategy optimization process in order to find the best combination of parameters 2: participate in the optimization as an enumeration type, only select the optimal combination of parameters from the given combination of parameters during the strategy optimization process
data_types (DataType or list of DataType or dict of str, optional) – The data type of historical data required for strategy computation; if provided, update the parameters for this data type.
data_type_id (str, optional) – The ID of the data type of historical data required for strategy computation; providing this ID indicates updating the parameters for this data type.
window_length (int or list of int or tuple of int,) – Window length: the length of the front view window calculated by the policy
use_latest_data_cycle (bool or list of bool or tuple of bool,) – Whether to use the latest data period.
freq (str or list of str or tuple of str or dict of str,) – The frequency of the data type; if provided, replace the corresponding item with the new DataType (dtype_id will change accordingly).
asset_type (str or list of str or tuple of str or dict of str,) – The asset type of the data type; if provided, replace the corresponding item with the new DataType (dtype_id will change accordingly).
par_values (tuple or list,) – The specific values of the strategy parameters.
par_range (tuple or list, or dict of tuples,) – The value range of the strategy parameters.
run_freq (str, optional) – If this parameter is provided, modify the strategy’s run frequency. Changing the run frequency will cause the strategy to be removed from its strategy group and reassigned to a new strategy group.
run_timing (str, optional) – If this parameter is provided, modify the strategy’s execution timing. Changing the execution timing will cause the strategy to be removed from its strategy group and reassigned to a new strategy group.
kwargs (dict,) – Other parameters
Set the list of trading instruments for the operator object.
- Parameters:
shares (list of str) – A list of strings representing the list of trading instrument symbols
- Return type:
None
- property strategies
Returns all Strategy objects of the operator object as a list.
- property strategy_count
Returns the number of all Strategy objects in the operator object.
- property strategy_group_count
Calculate the number of all trading strategy groups in the operator object
- Return type:
int, operator对象中所有交易策略组的数量
- property strategy_groups
Return all strategy groups of the operator, as a dictionary indexed by strategy group name
- property strategy_ids
Returns the IDs of all trading strategy objects in the operator object.
- view_blender(group: Optional[Union[str, int]] = None) Union[dict, str][source]
- Returns a human-readable version of the multi-hollow mask mixer in the operator object, i.e., a more human-readable version of the original blender string.
Version that replaces strategy codes such as s0 with strategy IDs and formats appropriately. If the group parameter is not provided, return the blender-readable version for all strategy groups.
- Parameters:
group (str) – An available group ID or index
Group strategy group class
- class qteasy.group.Group(name: str, signal_type: str = 'pt', blender: Optional[str] = None, run_freq: str = 'd', run_timing: str = 'close')[source]
A strategy group containing multiple strategy members, defining properties such as the member strategies’ signal type, blending method, run frequency, and timing.
- add_strategy(strategy: BaseStrategy) None[source]
Add a strategy to the group; the strategy will become a member of the group.
The added strategy must be an instance of BaseStrategy and must not already be a member of this group; otherwise, a ValueError will be raised. The added strategy’s group_id will be set to this group’s group_id so that the strategy can access information about its associated group.
- Parameters:
strategy (BaseStrategy) – The strategy instance to add to the group; it must be an instance of a subclass of BaseStrategy.
- Return type:
None
- Raises:
ValueError – If strategy is already a member of the group, raise ValueError indicating that the strategy already exists in the group.
TypeError – If strategy is not an instance of BaseStrategy, raise TypeError indicating an invalid strategy type.
- blend(signals: Iterable)[source]
Use the current blender to blend signals from strategies in the same group into a single set of signals.
- clear_strategies()[source]
Clear all strategies in the group; all member strategies will no longer be members of this group.
- property group_id
The group’s ID, the same as name, for compatibility with Strategy.group_id.
- remove_strategy(strategy: BaseStrategy)[source]
Remove a strategy from the group; the strategy will no longer be a member of the group.
The removed strategy must be a member of this group; otherwise, a ValueError will be raised. The removed strategy’s group_id will be set to None to indicate that it no longer belongs to any group.
- Parameters:
strategy (BaseStrategy) – The strategy instance to remove from the group; it must be a member of the group.
- Return type:
None
- Raises:
ValueError – If strategy is not a member of the group, raise ValueError indicating that the strategy is not in the group.
TypeError – If strategy is not an instance of BaseStrategy, raise TypeError indicating an invalid strategy type.