Built-in Strategies

There are more than 70 built-in trading strategies in qteasy, which users can easily use directly. At the same time, qteasy provides a set of trading strategy combination mechanisms, and users can combine multiple simple trading strategies into a more complex trading strategy. The combination method of the strategy can be flexibly set. After combining multiple simple trading strategies into a complex strategy, the strategy optimization tool can also be used to search for the best parameters of the entire complex strategy.

In this tutorial, you will learn how to use built-in trading strategies, how to combine strategies, how to set combination rules to achieve complex strategies, and how to optimize strategies.

Built-in Strategies

qt.get_built_in_strategy(id)

qt.built_in_list(stg_id=None)

Output of the above three methods is the same, all of them list all built-in trading strategies with a dict, where the key is the ID of the trading strategy and the value is the trading strategy object. If stg_id is given, the detailed information of the specified trading strategy is printed. For example:

# 获取内置交易策略的清单
stg_list = qt.built_ins('dma')

Following information is printed:

DMA择时策略

策略参数:
    s, int, 短均线周期
    l, int, 长均线周期
    d, int, DMA周期
信号类型:
    PS型:百分比买卖交易信号
信号规则:
    在下面情况下产生买入信号:
    1, DMA在AMA上方时,多头区间,即DMA线自下而上穿越AMA线后,输出为1
    2, DMA在AMA下方时,空头区间,即DMA线自上而下穿越AMA线后,输出为0
    3, DMA与股价发生背离时的交叉信号,可信度较高

策略属性缺省值:
默认参数:(12, 26, 9)
数据类型:close 收盘价,单数据输入
采样频率:天
窗口长度:270
参数范围:[(10, 250), (10, 250), (8, 250)]
策略不支持参考数据,不支持交易数据

The built-in trading strategy can be obtained directly by the ID in qteasy

Apart from using qt.get_built_in_strategy() to get the trading strategy, the built-in trading strategy ID can also be passed as a parameter when creating the Operator object to create the trading strategy directly.

# 获取内置交易策略的ID
strategy_ids = qt.built_ins().keys()
print(list(strategy_ids)[:10])
['crossline', 'macd', 'dma', 'trix', 'cdl', 'bband', 's-bband', 'sarext', 'ssma', 'sdema']
# 使用策略ID获取交易策略
stg = qt.get_built_in_strategy('trix')
# 显示策略的相关信息
stg.info()
Strategy_type:      RuleIterator
Strategy name:      TRIX
Description:        TRIX strategy, determine long/short position according to triple exponential weighted moving average prices
Strategy Parameter: (25, 125)

Strategy Properties     Property Value
---------------------------------------
Parameter count         2
Parameter types         ['int', 'int']
Parameter range         [(2, 50), (3, 150)]
Data frequency          d
Sample frequency        d
Window length           270
Data types              ['close']
# 通过策略ID直接生成Operator
op = qt.Operator(strategies='dma, macd')
# 通过op.get_stg或op[]获取交易策略
stg_dma = op.get_stg('dma')
stg_macd = op['macd']

# 查看两个交易策略的相关信息
stg_dma.info()
stg_macd.info()
Strategy_type:      RuleIterator
Strategy name:      DMA
Description:        Quick DMA strategy, determine long/short position according to differences of moving average prices with simple timing strategy
Strategy Parameter: (12, 26, 9)

Strategy Properties     Property Value
---------------------------------------
Parameter count         3
Parameter types         ['int', 'int', 'int']
Parameter range         [(10, 250), (10, 250), (10, 250)]
Data frequency          d
Sample frequency        d
Window length           270
Data types              ['close']

Strategy_type:      RuleIterator
Strategy name:      MACD
Description:        MACD strategy, determine long/short position according to differences of exponential weighted moving average prices
Strategy Parameter: (12, 26, 9)

Strategy Properties     Property Value
---------------------------------------
Parameter count         3
Parameter types         ['int', 'int', 'int']
Parameter range         [(10, 250), (10, 250), (10, 250)]
Data frequency          d
Sample frequency        d
Window length           270
Data types              ['close']

Following built-in trading strategies are supported by qteasy:

ID

Name

Description

crossline

TimingCrossline

Crossline timing strategy class, using the crossover of long and short moving averages to determine the long and short state
1. When the short moving average is above the long moving average and the distance is greater than l*m%, set the position target to 1
2. When the short moving average is below the long moving average and the distance is greater than l*m%, set the position target to -1
3. When the distance between the long and short moving averages is not greater than l*m%, set the position target to 0

macd

TimingMACD

MACD timing strategy class, using MACD moving average strategy to generate target position percentage:
1. When the MACD value is greater than 0, set the position target to 1
2. When the MACD value is less than 0, set the position target to 0

dma

TimingDMA

