def backTest(startDate, endDate): engine = BacktestingEngine() engine.setBacktestingMode(engine.BAR_MODE) # 设置引擎的回测模式为K线 engine.setDatabase(MINUTE_DB_NAME) # 设置使用的历史数据库 engine.setStartDate(startDate,initDays=1) # 设置回测用的数据起始日期 engine.setEndDate(endDate) engine.setSlippage(0.2) # 设置滑点为股指1跳 engine.setRate(1/1000) # 设置手续费万0.3 engine.setSize(1) # 设置股指合约大小 engine.setPriceTick(0.01) # 设置股指最小价格变动 engine.setCapital(1000000) # 设置回测本金 engine.initStrategy(MultiFrameMaStrategy, {'symbolList':['tBTCUSD:bitfinex']}) engine.setCapital(100000) engine.runBacktesting() # 优化配置 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget('totalNetPnl') # 设置优化排序的目标是策略净盈利 setting.addParameter('fastWindow', 20, 40, 10) # 增加第一个优化参数atrLength,起始12,结束20,步进2 setting.addParameter('slowWindow', 50, 80, 10) # 增加第二个优化参数atrMa,起始20,结束30,步进5 setting.addParameter('symbolList', ['tBTCUSD:bitfinex']) # 执行多进程优化 import time import json start = time.time() resultList = engine.runParallelOptimization(MultiFrameMaStrategy, setting) # resultList = engine.runOptimization(MultiFrameMaStrategy, setting) print('耗时:%s' %(time.time()-start)) performance = pd.DataFrame(resultList).sort_values(1, ascending=False).iloc[0:2] bestParameter = performance.iloc[0,0].replace("'",'"') newParameter = json.loads(bestParameter) return newParameter
def runOptimization(): from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, MINUTE_DB_NAME, OptimizationSetting # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) # 设置回测用的数据起始日期 engine.setStartDate('20110801') # 设置产品相关参数 engine.setCapital(100000) engine.setSlippage(1) # 股指1跳 engine.setRate(1.0 / 10000) # 万0.3 engine.setSize(10) # 股指合约大小 engine.setPriceTick(1) # 股指最小价格变动 # 设置使用的历史数据库 engine.setDatabase(MINUTE_DB_NAME, 'rb0000') engine.stratName = 'MultiTimeM60M5' engine.symbol = 'rb0000' # 跑优化 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget( 'totalNetPnl') # 设置优化排序的目标是策略净盈利 sharpeRatio totalNetPnl endBalance #setting.addParameter('stop_loss', 10, 100, 5) # 增加第一个优化参数atrLength,起始12,结束20,步进2 setting.addParameter('stop_loss', 65) #setting.addParameter('bollDev', 1, 5, 0.5) # 增加第二个优化参数atrMa,起始20,结束30,步进5 setting.addParameter('bollDev', 2.5) setting.addParameter('bollWindow', 10, 100, 5) #setting.addParameter('bollWindow', 5) # 增加一个固定数值的参数 # 性能测试环境:I7-3770,主频3.4G, 8核心,内存16G,Windows 7 专业版 # 测试时还跑着一堆其他的程序,性能仅供参考 import time start = time.time() # 运行单进程优化函数,自动输出结果,耗时:359秒 #engine.runOptimization(BollingerStrategy, setting) # 多进程优化,耗时:89秒 #engine.runParallelOptimization(BollingerStrategy, setting) engine.saveParallelOptimization(MultiTimeframeStrategy, setting) print u'耗时:%s' % (time.time() - start)
def runOptimization(): from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, MINUTE_DB_NAME, OptimizationSetting # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) bd = {'start':'20170801','capital':10000,'slippage':1,'rate':1.0/10000,'size':10,'priceTick':1,'symbol':'rb0000','stratName':'A3Strategy'} # 设置回测用的数据起始日期 engine.setStartDate(bd['start']) # 设置产品相关参数 engine.setCapital(bd['capital']) engine.setSlippage(bd['slippage']) # 股指1跳 engine.setRate(bd['rate']) # 万0.3 engine.setSize(bd['size']) # 股指合约大小 engine.setPriceTick(bd['priceTick']) # 股指最小价格变动 # 设置使用的历史数据库 engine.setDatabase(MINUTE_DB_NAME, bd['symbol']) engine.stratName = bd['stratName'] engine.symbolName = bd['symbol'] # 跑优化 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget('totalNetPnl') # 设置优化排序的目标是策略净盈利 sharpeRatio totalNetPnl endBalance #setting.addParameter('stop_loss', 10, 100, 5) # 增加第一个优化参数atrLength,起始12,结束20,步进2 setting.addParameter('fastPeriod', 5, 30, 5) setting.addParameter('slowPeriod', 60) # 性能测试环境:I7-3770,主频3.4G, 8核心,内存16G,Windows 7 专业版 # 测试时还跑着一堆其他的程序,性能仅供参考 import time start = time.time() # 运行单进程优化函数,自动输出结果,耗时:359秒 #engine.runOptimization(BollingerStrategy, setting) # 多进程优化,耗时:89秒 #engine.runParallelOptimization(BollingerStrategy, setting) engine.saveParallelOptimization(A3Strategy, setting) print u'耗时:%s' %(time.time()-start)
def runOptimization(): from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, MINUTE_DB_NAME, OptimizationSetting # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) # 设置回测用的数据起始日期 engine.setStartDate('20120101') # 设置产品相关参数 engine.setCapital(200000) engine.setSlippage(0.2) # 股指1跳 engine.setRate(0.3 / 10000) # 万0.3 engine.setSize(300) # 股指合约大小 engine.setPriceTick(0.2) # 股指最小价格变动 # 设置使用的历史数据库 engine.setDatabase(MINUTE_DB_NAME, 'IF0000') # 跑优化 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget( 'endBalance') # 设置优化排序的目标是策略净盈利 sharpeRatio totalNetPnl endBalance setting.addParameter('atrLength', 12, 20, 2) # 增加第一个优化参数atrLength,起始12,结束20,步进2 #setting.addParameter('atrMa', 20, 30, 5) # 增加第二个优化参数atrMa,起始20,结束30,步进5 #setting.addParameter('rsiLength', 5) # 增加一个固定数值的参数 # 性能测试环境:I7-3770,主频3.4G, 8核心,内存16G ,Windows 7 专业版 # 测试时还跑着一堆其他的程序,性能仅供参考 import time start = time.time() # 运行单进程优化函数,自动输出结果,耗时:359秒 #engine.runOptimization(AtrRsiStrategy, setting) # 多进程优化,耗时:89秒 engine.runParallelOptimization(AtrRsiStrategy, setting) print u'耗时:%s' % (time.time() - start)
def runBacktesting(self, symbol, strategy, sort): # 写入测试品种和参数, 返回回测数据集包含回测结果 # 在引擎中创建策略对象 # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) # 设置回测用的数据起始日期 engine.setStartDate(symbol["StartDate"]) engine.setSlippage(symbol["Slippage"]) # 1跳 engine.setRate(symbol["Rate"]) # 佣金大小 engine.setSize(symbol["Size"]) # 合约大小 engine.setPriceTick(symbol["Slippage"]) # 最小价格变动 engine.setCapital(symbol["Capital"]) # 设置使用的历史数据库 engine.setDatabase(MINUTE_DB_NAME, symbol["vtSymbol"]) # 调用优化方法,可以集成优化测试 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget(sort) # 设置优化排序的目标是策略净盈利 print strategy[1] for settingKey in strategy[1]: if isinstance(strategy[1][settingKey], tuple): setting.addParameter(settingKey, strategy[1][settingKey][0], strategy[1][settingKey][1], strategy[1][settingKey][2]) else: setting.addParameter(settingKey, strategy[1][settingKey]) # optimizationresult = engine.runParallelOptimization(strategy[0], setting) engine.output(u'输出统计数据') # 如果是使用优化模式,这里返回的是策略回测的dict的list,如果普通回测就是单个dict # 如果大于30 ,就返回三十之内,否则全部 if len(optimizationresult) > 30: return optimizationresult[:30] else: return optimizationresult
def run_tasks(pardir=None): if pardir: os.chdir(pardir) sys.path.append(pardir) setting = loadSettings() STRATEGY_SETTING = setting['STRATEGY_SETTING'] folderName = createFolder(STRATEGY_SETTING) opt_engine_setting = OptimizationSetting() opt_engine_setting.setOptimizeTarget(setting["OPT_TARGET"]) opt_engine_setting.addParameter("symbolList", STRATEGY_SETTING["symbolList"]) engine = startBacktestingEngine(setting['ENGINE_SETTINGS']) strategy = loadStrategy(STRATEGY_SETTING, pardir) for task in setting['TASK_LISTS']: task_name, param_mode = task opt_result = start_optimize_n_output(engine, task, param_mode, opt_engine_setting, folderName, strategy, setting["OPT_TARGET"]) with open(f'{folderName}/opt_result_summary.json', "w", encoding="utf-8") as f: json.dump(opt_result, f, indent=4) print("*** tasks finished ****")
if __name__ == "__main__": engine = BacktestingEngine() # 设置回测用的数据起始日期 engine.setStartDate('20190401 23:00:00') engine.setEndDate('20190430 23:00:00') # 设置产品相关参数 contracts = [{ "symbol": "eos.usd.q:okef", "size": 10, "priceTick": 0.001, "rate": 5 / 10000, "slippage": 0.005 }] engine.setContracts(contracts) # 设置回测合约相关数据 # 设置使用的历史数据库 engine.setDB_URI("mongodb://192.168.0.104:27017") engine.setDatabase("VnTrader_1Min_Db") engine.setCapital(100) # 设置起始资金,默认值是1,000,000 with open("CTA_setting.json") as parameterDict: params = json.load(parameterDict) engine.initStrategy(Strategy, params[0]) setting = OptimizationSetting() setting.setOptimizeTarget("sharpe_ratio") setting.addParameter('bBandPeriod', 12, 20, 2) # 增加第一个优化参数atrLength,起始12,结束20,步进2 engine.run_ga_optimization(setting)
engine.setBacktestingMode(engine.BAR_MODE) # 设置回测用的数据起始日期 engine.setStartDate('20130616',initDays=1) # 设置回测用的数据起始日期 engine.setEndDate('20130702') # 设置产品相关参数 engine.setSlippage(0.2) # 股指1跳 engine.setRate(0.3/10000) # 万0.3 engine.setSize(300) # 股指合约大小 engine.setPriceTick(0.2) # 股指最小价格变动 # 设置使用的历史数据库 engine.setDatabase(MINUTE_DB_NAME) # 跑优化 setting = OptimizationSetting() # 新建一个优化任务设置对象 setting.setOptimizeTarget('capital') # 设置优化排序的目标是策略净盈利 setting.addParameter('lmaPeriod', 12, 20, 2) # 增加第一个优化参数atrLength,起始12,结束20,步进2 setting.addParameter('cciPeriod', 20, 30, 5) # 增加第二个优化参数atrMa,起始20,结束30,步进5 setting.addParameter('rsiEntry', 5) # 增加一个固定数值的参数 setting.addParameter('vtSymbol','IF0000') # 性能测试环境:I7-3770,主频3.4G, 8核心,内存16G,Windows 7 专业版 # 测试时还跑着一堆其他的程序,性能仅供参考 import time start = time.time() # 运行单进程优化函数,自动输出结果,耗时:359秒 # engine.runOptimization(MultiSignalStrategy, setting) # 多进程优化,耗时:89秒