Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use average trend Index to assist MACD Strategy

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

How to use the average trend index to assist MACD strategy, I believe that many inexperienced people do not know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Preface

"Trends are your friends" is a familiar motto for every trader. But friends who have traded may realize that trends always start without warning and end abruptly. Then in the CTA strategy, how to seize the trend and filter the volatile market is the tireless pursuit of many subjective and quantitative traders. In this course, we will use the average trend Index (ADX) as a filter to analyze its application in quantifying transactions.

What is the average trend index?

The average trend index is a technical tool to measure the trend, referred to as ADX (average directional indicator), which was put forward by Wells Wilder in 1978. Different from other technical analysis tools, ADX can not judge the long-short direction, let alone indicate the exact buying and selling point, it just measures the strength of the current trend.

The default period parameter for ADX is 14, which is usually shown in the sub-graph of the K-diagram. Its value is between 0100, the higher the value, the stronger the upward or downward trend. Usually, when the ADX value is greater than 40, the trend is strong, and this is the time to use trend trading potential. When the ADX value is less than 20:00, the trend is weak and warn traders not to use trend tracking trading strategies.

The calculation method of ADX

The calculation method of ADX is complicated, which involves many intermediate variables, such as positive moving distance of price (+ DM), negative moving distance of price (- DM), true fluctuation range (TR), positive directional index (+ DI), negative directional index (- DI) and so on.

Calculate the trend change

Up: today's highest price-yesterday's highest price

Down: the lowest price yesterday-the lowest price today

+ DM: if up is greater than max (down, 0), then + DM equals up, otherwise it equals zero

-DM: if down is greater than max (up, 0),-DM equals down, otherwise it equals zero

Calculate the real amplitude

TR:max (the difference between today's highest price and today's lowest price, the absolute value of today's high price and yesterday's closing price difference, the absolute value of today's lowest price and yesterday's closing price difference)

Calculate the trend index

DI (14): + DM (14) / TR (14) * 100

-DI (14):-DM (14) / TR (14) * 100

Calculate ADX

DX: (+ DI14)-(- DI14) / (+ DI14) + (- DI14) * 100

ADX:MA (DX,14)

Although the calculation of ADX is relatively complex, its logic is relatively clear: up and down represent the positive and negative moving distance of the price respectively; + DI and-DI represent the upward and downward trend adjusted by volatility, respectively. Regardless of whether the trend is up or down, as long as there is a clear trend, then one of + DI and-DI is always larger, so the value of DX will indicate between 0 and 100 with the strength of the trend; finally, ADX is the 14-day average of DX.

When + DI is higher than-DI, it indicates that the price is on an upward trend. On the contrary, when the-DI is higher than + DI, the price is on a downward trend. Traders can determine the intensity of an upward or downward trend by checking the ADX value at the same point in time.

Policy logic

In the previous sections, we used MACD indicators to create a simple strategy, although the strategy can perform well in the trend market, but in the shock market can not make ends meet, and even in the long-term shock market capital withdrawal is relatively large. So we will add the previous MACD strategy to the ADX filter in this section, and let's see how it works.

Original strategy logic

Long opening: DIF is greater than zero axis

Short opening: DIF is less than zero axis

Long closing position: DIF breaks through DEA Down

Short positions are closed: DIF breaks through DEA upward

Improved strategy logic

Long opening: DIF is greater than zero axis, and ADX is greater than 20

Short opening: DIF is less than zero axis and ADX is greater than 20

Long closing: DIF breaks down through DEA, or ADX drops

Short positions are closed: DIF breaks through DEA up, or ADX falls.

On the basis of the logic of the original strategy, we add ADX filters to open positions and close positions respectively to control the number of opening times when the market enters a period of shock. The value of ADX must be greater than the specified value at the time of opening; once the ADX drops after opening, the position will be closed. The whole strategy logic is designed as a strict in-and-out model to control the pullback during the concussion period.

Strategy writing

Original strategy

# backteststart: 2015-02-22 00:00:00end: 2019-10-17 00:00:00period: 1hexchanges: [{"eid": "Futures_CTP", "currency": "FUTURES"}]''mp = 0 # define a global variable Used to control virtual positions # to determine whether the array rises def is_up (arr): arr_len = len (arr) if arr [arr _ len-1] > arr [arr _ len-2] and arr [arr _ len-3]: return True # determines whether the array drops def is_down (arr): arr_len = len (arr) if arr [arr _ len-1]