DMA timing strategy
1. When DMA is above AMA, it is a long position interval, that is, when the DMA line crosses the AMA line from bottom to top, the output is 1
2. When DMA is below AMA, it is a short position interval, that is, when the DMA line crosses the AMA line from top to bottom, the output is 0

trix

TimingTRIX

TRIX timing strategy, using the triple smoothed exponential moving average price of stock prices for long and short judgment:
Calculate the triple smoothed exponential moving average price TRIX of the price, and then calculate the moving average of M-day TRIX:
1. When TRIX is above MATRIX, set the position target to 1
2. When TRIX is below MATRIX, set the position target to -1

cdl

TimingCDL

CDL timing strategy, find the cdldoji pattern that meets the requirements in the K-line chart
Search for the cdldoji pattern that appears in the historical data window (matching degree between 0 and 100), add it up /100, and calculate the equivalent cdldoji matching quantity, using the matching quantity as the trading signal.

bband

TimingBBand

Bollinger Band trading strategy, determines long and short positions based on the relationship between stock prices and the upper and lower bands of the Bollinger Bands. Trading signals are generated when the price crosses above or below the upper and lower bands. The moving average type of the Bollinger Bands is not selectable<br

s-bband

SoftBBand

Bollinger Band progressive trading strategy, determines long and short positions based on the relationship between stock prices and the upper and lower bands of the Bollinger Bands. The trading signal is not generated all at once, but is gradually increased for buying and selling. Calculate BBAND, check if the price exceeds the upper or lower band of BBAND:
1. When the price is greater than the upper band, a 10% proportion buy trading signal is generated every day
2. When the price is lower than the lower band, a 33% proportion sell trading signal is generated every day

sarext

TimingSAREXT

SAR strategy, when the indicator is greater than 0, a buy signal is issued, and when the indicator is less than 0, a sell signal is issued.

ssma

SCRSSMA

Single moving average crossover strategy - SMA moving average (simple moving average): set the position ratio according to the relative position of the stock price and the SMA moving average

sdema

SCRSDEMA

Single moving average crossover strategy - DEMA moving average (double exponential smoothing moving average): set the position ratio according to the relative position of the stock price and the DEMA moving average

sema

SCRSEMA

Single moving average crossover strategy - EMA moving average (exponential smoothing moving average): set the position ratio according to the relative position of the stock price and the EMA moving average

sht

SCRSHT

Single moving average crossover strategy - HT (Hilbert transform instantaneous trend line): set the position ratio according to the relative position of the stock price and the HT line

skama

SCRSKAMA

Single moving average crossover strategy - KAMA moving average (Kaufman adaptive moving average): set the position ratio according to the relative position of the stock price and the KAMA moving average

smama

SCRSMAMA

Single moving average crossover strategy - MAMA moving average (MESA adaptive moving average): set the position ratio according to the relative position of the stock price and the MAMA moving average

st3

SCRST3

Single moving average crossover strategy - T3 moving average (triple exponential smoothing moving average): set the position ratio according to the relative position of the stock price and the T3 moving average

stema

SCRSTEMA

Single moving average crossover strategy - TEMA moving average (triple exponential smoothing moving average): set the position ratio according to the relative position of the stock price and the TEMA moving average

strima

SCRSTRIMA

Single moving average crossover strategy - TRIMA moving average (triple exponential smoothing moving average): set the position ratio according to the relative position of the stock price and the TRIMA moving average

swma

SCRSWMA

Single moving average crossover strategy - WMA moving average (weighted moving average): set the position ratio according to the relative position of the stock price and the WMA moving average

dsma

DCRSSMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the SMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

ddema

DCRSDEMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the DEMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dema

DCRSEMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the EMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dkama

DCRSKAMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the KAMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dmama

DCRSMAMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the MAMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dt3

DCRST3

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the T3 moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dtema

DCRSTEMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the TEMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dtrima

DCRSTRIMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the TRIMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

dwma

DCRSWMA

Double moving average crossover strategy - SMA moving average (simple moving average):
Generate fast and slow moving averages based on the WMA moving average calculation rules, and set the position ratio according to the relative position of the fast and slow moving averages

slsma

SLPSMA

Slope trading strategy - SMA moving average (simple moving average):
Generate moving averages based on the SMA calculation rules, and set the position ratio target according to the slope of the moving average

sldema

SLPDEMA

Slope trading strategy - DEMA moving average (double exponential smoothing moving average):
Generate moving averages based on the DEMA calculation rules, and set the position ratio target according to the slope of the moving average

slema

SLPEMA

Slope trading strategy - EMA moving average (exponential smoothing moving average):
Generate moving averages based on the EMA calculation rules, and set the position ratio target according to the slope of the moving average

slht

SLPHT

