In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to use python to achieve thermostat strategy, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Brief introduction of strategy
When it comes to thermostats, some people may think of the thermostat between the car engine and the water tank. When the engine temperature is low, the thermostat is off, and the water between the engine and the water tank is not connected until the engine temperature rises to achieve the best oil lubrication effect; when the engine temperature rises to a certain threshold, the thermostat is on, at this time, the water of the engine and the water tank forms a cycle, and flows through the fan to open the cooling mode until the engine reaches the optimal working temperature.
So the thermostat strategy is similar to this principle, and the name is extended. Through the volatility index as the threshold, it divides the market into trend market and concussive market, and automatically uses the corresponding trading logic for two different quotations, which effectively makes up for the inadaptability of trend strategy in volatile market.
Market volatility index
How to divide the market into trend market and shock market has become the key to this strategy. The thermostat strategy introduces the market volatility index (Choppy Market Index), referred to as CMI. It is a technical index used to judge the type of market trend. By calculating the ratio of the difference between the current closing price and the closing price before the N cycle to the range of price fluctuations during this period, we can judge whether the current price trend is a trend or a shock.
The calculation formula of CMI is:
CMI= (abs (Close-ref (close, (NMur1) * 100 / (HHV (high,n)-LLV (low,n))
Where abs is the absolute value and n is the number of cycles.
Policy logic
Generally speaking, the value of CMI is in the range of 0,100. The higher the value is, the stronger the trend is. When the value of CMI is less than 20:00, the strategy thinks the market is in volatile mode; when the value of CMI is greater than or equal to 20:00, the strategy thinks the market is in trend mode.
The whole policy logic can be simplified as follows:
If CMI
< 20,执行震荡策略; 如果CMI ≥ 20,执行趋势策略; 策略架构就是这么简单,剩下的就是把震荡策略的内容和趋势策略的内容,填充到这个框架里面。 策略编写 依次打开:fmz.com网站 >Log in > Control Center > Policy Library > New Policy > Click the drop-down menu in the upper right corner to select the Python language and start writing the policy. Pay attention to the comments in the code below.
Step 1: write a strategy framework
This has been learned in the previous chapter, one is the onTick function, and the other is the main function, where the onTick function is executed in an infinite loop in the main function, as follows:
# Policy main function def onTick (): pass# program entry def main (): while True: # enter infinite loop mode onTick () # execute policy main function Sleep (1000) # hibernate for 1 second
Step 2: define virtual position variables
Mp = 0 # defines a global variable to control virtual positions
The function of virtual position is mainly used to control the strategy position. When the policy runs, the default is short position mp=0, when multiple orders are opened, virtual positions are reset to mp=1, when short orders are opened, virtual positions are reset to mp=-1, and when multiple orders or short orders are leveled, virtual positions are reset to mp=0. In this way, we only need to judge the value of mp when judging the construction logic to get the position. The characteristic of virtual position is easy to write and fast iterative strategy update, which is generally used in the backtest environment, assuming that every order is fully closed, but the real position is commonly used in the actual transaction.
Step 3: get the basic data
Exchange.SetContractType ("rb000") # subscription futures variety bar_arr = exchange.GetRecords () # get K-line array if len (bar_arr)
< 100: # 如果K线少于100根 return # 直接返回close0 = bar_arr[-1]['Close'] # 获取最新价格(卖价),用于开平仓bar_arr.pop() # 删除K线数组最后一个元素,策略采用开平仓条件成立,下根K线交易模式 首先使用发明者量化API中的SetContractType方法订阅期货品种。接着使用GetRecords方法获取K线数组,因为有时候K线数量太少,导致无法计算一些数据,所以我们判断如果K线少于100根,就直接返回等待下一次新数据。 然后我们从K线数组中获取最新的卖一价,这个主要用于使用开平仓函数时传入价格参数。最后因为我们的策略采用当前K线开平仓条件成立,在下根K线交易的模式,所以需要删除K线数组最后一个元素。这样做有2个好处:第1个可以使回测绩效更接近于实盘;第2个是避免未来函数和偷价这些常见的策略逻辑错误。 计算市场波动指数CMI close1 = bar_arr[-1]['Close'] # 最新收盘价close30 = bar_arr[-30]['Close'] # 前30根K线的收盘价hh40 = TA.Highest(bar_arr, 30, 'High') # 最近30根K线的最高价ll30 = TA.Lowest(bar_arr, 30, 'Low') # 最近30根K线的最低价cmi = abs((close1 - close30) / (hh40 - ll30)) * 100 # 计算市场波动指数 根据CMI的计算公式,我们需要4个数据,分别是:最新收盘价、前30根K线的收盘价、最近30根K线的最高价、最近30根K线的最低价。前两个很简单,可以直接从K线数组中获取。最后两个则需要调用发明者量化内置的talib指标库TA.Highest和TA.Lowest,这两个指标函数需要传入三个参数,分别是:K线数据、周期、属性。最后当前收盘价与前30根K线的收盘价的差值与这段时间内价格波动的范围的比值就是市场波动指数CMI。 定义宜卖市和宜买市 high2 = bar_arr[-1]['High'] # 最新最高价low1 = bar_arr[-1]['Low'] # 最新最低价kod = (close1 + high2 + low1) / 3 # 计算关键价格if close1 >Kod: be = 1 se = 0else: be = 0 se = 1
In volatile markets, there is usually a phenomenon: if prices rise today, they are more likely to fall tomorrow. If prices fall today, prices are more likely to rise tomorrow, which is the characteristic of the volatile market. So first define a key price (the average of the highest price, the lowest price and the closing price). These data can be obtained directly from the K-line data. If the current price is higher than the key price, it should be bearish tomorrow. On the contrary, if the current price is less than the key price, it should be volatile and bullish tomorrow.
Calculate the entry and exit price of the concussive market
# calculate the ATR index of 10 K lines atr10 = TA.ATR (bar_arr 10) [- 1] # define the highest price and the lowest price 3-day average price high3 = bar_arr [- 2] ['High'] # the highest price on the K line high4 = bar_arr [- 3] [' High'] # the highest price on the front K line low2 = bar_arr [- 2] ['Low'] # the lowest price low3 = bar_arr [- 3] [' Low'] # the lowest price on the front K line avg3high = ( High2 + high3 + high4) / 3 # mean of the highest price of the last three K lines avg3low = (low1 + low2 + low3) / 3 # the average of the lowest price of the last three K lines # calculate the entry and exit price of the volatile market open1 = bar_arr [- 1] ['Open'] # latest opening price if close1 > kod: # if the closing price is greater than the key price lep = open1 + atr10 * 3 sep = open1- Atr10 * 2else: lep = open1 + atr10 * 2 sep = open1-atr10 * 3lep1 = max (lep Avg3high) # calculate the long entry price of the concussion market sep1 = min (sep, avg3low) # calculate the short entry price of the concussion market
First of all, the ATR index of 10 K-lines is calculated, which is also a direct call to the TA.ATR in the built-in talib library quantified by the inventor. In order to prevent false breakthroughs and cause the strategy to stop losses back and forth, a 3-day moving average filter with the highest price and the lowest price is added to avoid this situation, and the average values of the last three K-lines are obtained from the K-line array.
With the above calculation steps, we can finally calculate the entry and exit price in the concussion market, the principle is to take the opening price as the center, up and down to add or subtract the true fluctuation range of the last 10 K lines, forming an open and empty price channel. In order to make the strategy more in line with the market trend, different spaces are set for long and short.
Being bullish in a volatile market only means that prices are more likely to rise, not that prices will necessarily rise. So set the long threshold lower and the short threshold higher. By the same token, being bearish in a volatile market only means that the price is more likely to fall, not necessarily that the price will fall. So set the threshold for shorting a little lower and the threshold for long a little higher.
Calculate the entry price of the trend market
Boll = TA.BOLL (bar_arr, 50,2) up_line = boll [0] [- 1] mid_line = boll [1] [- 1] down_line = boll [2] [- 1]
In dealing with the entry and exit price of the trend market, the Bollinger belt strategy is adopted. when the price breaks through the upper rail of the Bollinger belt, the long position is opened, and when the price breaks down through the lower rail of the Bollinger belt, the short position is opened, and the closing mode is judged by the position relationship between the current price and the Bollinger middle rail.
Complete policy code
Backteststart: 2015-02-22 00:00:00end: 2019-12-20 00:00:00period: 1hexchanges: [{"eid": "Futures_CTP", "currency": "FUTURES"}]''mp = 0 # define a global variable Used to control virtual position # policy main function def onTick (): exchange.SetContractType ("rb000") # subscribe futures variety bar_arr = exchange.GetRecords () # get K-line array if len (bar_arr)
< 100: # 如果K线少于100根 return # 直接返回 close0 = bar_arr[-1]['Close'] # 获取最新价格(卖价),用于开平仓 bar_arr.pop() # 删除K线数组最后一个元素,策略采用开平仓条件成立,下根K线交易模式 # 计算CMI指标用以区分震荡市与趋势市 close1 = bar_arr[-1]['Close'] # 最新收盘价 close30 = bar_arr[-30]['Close'] # 前30根K线的收盘价 hh40 = TA.Highest(bar_arr, 30, 'High') # 最近30根K线的最高价 ll30 = TA.Lowest(bar_arr, 30, 'Low') # 最近30根K线的最低价 cmi = abs((close1 - close30) / (hh40 - ll30)) * 100 # 计算市场波动指数 # 震荡市中收盘价大于关键价格为宜卖市,否则为宜买市 high2 = bar_arr[-1]['High'] # 最新最高价 low1 = bar_arr[-1]['Low'] # 最新最低价 kod = (close1 + high2 + low1) / 3 # 计算关键价格 if close1 >Kod: be = 1 se = 0 else: be = 0 se = 1 # calculate 10 K-lines ATR index atr10 = TA.ATR (bar_arr 10) [- 1] # define the highest price and the lowest price the 3-day average high3 = bar_arr [- 2] ['High'] # the highest price on the K line high4 = bar_arr [- 3] [' High'] # the highest price on the front K line low2 = bar_arr [- 2] ['Low'] # the lowest price on the K line low3 = bar_arr [- 3] [' Low'] # The lowest price of the front K line avg3high = (high2 + high3 + high4) / 3 # the mean value of the highest price of the last 3 K lines avg3low = (low1 + low2 + low3) / 3 # the mean value of the lowest price of the last 3 K lines # calculate the entry price of the volatile market open1 = bar_arr [- 1] ['Open'] # latest opening price if close1 > kod: # if the market closes The price is greater than the key price lep = open1 + atr10 * 3 sep = open1-atr10 * 2 else: lep = open1 + atr10 * 2 sep = open1-atr10 * 3 lep1 = max (lep Avg3high) # calculate the long entry price of the volatile market sep1 = min (sep, avg3low) # calculate the short price of the volatile market # calculate the entry price of the trend market boll = TA.BOLL (bar_arr, 50 2) up_line = boll [0] [- 1] mid_line = boll [1] [- 1] down_line = boll [2] [- 1] global mp # introduces the global variable if cmi
< 20: # 如果是震荡行情 if mp == 0 and close1 >= lep1 and se: exchange.SetDirection ("buy") # set the trading direction and type exchange.Buy (close0, 1) # open multiple orders mp = 1 # set the value of virtual position That is, multiple single if mp = = 0 and close1 = avg3high or be): exchange.SetDirection ("closebuy") # sets the trading direction and type exchange.Sell (close0-1,1) # flat multiple single mp = 0 # sets the value of virtual position That is, short position if mp =-1 and (close1 = up_line: exchange.SetDirection ("buy") # sets the trading direction and type exchange.Buy (close0, 1) # multiple orders mp = 1 # sets the value of virtual positions, that is, there are multiple orders if mp = = 0 and close1
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: 204
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.