< arr[arr_len - 2] and arr[arr_len - 2] < arr[arr_len - 3]: return True # 判断两根两个数组是否金叉def is_up_cross(arr1, arr2): if arr1[len(arr1) - 2] < arr2[len(arr2) - 2] and arr1[len(arr1) - 1] >

Arr2 [len (arr2)-1]: return True# determines whether two arrays are dead forks def is_down_cross (arr1, arr2): if arr1 [len (arr1)-2] > arr2 [len (arr2)-2] and arr1 [len (arr1)-1]

< arr2[len(arr2) - 1]: return True # 程序主函数def onTick(): exchange.SetContractType("rb000") # 订阅期货品种 bar_arr = exchange.GetRecords() # 获取K线数组 if len(bar_arr) < long + m + 1: # 如果K线数组长度太小,就不能计算MACD,所以直接返回跳过 return all_macd = TA.MACD(bar_arr, short, long, m) # 计算MACD值,返回的是一个二维数组 dif = all_macd[0] # 获取DIF的值,返回一个数组 dif.pop() # 删除DIF数组最后一个元素 dea = all_macd[1] # 获取DEA的值,返回一个数组 dea.pop() # 删除DEA数组最后一个元素 last_close = bar_arr[len(bar_arr) - 1]['Close'] # 获取最新价格(卖价),用于开平仓 global mp # 全局变量,用于控制虚拟持仓 # 开多单 if mp == 0 and dif[len(dif) - 1] >

0: exchange.SetDirection ("buy") # set transaction direction and type exchange.Buy (last_close, 1) # multiple orders mp = 1 # set the value of virtual positions, that is, multiple orders # open orders if mp = = 0 and dif [len (dif)-1]

< 0: exchange.SetDirection("sell") # 设置交易方向和类型 exchange.Sell(last_close - 1, 1) # 开空单 mp = -1 # 设置虚拟持仓的值,即有空单 # 平多单 if mp == 1 and is_down_cross(dif, dea): exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(last_close - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓 # 平空单 if mp == -1 and is_up_cross(dif, dea): exchange.SetDirection("closesell") # 设置交易方向和类型 exchange.Buy(last_close, 1) # 平空单 mp = 0 # 设置虚拟持仓的值,即空仓 def main(): while True: onTick() Sleep(1000) 根据上面更改的策略逻辑,我们可以直接在原始策略的基础之上把ADX滤网加入进去,虽然ADX的计算方法比较复杂,但可以借助talib库只需要几行代码就可以把ADX的值计算出来。因为计算ADX需要用带talib,而计算talib库又需要用到numpy.array数据类型,所以我们需要在代码开头导入talib库和numpy库。 import talibimport numpy as np 在使用talib库计算ADX的时候,一共需要4个参数:最高价、最低价、收盘价、周期参数。所以我们还需要写一个get_data函数,这个函数的目的是从K线数组中提取出最高价、最低价、收盘价。 # 把K线数组转换成最高价、最低价、收盘价数组,用于转换为numpy.array类型数据def get_data(bars): arr = [[], [], []] for i in bars: arr[0].append(i['High']) arr[1].append(i['Low']) arr[2].append(i['Close']) return arr 然后我们使用numpy库把普通的数组转换为numpy.array类型数据,最后使用talib库就可以计算出ADX的值,具体的写法可以看下面代码中的注释: np_arr = np.array(get_data(bar_arr)) # 把列表转换为numpy.array类型数据,用于计算ADX的值adx = talib.ADX(np_arr[0], np_arr[1], np_arr[2], 20); # 计算ADX的值 在策略逻辑中,需要判断ADX的大小和是否上升下降。判断大小很简单,只需要把ADX具体某一天的值提取出来就可以了,跟判断MACD一样,我们只取倒数第二根K线的ADX值;但判断时候上升下降则需要只取倒数第二根和第三根K线的ADX值。 adx1 = adx_arr[len(adx_arr) - 2] # 倒数第二根K线的ADX值adx2 = adx_arr[len(adx_arr) - 3] # 倒数第三根K线的ADX值 最后修改下单逻辑: # 开多单if mp == 0 and dif[len(dif) - 1] >

0 and adx1 > 40: exchange.SetDirection ("buy") # sets the trading direction and type exchange.Buy (last_close, 1) # multiple orders mp = 1 # sets the value of virtual positions, that is, multiple orders # open orders if mp = = 0 and dif [len (dif)-1]