Slope trading strategy - HT moving average (Hilbert transform - instantaneous trend line):
Generate moving averages based on the HT calculation rules, and set the position ratio target according to the slope of the moving average

slkama

SLPKAMA

Slope trading strategy - KAMA moving average (Kaufman adaptive moving average):
Generate moving averages based on the KAMA calculation rules, and set the position ratio target according to the slope of the moving average

slmama

SLPMAMA

Slope trading strategy - MAMA moving average (MESA adaptive moving average):
Generate moving averages based on the MAMA calculation rules, and set the position ratio target according to the slope of the moving average

slt3

SLPT3

Slope trading strategy - T3 moving average (triple exponential smoothing moving average):
Generate moving averages based on the T3 calculation rules, and set the position ratio target according to the slope of the moving average

sltema

SLPTEMA

Slope trading strategy - TEMA moving average (triple exponential smoothing moving average):
Generate moving averages based on the TEMA calculation rules, and set the position ratio target according to the slope of the moving average

sltrima

SLPTRIMA

Slope trading strategy - TRIMA moving average (triple exponential smoothing moving average):
Generate moving averages based on the TRIMA calculation rules, and set the position ratio target according to the slope of the moving average

slwma

SLPWMA

Slope trading strategy - WMA moving average (weighted moving average):
Generate moving averages based on the WMA calculation rules, and set the position ratio target according to the slope of the moving average

adx

ADX

ADX indicator (Average Directional Movement Index) stock selection strategy:
Based on the ADX indicator, determine the strength of the current trend, and generate trading signals based on trend strength
1. When ADX is greater than 25, the trend is judged to be upward, and the position ratio is set to 1
2. When ADX is between 20 and 25, it is judged to be a neutral trend, and the position ratio is set to 0
3. When ADX is less than 20, it is judged that the trend is downward, and the position ratio is set to -1

apo

APO

APO indicator (Absolute Price Oscillator) stock selection strategy:
Based on the APO indicator, determine the bullish and bearish trends of the current stock price movement, and generate trading signals based on the trend
1. When APO is greater than 0, it is judged to be a bull market trend, and the position ratio is set to 1
2. When ADX is less than 0, it is judged to be a bear market trend, and the position ratio is set to -1

aroon

AROON

AROON indicator stock selection strategy:
Output strong long/short and weak long/short based on the strength of the AROON indicator trend
1. When UP is above DOWN, output weak long
2. When UP is below DOWN, output weak short
3. When UP is greater than 70 and DOWN is less than 30, output strong long
4. When UP is less than 30 and DOWN is greater than 70, output strong short

aroonosc

AROONOSC

AROON Oscillator stock selection strategy:
When AROONOSC is greater than 0, it indicates that the price trend is upward, and conversely, the trend is downward. When the absolute value is greater than 50, it indicates a strong trend
1. When AROONOSC is greater than 0, output weak long
2. When AROONOSC is less than 0, output weak short
3. When AROONOSC is greater than 50, output strong long
4. When AROONOSC is less than -50, output strong short

cci

CCI

CCI (Commodity Channel Index) stock selection strategy:
CCI commodity channel index is used to determine whether the current stock price is in the oversold or overbought range. This strategy uses this indicator to generate investment position targets
1. When CCI is greater than 0, output weak long
2. When CCI is less than 0, output weak short
3. When CCI is greater than 50, output strong long
4. When CCI is less than -50, output strong short

cmo

CMO

CMO (Chande Momentum Oscillator) stock selection strategy:
CMO is a momentum indicator that fluctuates between -100 and 100. It is used to determine whether the current stock price is in the oversold or overbought range. This strategy uses this indicator to generate investment position targets
1. When CMO is greater than 0, output weak long
2. When CMO is less than 0, output weak short
3. When CMO is greater than 50, output strong long
4. When CMO is less than -50, output strong short

macdext

MACDEXT

MACDEXT (Extendec MACD) stock selection strategy:
This strategy uses the MACD indicator to generate position targets, but unlike the standard MACD, the fast, slow, and signal moving average types of MACDEXT can be selected
1. When hist>0, output long
2. When hist<0, output short

mfi

MFI

MFI (Money Flow Index) stock selection strategy:
MFI index is used to determine whether the stock price is in an overbought or oversold state. This strategy uses the MFI indicator to generate trading signals
1. When MFI>20, continuously generate 10% buy trading signals
2. When MFI>80, continuously generate 30% sell trading signals, and continue to sell the held stocks

di

DI

DI (Directory Indicator) trading strategy:
DI indicator includes negative directional indicator and positive directional indicator, which represent the strength of upward and downward price trends respectively. This strategy uses ±DI indicators to generate trading signals
1. When +DI > -DI, set the position target to 1
2. When +DI < -DI, set the position target to -1

dm

DM

