移动均线交叉策略是一种非常常见的量化交易策略。该策略利用移动均线的金叉死叉来判断趋势,以获利。当短期移动均线上穿长期移动均线时,表明股价开始上涨,可以做多;当短期移动均线下穿长期移动均线时,表明股价开始下跌,可以做空。
该策略基于移动均线的金叉死叉来判断买入和卖出时机。代码中使用upOrDown
和longOrShort
两个布尔型输入参数来判断做多做空;使用percentInput
输入参数来设定股价变化的阈值百分比;使用closePositionDays
输入参数来设定头寸持有的天数。
策略的核心逻辑是:计算今天相对于昨天的涨跌幅,如果达到了输入的阈值百分比,则发出交易信号。如果是看涨,则当今天相对昨天上涨超过阈值时,做多;如果是看跌,则当今天相对昨天下跌超过阈值时,做空。
做多做空后,会在画图上用不同颜色标记这一天和之后的4天。4天后自动平仓。
风险控制措施:
移动均线交叉策略是一个非常简单实用的量化交易策略。它通过判断短期和长期趋势的关系,利用股票价格的趋势性来获利。该策略容易实现,逻辑清晰,是许多量化交易策略的基础。通过参数调整和优化,可以获得更好的策略效果。但我们也需要注意控制风险,防止曲解其思想而盲目使用。
/*backtest start: 2023-01-01 00:00:00 end: 2023-10-11 00:00:00 period: 1d basePeriod: 1h exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ //@version=3 // Created by Leon Ross strategy(title = "DaysAfterCertainPercentChangev1", shorttitle = "DACPCv1", overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, calc_on_every_tick=true, initial_capital=100000) //Inputs longOrShort = input(title="Long=Checked Short=Unchecked", type=bool, defval=true) //long=true, down=false upOrDown = input(title="Direction of Today vs. Previous day: Up=Checked Down=Unchecked", type=bool, defval=true) //up=true, down=false: this is the direction of days vs previous day percentInput = input(title="Percent", type=float, defval=4.5) closePositionDays = input(title="How Many Days to Close Position", defval=4) //Conditions //percentUpValue = (close / close[1]) - 1 //percentUp = percentUpValue >= (percentInput/100.0) //upConditions = percentUp //percentDownValue = 1- (close / close[1]) //percentDown = percentDownValue >= (percentInput/100.0) //downConditions = percentDown upValue = (close / close[1]) - 1 downValue = 1 - (close / close[1]) allConditions = if(upOrDown) upValue >= (percentInput/100.0) else downValue >= (percentInput/100.0) //Plots bgcolor(allConditions ? (upOrDown ? green : red) : na, transp=70) bgcolor(allConditions ? silver : na, transp=70, offset=1) bgcolor(allConditions ? silver : na, transp=70, offset=2) bgcolor(allConditions ? silver : na, transp=70, offset=3) bgcolor(allConditions ? silver : na, transp=70, offset=4) //bgcolor(downConditions == 1 ? red : na, transp=70) //bgcolor(downConditions == 1 ? silver : na, transp=70, offset=1) //bgcolor(downConditions == 1 ? silver : na, transp=70, offset=2) //bgcolor(downConditions == 1 ? silver : na, transp=70, offset=3) //bgcolor(downConditions == 1 ? silver : na, transp=70, offset=4) //Entires if(longOrShort) strategy.entry(id = "Long", long = true, when = allConditions) else strategy.entry(id = "Short", long = false, when = allConditions) //Exits if (barssince(allConditions) == closePositionDays) if(longOrShort) strategy.close("Long") else strategy.close("Short")