< 0 and adx1 >

40: exchange.SetDirection ("sell") # set the trading direction and type exchange.Sell (last_close-1,1) # Open single mp =-1 # set the value of virtual position, that is, there are empty orders # flat multiple single if mp = = 1 and (is_down_cross (dif, dea) or adx1

< adx2): exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(last_close - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓# 平空单if mp == -1 and (is_up_cross(dif, dea) or adx1 < adx2): exchange.SetDirection("closesell") # 设置交易方向和类型 exchange.Buy(last_close, 1) # 平空单 mp = 0 # 设置虚拟持仓的值,即空仓 完整策略代码 # 回测配置'''backteststart: 2015-02-22 00:00:00end: 2019-10-17 00:00:00period: 1hexchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]'''# 导入库import talibimport numpy as npmp = 0 # 定义一个全局变量,用于控制虚拟持仓# 把K线数组转换成最高价、最低价、收盘价数组,用于转换为numpy.array类型数据def get_data(bars): arr = [[], [], []] for i in bars: arr[0].append(i['High']) arr[1].append(i['Low']) arr[2].append(i['Close']) return arr# 判断两根两个数组是否金叉def is_up_cross(arr1, arr2): if arr1[len(arr1) - 2] < arr2[len(arr2) - 2] and arr1[len(arr1) - 1] >

Arr2 [len (arr2)-1]: return True# determines whether two arrays are dead forks def is_down_cross (arr1, arr2): if arr1 [len (arr1)-2] > arr2 [len (arr2)-2] and arr1 [len (arr1)-1]

< arr2[len(arr2) - 1]: return True # 程序主函数def onTick(): exchange.SetContractType("rb000") # 订阅期货品种 bar_arr = exchange.GetRecords() # 获取K线数组 if len(bar_arr) < long + m + 1: # 如果K线数组长度太小,就不能计算MACD,所以直接返回跳过 return all_macd = TA.MACD(bar_arr, short, long, m) # 计算MACD值,返回的是一个二维数组 dif = all_macd[0] # 获取DIF的值,返回一个数组 dif.pop() # 删除DIF数组最后一个元素 dea = all_macd[1] # 获取DEA的值,返回一个数组 dea.pop() # 删除DEA数组最后一个元素 np_arr = np.array(get_data(bar_arr)) # 把列表转换为numpy.array类型数据,用于计算ADX的值 adx_arr = talib.ADX(np_arr[0], np_arr[1], np_arr[2], 20); # 计算ADX的值 adx1 = adx_arr[len(adx_arr) - 2] # 倒数第二根K线的ADX值 adx2 = adx_arr[len(adx_arr) - 3] # 倒数第三根K线的ADX值 last_close = bar_arr[len(bar_arr) - 1]['Close'] # 获取最新价格(卖价),用于开平仓 global mp # 全局变量,用于控制虚拟持仓 # 开多单 if mp == 0 and dif[len(dif) - 1] >

0 and adx1 > 40: exchange.SetDirection ("buy") # sets the trading direction and type exchange.Buy (last_close, 1) # multiple orders mp = 1 # sets the value of virtual positions, that is, multiple orders # open orders if mp = = 0 and dif [len (dif)-1]

< 0 and adx1 >

40: exchange.SetDirection ("sell") # set transaction direction and type exchange.Sell (last_close-1,1) # Open order mp =-1 # set the value of virtual position That is, there is an empty order # flat multiple single if mp = = 1 and (is_down_cross (dif, dea) or adx1 < adx2): exchange.SetDirection ("closebuy") # set the trading direction and type exchange.Sell (last_close-1,1) # flat multiple single mp = 0 # set the value of virtual position That is, short position # short order if mp = =-1 and (is_up_cross (dif, dea) or adx1 < adx2): exchange.SetDirection ("closesell") # set transaction direction and type exchange.Buy (last_close, 1) # short order mp = 0 # set the value of virtual position, that is, short position def main (): while True: onTick () Sleep (1000)

The complete source code of the strategy that has been improved in this section is posted above, or you can copy and download it from the policy on the https://www.fmz.com/strategy/174672 inventor's Quantification website without configuration and direct online backtesting.

After reading the above, have you mastered how to use the average trend index to assist the MACD strategy? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report