DM (Directional Movement) trading strategy:
DM indicator includes negative directional movement indicator and positive directional movement indicator, which represent the upward and downward price trends respectively. This strategy uses ±DM indicators to generate trading signals
1. When +DM > -DM, set the position target to 1
2. When +DM < -DM, set the position target to -1
3. In other cases, set the position target to 0

mom

MOM

MOM (momentum indicator) trading strategy:
MOM indicator can be used to identify the strength of upward or downward price trends. When the current price is higher than the price N days ago, MOM is positive; otherwise, it is negative.
1. When MOM > 0, set the position target to 1
2. When MOM < 0, set the position target to -1
3. In other cases, set the position target to 0

ppo

PPO

PO (Percentage Price Oscillator) trading strategy:
PPO indicator represents the percentage difference between fast and slow moving averages, used to determine the price change trend. The calculation period and moving average type of long and short moving averages are both strategy parameters.
1. When PPO > 0, set the position target to 1
2. When PPO < 0, set the position target to -1
3. In other cases, set the position target to 0

rsi

RSI

RSI (Relative Strength Index) trading strategy:
RSI indicator measures the magnitude of recent price changes to determine whether the current stock is in an oversold or overbought state
1. When RSI > ulim, set the position target to 1
2. When RSI < llim, set the position target to -1
3. In other cases, set the position target to 0

stoch

STOCH

STOCH (Stochastic Indicator) trading strategy:
STOCH indicator measures the momentum of price changes, and the size of the momentum determines the price trend, generating proportional buy and sell trading signals.
1. When k > 80, a gradual sell signal is generated, selling 30% of the held shares each cycle
2. When k < 20, a gradual buy signal is generated, buying 10% of the total investment amount each cycle

stochf

STOCHF

STOCHF (Stochastic Fast Indicator) trading strategy:
STOCHF indicator measures the momentum of price changes. Similar to the STOCH strategy, it uses the fast stochastic indicator to determine the price trend and generate proportional buy and sell trading signals.
1. When k > 80, a gradual sell signal is generated, selling 30% of the held shares each cycle
2. When k < 20, a gradual buy signal is generated, buying 10% of the total investment amount each cycle

stochrsi

STOCHRSI

STOCHRSI (Stochastic Relative Strength Index) trading strategy:
STOCHRSI indicator measures the momentum of price changes. This indicator fluctuates between 0 and 1, indicating the relative strength of the price trend, and generates proportional buy and sell trading signals
1. When k > 0.8, a gradual sell signal is generated, selling 30% of the held shares each cycle
2. When k < 0.2, a gradual buy signal is generated, buying 10% of the total investment amount each cycle

ultosc

ULTOSC

ULTOSC (Ultimate Oscillator Indicator) trading strategy:
ULTOSC indicator calculates price momentum through three different time spans, and generates trading signals based on the deviation values between various momentum.
1. When ULTOSC > u, a gradual sell signal is generated, selling 30% of the held shares each cycle
2. When ULTOSC < l, a gradual buy signal is generated, buying 10% of the total investment amount each cycle

willr

WILLR

WILLR (William’s %R) trading strategy:
WILLR indicator is used to calculate whether the stock price is currently in the overbought or oversold range, and is used to generate trading signals
1. When WILLR > -l, a gradual sell signal is generated, selling 30% of the held shares each cycle
2. When WILLR < -u, a gradual buy signal is generated, buying 10% of the total investment amount each cycle

signal_none

SignalNone

Empty trading signal strategy: A strategy that does not generate any trading signals

sellrate

SellRate

Rate of change sell signal strategy: When the rate of change of the price exceeds the threshold, a sell signal is generated
1. When change > 0 and the daily increase is greater than change, a -1 sell signal is generated
2. When change < 0 and the daily decrease is greater than change, a -1 sell signal is generated

buyrate

BuyRate

Rate of change buy signal strategy: When the rate of change of the price exceeds the threshold, a buy signal is generated
1. When change > 0 and the daily increase is greater than change, a 1 buy signal is generated
2. When change < 0 and the daily decrease is greater than change, a 1 buy signal is generated

long

TimingLong

Simple timing strategy, fixed long position in the entire historical period

short

TimingShort

Simple timing strategy, fixed short position in the entire historical period

zero

TimingZero

Simple timing strategy, fixed empty position in the entire historical period

all

SelectingAll

Select all stocks in the historical stock pool, and the investment ratio is evenly distributed

select_none

SelectingNone

Select none of the stocks in the historical stock pool, and the investment position is 0

random

SelectingRandom

Select a number of stocks randomly in each historical segment according to the specified proportion (when p<1), or randomly select a specified number (when p>=1) of stocks to enter the investment portfolio, and the investment ratio is evenly distributed

finance

SelectingAvgIndicator

