该策略的核心思想是实现一个可以灵活选择回测时间范围的框架,让用户可以根据不同的需求,自动或手动设置回测的起止时间。
策略通过输入参数提供了四种日期范围选择方式:使用全部历史数据、最近指定天数、最近指定周数或手动指定日期范围。策略会根据选择的日期范围动态设置回测窗口,而交易逻辑保持不变,这样可以比较不同时间窗口下策略表现的差异。
该策略由回测日期范围选择模块和双MA交易策略模块组成。
该策略作为一个通用的回测日期范围框架,优点是灵活、可定制,可以满足用户不同的测试需求。配合简单有效的双MA交易逻辑,可以快速对策略进行验证和比较。后续可通过增加过滤器、止损逻辑等进行优化,使策略向实盘应用又近了一步。总体来说,该策略框架具有很好的拓展性和参考价值。
/*backtest
start: 2022-12-29 00:00:00
end: 2024-01-04 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=4
strategy(title = "How To Auto Set Date Range", shorttitle = " ", overlay = true)
// Revision: 1
// Author: @allanster
// === INPUT MA ===
fastMA = input(defval = 14, title = "FastMA", type = input.integer, minval = 1, step = 1)
slowMA = input(defval = 28, title = "SlowMA", type = input.integer, minval = 1, step = 1)
// === INPUT BACKTEST RANGE ===
useRange = input(defval = "WEEKS", title = "Date Range", type = input.string, confirm = false, options = ["ALL", "DAYS", "WEEKS", "MANUAL"])
nDaysOrWeeks = input(defval = 52, title = "# Days or Weeks", type = input.integer, minval = 1)
FromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 15, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2019, title = "From Year", minval = 2014)
ToMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 2014)
// === FUNCTION EXAMPLE ===
window() => true
// === LOGIC ===
buy = crossover(sma(close, fastMA), sma(close, slowMA)) // buy when fastMA crosses over slowMA
sell = crossunder(sma(close, fastMA), sma(close, slowMA)) // sell when fastMA crosses under slowMA
// === EXECUTION ===
strategy.entry("L", strategy.long, when=window() and buy) // buy long when "within window of time" AND crossover
strategy.close("L", when=window() and sell) // sell long when "within window of time" AND crossunder
// === PLOTTING ===
plot(sma(close, fastMA), title = 'FastMA', color = color.aqua, linewidth = 2, style = plot.style_line) // plot FastMA
plot(sma(close, slowMA), title = 'SlowMA', color = color.yellow, linewidth = 2, style = plot.style_line) // plot SlowMA