Select stocks based on the average value of financial indicators over a period of time, basic stock selection strategy: use the average value of historical indicators of stocks as stock selection factors. The factor sorting parameter can be passed in as a strategy parameter to change the data type of the strategy. Select stocks based on different historical data. The stock selection parameters can be passed in through pars.

ndaylast

SelectingNDayLast

Select stocks based on the price or data indicator of the stock N days ago as the stock selection factor

ndayavg

SelectingNDayAvg

Select stocks based on the average value of the price or data indicator of the stock over the past N days as the stock selection factor

ndayrate

SelectingNDayRateChange

Select stocks based on the percentage change of the price or data indicator of the stock over the past N days as the stock selection factor

ndaychg

SelectingNDayChange

Select stocks based on the change value of the price or data indicator of the stock over the past N days as the stock selection factor

ndayvol

SelectingNDayVolatility

Select stocks based on the stock price volatility over the past N days as the stock selection factor

If you need to see a detailed explanation of each built-in trading strategy, such as the meaning of strategy parameters and signal generation rules, you can check the Doc-string of each trading strategy:

For example:

qt.built_ins('Crossline')

You can see

Init signature: qt.built_in.TimingCrossline(pars:tuple=(35, 120, 0.02))
Docstring:     
crossline择时策略类,利用长短均线的交叉确定多空状态

策略参数:
    s: int, 短均线计算日期;
    l: int, 长均线计算日期;
    m: float, 均线边界宽度(百分比);
信号类型:
    PT型:目标仓位百分比
信号规则:
    1,当短均线位于长均线上方,且距离大于l*m%时,设置仓位目标为1
    2,当短均线位于长均线下方,且距离大于l*mM时,设置仓位目标为-1
    3,当长短均线之间的距离不大于l*m%时,设置仓位目标为0

策略属性缺省值:
默认参数:(35, 120, 0.02)
数据类型:close 收盘价,单数据输入
采样频率:天
窗口长度:270
参数范围:[(10, 250), (10, 250), (0, 1)]
策略不支持参考数据,不支持交易数据
File:           ~/Library/CloudStorage/OneDrive-Personal/Projects/PycharmProjects/qteasy/qteasy/built_in.py
Type:           type
Subclasses:     

Detailed information about built-in trading strategies can also be displayed in interactive Python environments such as ipython using ‘?’, for example:

>>> qt.built_in.SelectingNDayRateChange?

You can see:

Init signature: qt.built_in.SelectingNDayRateChange(pars=(14,))
Docstring:     
基础选股策略:根据股票以前n天的股价变动比例作为选股因子

策略参数:
    n: int, 股票历史数据的选择期
信号类型:
    PT型:百分比持仓比例信号
信号规则:
    在每个选股周期使用以前n天的股价变动比例作为选股因子进行选股
    通过以下策略属性控制选股方法:
    *max_sel_count:     float,  选股限额,表示最多选出的股票的数量,默认值:0.5,表示选中50%的股票
    *condition:         str ,   确定股票的筛选条件,默认值'any'
                                'any'        :默认值,选择所有可用股票
                                'greater'    :筛选出因子大于ubound的股票
                                'less'       :筛选出因子小于lbound的股票
                                'between'    :筛选出因子介于lbound与ubound之间的股票
                                'not_between':筛选出因子不在lbound与ubound之间的股票
    *lbound:            float,  执行条件筛选时的指标下界, 默认值np.-inf
    *ubound:            float,  执行条件筛选时的指标上界, 默认值np.inf
    *sort_ascending:    bool,   排序方法,默认值: False,
                                True: 优先选择因子最小的股票,
                                False, 优先选择因子最大的股票
    *weighting:         str ,   确定如何分配选中股票的权重
                                默认值: 'even'
                                'even'       :所有被选中的股票都获得同样的权重
                                'linear'     :权重根据因子排序线性分配
                                'distance'   :股票的权重与他们的指标与最低之间的差值(距离)成比例
                                'proportion' :权重与股票的因子分值成正比

策略属性缺省值:
默认参数:(14,)
数据类型:close 收盘价,单数据输入
采样频率:月
窗口长度:150
参数范围:[(2, 150)]
策略不支持参考数据,不支持交易数据
File:           ~/Library/CloudStorage/OneDrive-Personal/Projects/PycharmProjects/qteasy/qteasy/built_in.py
Type:           type
Subclasses:    

Multiple strategies and strategy combinations

In qteasy, an Operator trader object can run multiple trading strategies simultaneously. These trading strategies will extract their respective historical data independently during operation, generating different trading signals. These trading signals will be combined into a set of trading signals for unified execution.

With this feature, users can run multiple trading strategies with different focuses in one trader object. For example, one trading strategy monitors the stock price and generates selection signals based on the stock price, while the second trading strategy is responsible for monitoring the overall market trend and determining the overall position based on it. The third trading strategy is responsible for profit-taking and stop-loss, executing stop-loss at specific times. The final trading signal is mainly based on the first trading strategy but is restrained by the second strategy and can be completely controlled by the third strategy when necessary.

Or, users can easily formulate a ‘committee’ strategy, where multiple strategies independently make trading decisions in a comprehensive strategy. The final trading signal is determined by the ‘committee’ composed of all sub-strategies through voting, which can be done by simple majority, absolute majority, weighted voting results, etc.

In above mentioned strategy combination, each independent trading strategy is simple and easy to define, while their combination can play a greater role. At the same time, each sub-strategy is independent, allowing for free combination into complex comprehensive trading strategies. This can avoid the need to repeatedly develop strategies; instead, simply rearranging and redefining the combination of sub-strategies can quickly build a series of complex comprehensive trading strategies. This is believed to greatly improve the efficiency of building trading strategies and shorten the cycle. Time is money.

However, in an Operator object, the trading signals generated by different strategies may operate at different trading prices. For example, some strategies generate opening price trading signals, while others generate closing price trading strategies. Therefore, different trading price signals should not be mixed. But apart from that, as long as the trading prices are the same, all signals should be mixed together.

Blending trading signals means various operations or functions on trading signals, ranging from simple logical operations and addition/subtraction to complex custom functions. As long as the function can be applied to an ndarray, it can theoretically be used to blend trading signals, as long as the final output trading signal is meaningful.

Defining strategy combination method blender

qteasy’s combination strategy is implemented by blender. In an Operator, if the number of strategies exceeds 1, a blender must be defined. If no blender is explicitly defined and the number of strategies exceeds 1, qteasy will create a default blender when running the Operator. However, to ensure the correct operation of multiple strategies, users need to define the blender themselves.

blender expression is a user-defined combination expression that determines the combination method of different trading strategies. This combination expression uses arithmetic operators, logical operators, functions, and other symbols to specify how strategy signals are combined. The blender expression can include the following elements:

blender expression supports the following functions:

Elements

Examples

Description

Strategy Number

s1

A string starting with ‘s’ and ending with a number, where the number is the index of the strategy in the Operator, representing the trading signal generated by this strategy

Numbers

-1.35

Any valid number, a number that participates in expression operations

Operators

+

arithmetic operators like '+-*/^'

Logical Operators

and

Supports `&

Functions

sum()

Functions supported are listed in the table below

Perentheses

()

Combined Operations

Examples of blender

When there are three trading strategies in an Operator object (with indices 0/1/2), the following ways of defining blender are all valid and can be used. At the same time, use Operator.set_blender() to set blender:

Defining blender expression using arithmetic operators

's0 + s1 + s2'

The trading signals generated by the three trading strategies will be added together to form the final trading signal. If the result of strategy 0 is a buy of 10%, the result of strategy 1 is a buy of 10%, and the result of strategy 2 is a buy of 30%, then the final result is a buy of 50%.

Defining blender expression using logical operators:

's0 and s1 and s2'

Indicating that a trading signal will only be formed when trading strategies 1, 2, and 3 all have trading signals. For example, if the result of strategy 1 is a buy, the result of strategy 2 is a buy, and strategy 3 has no trading signal, then the final result is no trading signal.

Functions and parentheses can also be included in the blender expression:

'max(s0, s1) + s2'

The maximum value of the results of strategies 1 and 2 is added to the result of strategy 3 to form the final trading signal. If the result of strategy 1 is a buy of 10%, the result of strategy 2 is a buy of 20%, and the result of strategy 3 is a buy of 30%, then the final result is a buy of 50%.

Same strategy can appear more than once in the blender expression, and pure numbers can also appear:

'(0.5 * s0 + 1.0 * s1 + 1.5 * s2) / 3 * min(s0, s1, s2)'

Above blender expression indicates: First, calculate the weighted average of the three strategy signals (with weights of 0.5, 1.0, and 1.5), and then multiply by the minimum value of the three signals.

Function parameters in the blender expression are defined in the function name:

'clip_-0.5_0.5(s0 + s1 + s2) + pos_2_0.2(s0, s1, s2)'

Above blender expression defines two different function operations, and the results are added together to obtain the final result. The first function is a range clipping function, which adds the three sets of strategy signals and clips the signal values less than -0.5 and greater than 0.5 to obtain the calculation result. The second function is a position judgment function, which counts the time periods when the three sets of signals have positions greater than 0.2, defining them as ‘long’. Then, it counts the number of strategies suggesting long positions in each time period. If more than two strategies suggest long positions, it outputs a full long position; otherwise, it outputs an empty position.

blender expression supports the following functions:

Functions

Expressions

Description

abs

abs(*signals)

absolute value function
Calculate the absolute value of all trading signals
The number of input signals is unlimited

avg

avg(*signals)

Average value function
Calculate the average value of all trading signals
The number of input signals is unlimited

avgpos

avgpos_N_T(*signals)

Average cumulative function
When the trading signal is a position target signal, count the number of non-empty position signals (output signal absolute value > T) generated at the same time. When the number of short/long signals is greater than N, output the average of all short/long signals; otherwise, output 0.
The number of input signals is unlimited

ceil

ceil(signal)

Ceiling function
Trading signal rounded up
Only one trading signal can be input

clip

clip_U_L(signal)

Clipping function
Clip the signal values that exceed the range, and the upper and lower clipping ranges are defined in the function name
Only one trading signal can be input

combo

combo(*signals)

Combo function
Output the sum of all trading signals
The number of input signals is unlimited

committee

cmt_N_T(*signals)

Committee function (equivalent to cumulative position function)
When the trading signal is a position target signal, count the number of non-empty position signals (output signal absolute value > T) generated at the same time. When the number of long/short signals is greater than N, output -1/1; otherwise, output 0.
The number of input signals is unlimited

exp

exp(signal)

Exponent function
Calculate the power of e to the signal
Only one trading signal can be input

floor

floor(signal)

Floor function
Trading signal rounded down
Only one trading signal can be input

log

log(signal)

Logarithm function
Calculate the logarithm value with base e
Only one trading signal can be input

log10

log10(signal)

Logarithm base 10 function
Calculate the logarithm value with base 10
Only one trading signal can be input

max

max(*signals)

Maximum value function
Calculate the maximum value of all trading signals
The number of input signals is unlimited

min

min(*signals)

Minimum value function
Calculate the minimum value of all trading signals
The number of input signals is unlimited

pos

pos_N_T(*signals)

Cumulative position function
When the trading signal is a position target signal, count the number of non-empty position signals (output signal absolute value > T) generated at the same time. When the number of long/short signals is greater than N, output -1/1; otherwise, output 0.
The number of input signals is unlimited

position

position_N_T(*signals)

Cumulative position function
When the trading signal is a position target signal, count the number of non-empty position signals (output signal absolute value > T) generated at the same time. When the number of long/short signals is greater than N, output -1/1; otherwise, output 0.
The number of input signals is unlimited

pow

pow(*signals)

Power function
Calculate the first trading signal raised to the power of the second trading signal, i.e., sig0^sig1
The number of input signals can only be two

power

power(*signals)

Power function
Calculate the first trading signal raised to the power of the second trading signal, i.e., sig0^sig1
The number of input signals can only be two

sqrt

sqrt(signal)

Square root function
Square root of trading signal
Only one trading signal can be input

str

str_T(*signals)

Cumulative strength function
Sum all trading signals, output 1 when the signal strength exceeds T, otherwise output 0
The number of input signals is unlimited

strength

strength_T(*signals)

Cumulative strength function
Sum all trading signals, output 1 when the signal strength exceeds T, otherwise output 0
The number of input signals is unlimited

sum

sum(*signals)

Combo function
Output the sum of all trading signals
The number of input signals is unlimited

unify

unify(signal)

Unifying function
Normalize trading signals, scaling the trading signals in the same row proportionally so that the sum of each row is 1
Only one trading signal can be input

vote

vote_N_T(*signals)

Voting function (equivalent to cumulative position function)
When the trading signal is a position target signal, count the number of non-empty position signals (output signal absolute value > T) generated at the same time. When the number of long/short signals is greater than N, output -1/1; otherwise, output 0.
The number of input signals is unlimited

blender can be set or retrieved using the following methods

operator.set_blender(blender=None, price_type=None)

Pass in an expression directly to set the blender, which will be automatically parsed and used to combine trading strategies.

operator.view_blender()

View blender

Examples of blender usage

Here is an example to demonstrate how blender works:

# 创建一个交易员对象,同时运行五个相同的dma交易策略,这些交易策略运行方式相同,但是设置不同的参数后,会产生不同的交易信号。我们通过不同的策略组合方式,得到不同的回测结果
op = qt.Operator('dma, dma, dma, dma, dma')
# 分别给五个不同的交易策略设置不同的策略参数,使他们产生不同的交易信号
op.set_parameter(stg_id=0, pars=(132, 200, 24))
op.set_parameter(stg_id=1, pars=(124, 187, 51))
op.set_parameter(stg_id=2, pars=(103, 81, 16))
op.set_parameter(stg_id=3, pars=(48, 111, 148))
op.set_parameter(stg_id=4, pars=(104, 127, 58))

# 第一种组合方式:加权平均方式:分别给每一个不同的策略设置不同的权重:
# s0: 权重0.8
# s0: 权重1.2
# s0: 权重2.0
# s0: 权重0.5
# s0: 权重1.5
# 将五个交易策略生成的交易信号加权平均后得到最终的交易信号
op.set_blender('(0.8*s0+1.2*s1+2*s2+0.5*s3+1.5*s4)/5')

# 运行策略
res = qt.run(op, mode=1)
# 得到结果如下:年化收益12.19,夏普率1.053
     ====================================
     |                                  |
     |       BACK TESTING RESULT        |
     |                                  |
     ====================================

qteasy running mode: 1 - History back testing
time consumption for operate signal creation: 130.5ms
time consumption for operation back looping:  523.8ms

investment starts on      2016-04-05 00:00:00
ends on                   2021-02-01 00:00:00
Total looped periods:     4.8 years.

-------------operation summary:------------

          Sell Cnt Buy Cnt Total Long pct Short pct Empty pct
000300.SH   478      421    899   89.7%      0.0%     10.3%   

Total operation fee:     ¥    2,615.40
total investment amount: ¥  100,000.00
final value:              ¥  174,263.46
Total return:                    74.26% 
Avg Yearly return:               12.19%
Skewness:                         -0.31
Kurtosis:                         10.31
Benchmark return:                65.96% 
Benchmark Yearly return:         11.06%

------strategy loop_results indicators------ 
alpha:                            0.007
Beta:                             1.408
Sharp ratio:                      1.053
Info ratio:                       0.000
250 day volatility:               0.111
Max drawdown:                    12.26% 
    peak / valley:        2019-04-19 / 2020-02-03
    recovered on:         2020-07-06
===========END OF REPORT=============

png

# 第二种组合方式:将五个交易策略看成一个“委员会”,最终的持仓仓位由委员会投票决定:
# 当同一时间累计五个策略中至少三个输出多头满仓使,输出多头满仓,否则空仓
op.set_blender('pos_3_0(s0, s1, s2, s3, s4)')
# 运行策略
res = qt.run(op, mode=1)
# 得到结果如下:年化收益13.39,夏普率1.075
     ====================================
     |                                  |
     |       BACK TESTING RESULT        |
     |                                  |
     ====================================

qteasy running mode: 1 - History back testing
time consumption for operate signal creation: 540.1ms
time consumption for operation back looping:  435.8ms

investment starts on      2016-04-05 00:00:00
ends on                   2021-02-01 00:00:00
Total looped periods:     4.8 years.

-------------operation summary:------------

          Sell Cnt Buy Cnt Total Long pct Short pct Empty pct
000300.SH    11       10     21   55.4%      0.0%     44.6%   

Total operation fee:     ¥      585.88
total investment amount: ¥  100,000.00
final value:              ¥  183,485.41
Total return:                    83.49% 
Avg Yearly return:               13.39%
Skewness:                         -0.43
Kurtosis:                         14.75
Benchmark return:                65.96% 
Benchmark Yearly return:         11.06%

------strategy loop_results indicators------ 
alpha:                            0.046
Beta:                             1.003
Sharp ratio:                      1.075
Info ratio:                       0.006
250 day volatility:               0.124
Max drawdown:                    15.71% 
    peak / valley:        2019-04-19 / 2020-02-03
    recovered on:         2020-07-31
===========END OF REPORT=============

png

# 第三种组合方式:同样是委员会策略,但输出满仓多头的投票门槛变为2票,即只要有两个策略认为输出多头即可
op.set_blender('pos_2_0(s0, s1, s2, s3, s4)')
# 运行策略
res = qt.run(op, mode=1)
# 得到结果如下:年化收益12.88,夏普率0.824
     ====================================
     |                                  |
     |       BACK TESTING RESULT        |
     |                                  |
     ====================================

qteasy running mode: 1 - History back testing
time consumption for operate signal creation: 133.8ms
time consumption for operation back looping:  500.0ms

investment starts on      2016-04-05 00:00:00
ends on                   2021-02-01 00:00:00
Total looped periods:     4.8 years.

-------------operation summary:------------

          Sell Cnt Buy Cnt Total Long pct Short pct Empty pct
000300.SH    15       14     29   71.4%      0.0%     28.6%   

Total operation fee:     ¥      707.30
total investment amount: ¥  100,000.00
final value:              ¥  179,532.76
Total return:                    79.53% 
Avg Yearly return:               12.88%
Skewness:                         -0.45
Kurtosis:                         10.45
Benchmark return:                65.96% 
Benchmark Yearly return:         11.06%

------strategy loop_results indicators------ 
alpha:                            0.029
Beta:                             1.000
Sharp ratio:                      0.824
Info ratio:                       0.007
250 day volatility:               0.144
Max drawdown:                    15.94% 
    peak / valley:        2018-01-24 / 2019-01-03
    recovered on:         2019-02-25
===========END OF REPORT=============

png