def test(self, test): fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE2.csv') source2 = pd.read_csv(fname, parse_dates=True, index_col=0) global smg, multi target1, cashes1, t1, c1, dts = trade_closed_curbar( source, capital / 2, lmg, smg, multi, 1) # 期货 multi = Contract.volume_multiple('future2.TEST') smg = Contract.short_margin_ratio('future2.TEST') target2, cashes2, t2, c2, dts = trade_closed_curbar( source2, capital / 2, lmg, smg, multi, -1) target = [x + y for x, y in zip(target1, target2)] cashes = [x + y for x, y in zip(cashes1, cashes2)] open_equities = [x + y for x, y in zip(t1, t2)] open_cashes = [x + y for x, y in zip(c1, c2)] test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes) - 1): # 最后一根强平了无法比较 test.assertAlmostEqual(self.cashes[i], open_cashes[i]) test.assertAlmostEqual(self.equities[i], open_equities[i]) for i, hd in enumerate(profile.all_holdings()): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], target[i]) test.assertAlmostEqual(hd['cash'], cashes[i])
def test_case5(self): """ 测试跨合约交易的持仓, 资金 """ cashes0 = [] class DemoStrategy(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) # 默认future.TEST ctx.short(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST') else: if curtime == sell1: assert (ctx.pos('long', 'future.TEST') == 3 and '持仓测试失败!') ctx.sell(ctx.close, 2) assert (ctx.pos('short', 'future2.TEST') == 6 and '持仓测试失败!') ctx.cover(ctx['future2.TEST-1.Minute'].close, 4, 'future2.TEST') elif curtime == sell2: assert (ctx.pos('long', 'future.TEST') == 1 and '跨合约持仓测试失败!') ctx.sell(ctx.close, 1, 'future.TEST') assert (ctx.pos('short', 'future2.TEST') == 2 and '持仓测试失败!') ctx.cover(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST') cashes0.append(ctx.test_cash()) set_symbols(['future.TEST-1.Minute', 'future2.TEST-1.Minute']) profile = add_strategy([DemoStrategy('D1')], {'capital': capital}) run() fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE2.csv') source2 = pd.read_csv(fname, parse_dates=True, index_col=0) lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') # 确保资金够用,所以不影响 target1, cashes1, dts = holdings_buy_maked_curbar( source, capital / 2, lmg, multi) # 期货 multi = Contract.volume_multiple('future2.TEST') smg = Contract.short_margin_ratio('future2.TEST') target2, cashes2, dts = holdings_short_maked_curbar( source2, capital / 2, smg, multi) target = [x + y for x, y in zip(target1, target2)] cashes = [x + y for x, y in zip(cashes1, cashes2)] self.assertTrue(len(cashes0) == len(cashes), 'cash接口测试失败!') for i in range(0, len(cashes0) - 1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i], cashes[i]) for i, hd in enumerate(profile.all_holdings()): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], target[i])
def test_case5(self): """ 测试跨合约交易的持仓, 资金 """ cashes0 = [] class DemoStrategy(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) # 默认future.TEST ctx.short(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST') else: if curtime == sell1: all_postions = ctx.all_positions() assert(len(all_postions) == 2) assert(all_postions[0].quantity == 6) assert(all_postions[0].closable == 6) assert(all_postions[0].direction == Direction.SHORT) assert(all_postions[1].quantity == 3) assert(all_postions[1].closable == 3) assert(all_postions[1].direction == Direction.LONG) assert(ctx.pos('long', 'future.TEST') == 3 and '持仓测试失败!') ctx.sell(ctx.close, 2) assert(ctx.pos('short', 'future2.TEST') == 6 and '持仓测试失败!') ctx.cover(ctx['future2.TEST-1.Minute'].close, 4, 'future2.TEST') elif curtime == sell2: assert(ctx.pos('long', 'future.TEST') == 1 and '跨合约持仓测试失败!') ctx.sell(ctx.close, 1, 'future.TEST') assert(ctx.pos('short', 'future2.TEST') == 2 and '持仓测试失败!') ctx.cover(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST') cashes0.append(ctx.test_cash()) set_symbols(['future.TEST-1.Minute', 'future2.TEST-1.Minute']) profile = add_strategy([DemoStrategy('D1')],{ 'capital': capital }) run() fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE2.csv') source2 = pd.read_csv(fname, parse_dates=True, index_col=0) lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') # 确保资金够用,所以不影响 target1, cashes1, dts = holdings_buy_maked_curbar(source, capital/2, lmg, multi) # 期货 multi = Contract.volume_multiple('future2.TEST') smg = Contract.short_margin_ratio('future2.TEST') target2, cashes2, dts = holdings_short_maked_curbar(source2, capital/2, smg, multi) target = [x + y for x, y in zip(target1, target2)] cashes = [x + y for x, y in zip(cashes1, cashes2)] self.assertTrue(len(cashes0) == len(cashes), 'cash接口测试失败!') for i in range(0, len(cashes0)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i],cashes[i]) for i, hd in enumerate(profile.all_holdings()): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], target[i])
def test_case3(self): """ 测试市价成交 """ cashes0 = [] class DemoStrategy(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(0, 1) ctx.short(0, 2) else: if curtime == sell1: assert(ctx.pos('long') == 3 and '持仓测试失败!') ctx.sell(0, 2) assert(ctx.pos('short') == 6 and '持仓测试失败!') ctx.cover(0, 4) elif curtime == sell2: assert(ctx.pos('long') == 1 and '持仓测试失败!') ctx.sell(0, 1) assert(ctx.pos('short') == 2 and '持仓测试失败!') ctx.cover(0, 2) cashes0.append(ctx.test_cash()) set_symbols(['future.TEST-1.Minute']) profile = add_strategy([DemoStrategy('C1')],{ 'capital': capital}) run() lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') target, cashes, dts = holdings_buy_short_maked_market(source, capital, lmg, smg, multi) self.assertTrue(len(cashes0) == len(cashes), 'cash接口测试失败!') for i in range(0, len(cashes0)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i],cashes[i]) for i, hd in enumerate(profile.all_holdings()): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i])
def test_case4(self): """ 测试市价成交 """ cashes0 = [] class DemoStrategy(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [bt1, bt2, bt3]: ctx.buy(0, 1) ctx.short(0, 2) else: if curtime == st1: assert (ctx.pos('long') == 3 and '持仓测试失败!') ctx.sell(0, 2) assert (ctx.pos('short') == 6 and '持仓测试失败!') ctx.cover(0, 4) elif curtime == st2: assert (ctx.pos('long') == 1 and '持仓测试失败!') ctx.sell(0, 1) assert (ctx.pos('short') == 2 and '持仓测试失败!') ctx.cover(0, 2) cashes0.append(ctx.test_cash()) set_symbols(['future.TEST-1.Minute']) profile = add_strategy([DemoStrategy('C1')], {'capital': capital}) run() lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') target, cashes, dts = holdings_buy_short_maked_market( source, capital, lmg, smg, multi) self.assertTrue(len(cashes0) == len(cashes), 'cash接口测试失败!') for i, hd in enumerate(profile.all_holdings()): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) for i in range(0, len(cashes0) - 1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i], cashes[i])
def test(self, test): fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE2.csv') source2 = pd.read_csv(fname, parse_dates=True, index_col=0) global smg, multi target1, cashes1, t1, c1, dts = trade_closed_curbar(source, capital / 2, lmg, smg, multi, 1) # 期货 multi = Contract.volume_multiple('future2.TEST') smg = Contract.short_margin_ratio('future2.TEST') target2, cashes2, t2, c2, dts = trade_closed_curbar(source2, capital / 2, lmg, smg, multi, -1) target = [x + y for x, y in zip(target1, target2)] cashes = [x + y for x, y in zip(cashes1, cashes2)] open_equities = [x + y for x, y in zip(t1, t2)] open_cashes = [x + y for x, y in zip(c1, c2)] test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes) - 1): # 最后一根强平了无法比较 test.assertAlmostEqual(self.cashes[i], open_cashes[i]) test.assertAlmostEqual(self.equities[i], open_equities[i]) for i, hd in enumerate(profile.all_holdings()): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], target[i]) test.assertAlmostEqual(hd['cash'], cashes[i])
def test_case(self): t_cashes0, t_cashes1 = [], [] class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) else: if ctx.pos() >= 2 and curtime == sell1: ctx.sell(ctx.close, 2) elif ctx.pos() >= 1 and curtime == sell2: ctx.sell(ctx.close, 1) ## 前一根的交易信号在当前价格撮合后的可用资金 t_cashes0.append(ctx.test_cash()) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 2) else: if curtime == sell1: if ctx.pos() >= 3: # quantity == 6, closable == 3 assert(ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) if ctx.pos('short') >= 6: assert(ctx.pos('short') == 6 and '默认持仓查询测试失败!') ctx.cover(ctx.close, 4) elif curtime == sell2: if ctx.pos() >= 1: ctx.sell(ctx.close, 1) if ctx.pos('short') >= 2: ctx.cover(ctx.close, 2) t_cashes1.append(ctx.test_cash()) class DemoStrategy3(Strategy): """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): return set_symbols(['stock.TEST-1.Minute']) profile = add_strategy([DemoStrategy1('A1'), DemoStrategy2('A2'), DemoStrategy3('A3')], { 'capital': capital, 'ratio': [0.3, 0.3, 0.4] }) run() # all_holdings, cash() all_holdings = profile.all_holdings() all_holdings0 = profile.all_holdings(0) all_holdings1 = profile.all_holdings(1) all_holdings2 = profile.all_holdings(2) self.assertTrue(len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') lmg = Contract.long_margin_ratio('stock.TEST') multi = Contract.volume_multiple('stock.TEST') smg = Contract.short_margin_ratio('stock.TEST') s_equity0, s_cashes0, dts = holdings_buy_maked_curbar(source, capital*0.3, lmg, multi) self.assertTrue(len(t_cashes0) == len(s_cashes0), 'cash接口测试失败!') for i in range(0, len(t_cashes0)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes0[i],s_cashes0[i]) self.assertTrue(len(all_holdings) == len(s_equity0), 'all_holdings接口测试失败!') for i, hd in enumerate(all_holdings0): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], s_equity0[i]) # 确保资金够用,所以不影响 e0, c0, dts = holdings_buy_maked_curbar(source, capital*0.3/2, lmg, multi) e1, c1, dts = holdings_short_maked_curbar(source, capital*0.3/2, smg, multi) s_equity1 = [x + y for x, y in zip(e0, e1)] s_cashes1 = [x + y for x, y in zip(c0, c1)] self.assertTrue(len(t_cashes1) == len(s_cashes1), 'cash接口测试失败!') for i in range(0, len(t_cashes1)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes1[i],s_cashes1[i]) for i, hd in enumerate(profile.all_holdings(1)): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], s_equity1[i]) for i in range(0, len(profile.all_holdings())): hd = all_holdings[i] hd0 = all_holdings0[i] hd1 = all_holdings1[i] hd2 = all_holdings2[i] self.assertTrue(hd['cash'] == hd0['cash']+hd1['cash']+hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue(hd['commission'] == hd0['commission']+ hd1['commission']+hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue(hd['equity'] == hd0['equity']+hd1['equity']+hd2['equity'], 'all_holdings接口测试失败!')
def test_case(self): ## @TODO 持仓过夜,不卖,累加仓位。 # @todo profile #signals 盈利 # @TODO deals DemoStrategy2 t_cashes0, t_cashes1 = [], [] class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) else: if curtime == sell1: assert(ctx.pos() == 3 and '持仓测试失败!') ctx.sell(ctx.close, 2) elif curtime == sell2: assert(ctx.pos() == 1 and '持仓测试失败!') ctx.sell(ctx.close, 1) ## 前一根的交易信号在当前价格撮合后的可用资金 t_cashes0.append(ctx.test_cash()) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 2) else: if curtime == sell1: assert(ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) assert(ctx.pos('short') == 6 and '持仓测试失败!') ctx.cover(ctx.close, 4) elif curtime == sell2: assert(ctx.pos('long') == 1 and '持仓测试失败!') ctx.sell(ctx.close, 1) assert(ctx.pos('short') == 2 and '持仓测试失败!') ctx.cover(ctx.close, 2) t_cashes1.append(ctx.test_cash()) class DemoStrategy3(Strategy): """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.curbar == 1: ctx.short(138, 1) ctx.short(138, 1) ctx.buy(ctx.close, 1) elif ctx.curbar == 3: # 保证下一根撤单成功, 而非当前这根。 assert(len(ctx.open_orders) == 2) ctx.cancel(ctx.open_orders[0]) assert(len(ctx.open_orders) == 2 and '撤单测试失败') elif ctx.curbar == 4: assert(len(ctx.open_orders) == 1 and '撤单测试失败!') elif ctx.curbar == 5: assert(ctx.pos() == 1) ctx.sell(300, 1) # 下无法成交的平仓,测试持仓。 elif ctx.curbar == 7: assert(ctx.pos() == 0 and '持仓测试失败!') assert(len(ctx.open_orders) == 2 and '撤单测试失败!') order = filter(lambda x: x.side == TradeSide.PING, ctx.open_orders)[0] ctx.cancel(order) elif ctx.curbar == 8: assert(len(ctx.open_orders) == 1 and '撤单测试失败!') assert(ctx.pos() == 1 and '持仓测试失败!') if ctx.curbar > 1 and ctx.datetime[0].date() != ctx.datetime[1].date(): assert(len(ctx.open_orders) == 0 and '隔夜订单清空测试失败') set_symbols(['future.TEST-1.Minute']) profile = add_strategy([DemoStrategy1('A1'), DemoStrategy2('A2'), DemoStrategy3('A3')], { 'capital': capital, 'ratio': [0.3, 0.3, 0.4] }) run() # all_holdings, cash() all_holdings = profile.all_holdings() all_holdings0 = profile.all_holdings(0) all_holdings1 = profile.all_holdings(1) all_holdings2 = profile.all_holdings(2) self.assertTrue(len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') s_equity0, s_cashes0, dts = holdings_buy_maked_curbar(source, capital*0.3, lmg, multi) self.assertTrue(len(t_cashes0) == len(s_cashes0), 'cash接口测试失败!') for i in range(0, len(t_cashes0)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes0[i], s_cashes0[i]) self.assertTrue(len(all_holdings) == len(s_equity0), 'all_holdings接口测试失败!') for i, hd in enumerate(all_holdings0): self.assertAlmostEqual(hd['equity'], s_equity0[i]) self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') # 确保资金够用,所以不影响 e0, c0, dts = holdings_buy_maked_curbar(source, capital*0.3/2, lmg, multi) e1, c1, dts = holdings_short_maked_curbar(source, capital*0.3/2, smg, multi) s_equity1 = [x + y for x, y in zip(e0, e1)] s_cashes1 = [x + y for x, y in zip(c0, c1)] self.assertTrue(len(t_cashes1) == len(s_cashes1), 'cash接口测试失败!') for i in range(0, len(t_cashes1)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes1[i], s_cashes1[i]) for i, hd in enumerate(profile.all_holdings(1)): self.assertAlmostEqual(s_equity0[i]-capital*0.3, -(s_equity1[i]-capital*0.3)) self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], s_equity1[i]) for i in range(0, len(profile.all_holdings())): hd = all_holdings[i] hd0 = all_holdings0[i] hd1 = all_holdings1[i] hd2 = all_holdings2[i] self.assertTrue(hd['cash'] == hd0['cash']+hd1['cash']+hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue(hd['commission'] == hd0['commission']+ hd1['commission']+hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue(hd['equity'] == hd0['equity']+hd1['equity']+hd2['equity'], 'all_holdings接口测试失败!') # holding hd0 = profile.holding(0) hd1 = profile.holding(1) hd2 = profile.holding(2) hd = profile.holding() self.assertTrue(hd0['equity']+hd1['equity']+hd2['equity']==hd['equity'], 'holdings接口测试失败!') self.assertTrue(hd0['cash']+hd1['cash']+hd2['cash']==hd['cash'], 'holdings接口测试失败!') self.assertTrue(hd0['commission']+hd1['commission']+hd2['commission']==hd['commission'], 'holdings接口测试失败!') self.assertTrue(hd0['history_profit']+hd1['history_profit']+hd2['history_profit']==hd['history_profit'], 'holdings接口测试失败!') hd0last = profile.all_holdings(0)[-1] self.assertTrue(hd0last['equity'] == hd0['equity'], 'holdings接口测试失败!') self.assertTrue(hd0last['cash'] == hd0['cash'], 'holdings接口测试失败!') self.assertTrue(hd0last['commission'] == hd0['commission'], 'holdings接口测试失败!') self.assertTrue(len(profile.all_holdings()) == len(s_equity0) and len(s_equity0) > 0, 'holdings接口测试失败!')
def test_case2(self): """ 测试限价的延迟成交, 与是否是期货还是股票无关。 """ buy_entries, sell_entries = [], [] short_entries, cover_entries = [], [] cashes0, cashes1 = [], [] class DemoStrategyBuy(Strategy): """ 只开多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0] in buy_entries: ctx.buy(ctx.low-OFFSET, 1) # 默认多头 elif ctx.pos() > 0 and ctx.datetime[0].time() == sell1: ctx.sell(ctx.close, ctx.pos()) cashes0.append(ctx.test_cash()) return cashes0.append(ctx.cash()) class DemoStrategyShort(Strategy): """ 只开空头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0] in short_entries: ctx.short(ctx.high+OFFSET, 1) elif ctx.pos('short') > 0 and ctx.datetime[0].time() == sell1: ctx.cover(ctx.close, ctx.pos('short')) cashes1.append(ctx.test_cash()) return cashes1.append(ctx.cash()) class DemoStrategySell(Strategy): """ 只开多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0].time() == buy1: ctx.buy(ctx.close, 1) elif ctx.pos('long') > 0 and ctx.datetime[0] in sell_entries: ctx.sell(ctx.high+OFFSET, ctx.pos()) elif ctx.pos('long') > 0 and ctx.datetime[0].time() == sell3: ctx.sell(ctx.close, ctx.pos()) class DemoStrategyCover(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0].time() == buy1: ctx.short(ctx.close, 1) elif ctx.pos('short') > 0 and ctx.datetime[0] in cover_entries: ctx.cover(ctx.low-OFFSET, ctx.pos('short')) elif ctx.pos('short') > 0 and ctx.datetime[0].time() == sell3: ctx.cover(ctx.close, ctx.pos('short')) set_symbols(['future.TEST-1.Minute']) profile = add_strategy([DemoStrategyBuy('B1'), DemoStrategySell('B2'), DemoStrategyShort('B3'), DemoStrategyCover('B4')],{ 'capital': capital, 'ratio': [0.25, 0.25, 0.25, 0.25] }) buy_entries, sell_entries, short_entries, cover_entries = entries_maked_nextbar(source) run() # buy lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') target, cashes, dts = holdings_buy_maked_nextbar(source, buy_entries, capital/4, lmg, multi) self.assertTrue(len(profile.all_holdings(0)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(0)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) # cash() 终点 for i in range(0, len(cashes0)-1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i],cashes[i]) # short target, cashes, dts = holdings_short_maked_nextbar(source, short_entries, capital/4, smg, multi) self.assertTrue(len(profile.all_holdings(2)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(2)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) for i in range(0, len(cashes1)-1): self.assertAlmostEqual(cashes1[i],cashes[i]) # sell target, dts = holdings_sell_maked_nextbar(source, sell_entries, capital/4, lmg, multi) self.assertTrue(len(profile.all_holdings(1)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(1)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) # cover target, dts = holdings_cover_maked_nextbar(source, cover_entries, capital/4, smg, multi) self.assertTrue(len(profile.all_holdings(3)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(3)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) #from quantdigger.digger import plotting #plotting.plot_strategy(profile.data(), deals=profile.deals(0)) ## @TODO 模拟器make_market的运行次数 return
def test_case(self): t_cashes0, t_cashes1 = [], [] class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) else: if ctx.pos() >= 2 and curtime == sell1: ctx.sell(ctx.close, 2) elif ctx.pos() >= 1 and curtime == sell2: ctx.sell(ctx.close, 1) ## 前一根的交易信号在当前价格撮合后的可用资金 t_cashes0.append(ctx.test_cash()) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 2) else: if curtime == sell1: if ctx.pos() >= 3: # quantity == 6, closable == 3 assert (ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) if ctx.pos('short') >= 6: assert (ctx.pos('short') == 6 and '默认持仓查询测试失败!') ctx.cover(ctx.close, 4) elif curtime == sell2: if ctx.pos() >= 1: ctx.sell(ctx.close, 1) if ctx.pos('short') >= 2: ctx.cover(ctx.close, 2) t_cashes1.append(ctx.test_cash()) class DemoStrategy3(Strategy): """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): return set_symbols(['stock.TEST-1.Minute']) profile = add_strategy( [DemoStrategy1('A1'), DemoStrategy2('A2'), DemoStrategy3('A3')], { 'capital': capital, 'ratio': [0.3, 0.3, 0.4] }) run() # all_holdings, cash() all_holdings = profile.all_holdings() all_holdings0 = profile.all_holdings(0) all_holdings1 = profile.all_holdings(1) all_holdings2 = profile.all_holdings(2) self.assertTrue( len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') lmg = Contract.long_margin_ratio('stock.TEST') multi = Contract.volume_multiple('stock.TEST') smg = Contract.short_margin_ratio('stock.TEST') s_equity0, s_cashes0, dts = holdings_buy_maked_curbar( source, capital * 0.3, lmg, multi) self.assertTrue(len(t_cashes0) == len(s_cashes0), 'cash接口测试失败!') for i in range(0, len(t_cashes0) - 1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes0[i], s_cashes0[i]) self.assertTrue( len(all_holdings) == len(s_equity0), 'all_holdings接口测试失败!') for i, hd in enumerate(all_holdings0): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], s_equity0[i]) # 确保资金够用,所以不影响 e0, c0, dts = holdings_buy_maked_curbar(source, capital * 0.3 / 2, lmg, multi) e1, c1, dts = holdings_short_maked_curbar(source, capital * 0.3 / 2, smg, multi) s_equity1 = [x + y for x, y in zip(e0, e1)] s_cashes1 = [x + y for x, y in zip(c0, c1)] for i, hd in enumerate(profile.all_holdings(1)): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertAlmostEqual(hd['equity'], s_equity1[i]) self.assertTrue(len(t_cashes1) == len(s_cashes1), 'cash接口测试失败!') for i in range(0, len(t_cashes1) - 1): # 最后一根强平了无法比较 self.assertAlmostEqual(t_cashes1[i], s_cashes1[i]) for i in range(0, len(profile.all_holdings())): hd = all_holdings[i] hd0 = all_holdings0[i] hd1 = all_holdings1[i] hd2 = all_holdings2[i] self.assertTrue( hd['cash'] == hd0['cash'] + hd1['cash'] + hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue( hd['commission'] == hd0['commission'] + hd1['commission'] + hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue( hd['equity'] == hd0['equity'] + hd1['equity'] + hd2['equity'], 'all_holdings接口测试失败!')
def test_case(self): lmg = Contract.long_margin_ratio('stock.TEST') multi = Contract.volume_multiple('stock.TEST') smg = Contract.short_margin_ratio('stock.TEST') profiles = None class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" self.cashes = [] self.equities = [] def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [bt1, bt2, bt3]: ctx.buy(ctx.close, 1) elif ctx.pos() >= 2 and curtime == st1: ctx.sell(ctx.close, 2) elif ctx.pos() >= 1 and curtime == st2: ctx.sell(ctx.close, 1) self.cashes.append(ctx.cash()) self.equities.append(ctx.equity()) def test(self, test): equities, cashes, open_equities, open_casheses, dts =\ trade_closed_curbar(source, capital * 0.3, lmg, smg, multi, 1) test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes)): test.assertAlmostEqual(self.cashes[i], open_casheses[i]) test.assertAlmostEqual(self.equities[i], open_equities[i]) for i, hd in enumerate(profiles[0].all_holdings()): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], equities[i]) test.assertAlmostEqual(hd['cash'], cashes[i]) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" self.cashes = [] def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [bt1, bt2, bt3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 1) elif curtime == st1: if ctx.pos() >= 3: assert(ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) if ctx.pos('short') >= 3: assert(ctx.pos('short') == 3 and '默认持仓查询测试失败!') ctx.cover(ctx.close, 2) elif curtime == st2: if ctx.pos() >= 1: ctx.sell(ctx.close, 1) if ctx.pos('short') >= 1: ctx.cover(ctx.close, 1) self.cashes.append(ctx.test_cash()) def test(self, test): e0, c0, oe0, oc0, dts = trade_closed_curbar(source, capital * 0.3 / 2, lmg, smg, multi, 1) e1, c1, oe1, oc1, dts = trade_closed_curbar(source, capital * 0.3 / 2, lmg, smg, multi, -1) equities = [x + y for x, y in zip(e0, e1)] cashes = [x + y for x, y in zip(c0, c1)] for i, hd in enumerate(profiles[1].all_holdings()): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], equities[i]) test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes) - 1): # 最后一根强平了无法比较 test.assertAlmostEqual(self.cashes[i], cashes[i]) class DemoStrategy3(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): return a1 = DemoStrategy1('A1') a2 = DemoStrategy2('A2') a3 = DemoStrategy3('A3') profiles = add_strategies(['stock.TEST-1.Minute'], [ { 'strategy': a1, 'capital': capital * 0.3, }, { 'strategy': a2, 'capital': capital * 0.3, }, { 'strategy': a3, 'capital': capital * 0.4, }, ]) a1.test(self) a2.test(self) all_holdings = Profile.all_holdings_sum(profiles) self.assertTrue(len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') for i in range(0, len(all_holdings)): hd = all_holdings[i] hd0 = profiles[0].all_holdings()[i] hd1 = profiles[1].all_holdings()[i] hd2 = profiles[2].all_holdings()[i] self.assertTrue(hd['cash'] == hd0['cash'] + hd1['cash'] + hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue(hd['commission'] == hd0['commission'] + hd1['commission'] + hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue(hd['equity'] == hd0['equity'] + hd1['equity'] + hd2['equity'], 'all_holdings接口测试失败!')
OFFSET, capital, bt1, bt2, bt3, st1, st2, st3, ) fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE.csv') source = pd.read_csv(fname, parse_dates=True, index_col=0) lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') class TestOneDataOneCombination(unittest.TestCase): """ 分钟线日内限价交易, 且当根bar成交。 测试: Strategy1, Strategy2: profile.all_holdings(x) ctx.buy, ctx.sell ctx.cash(), ctx.equity() Strategy3: 隔夜未成交订单自动清空。 保证测单动作从下一个Bar开始执行。 ctx.cancel(), ctx.open_orders()
def test_case(self): ## @TODO 持仓过夜,不卖,累加仓位。 # @todo profile #signals 盈利 # @TODO deals DemoStrategy2 t_cashes0, t_cashes1 = [], [] class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) else: if curtime == sell1: assert(ctx.pos() == 3 and '持仓测试失败!') ctx.sell(ctx.close, 2) elif curtime == sell2: assert(ctx.pos() == 1 and '持仓测试失败!') ctx.sell(ctx.close, 1) ## 前一根的交易信号在当前价格撮合后的可用资金 t_cashes0.append(ctx.test_cash()) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [buy1, buy2, buy3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 2) else: if curtime == sell1: assert(ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) assert(ctx.pos('short') == 6 and '持仓测试失败!') ctx.cover(ctx.close, 4) elif curtime == sell2: assert(ctx.pos('long') == 1 and '持仓测试失败!') ctx.sell(ctx.close, 1) assert(ctx.pos('short') == 2 and '持仓测试失败!') ctx.cover(ctx.close, 2) t_cashes1.append(ctx.test_cash()) class DemoStrategy3(Strategy): """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.curbar == 1: ctx.short(138, 1) ctx.short(138, 1) ctx.buy(ctx.close, 1) elif ctx.curbar == 3: # 保证下一根撤单成功, 而非当前这根。 assert(len(ctx.open_orders) == 2) ctx.cancel(ctx.open_orders[0]) assert(len(ctx.open_orders) == 2 and '撤单测试失败') elif ctx.curbar == 4: assert(len(ctx.open_orders) == 1 and '撤单测试失败!') elif ctx.curbar == 5: assert(ctx.pos() == 1) ctx.sell(300, 1) # 下无法成交的平仓,测试持仓。 elif ctx.curbar == 7: assert(ctx.pos() == 0 and '持仓测试失败!') assert(len(ctx.open_orders) == 2 and '撤单测试失败!') order = filter(lambda x: x.side == TradeSide.PING, ctx.open_orders)[0] ctx.cancel(order) elif ctx.curbar == 8: assert(len(ctx.open_orders) == 1 and '撤单测试失败!') assert(ctx.pos() == 1 and '持仓测试失败!') if ctx.curbar > 1 and ctx.datetime[0].date() != ctx.datetime[1].date(): assert(len(ctx.open_orders) == 0 and '隔夜订单清空测试失败') set_symbols(['future.TEST-1.Minute'], window_size) profile = add_strategy([DemoStrategy1('A1'), DemoStrategy2('A2'), DemoStrategy3('A3')], { 'capital': capital, 'ratio': [0.3, 0.3, 0.4] }) run() # all_holdings, cash() all_holdings = profile.all_holdings() all_holdings0 = profile.all_holdings(0) all_holdings1 = profile.all_holdings(1) all_holdings2 = profile.all_holdings(2) self.assertTrue(len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') s_equity0, s_cashes0, dts = holdings_buy_maked_curbar(source, capital*0.3, lmg, multi) self.assertTrue(len(t_cashes0) == len(s_cashes0), 'cash接口测试失败!') for i in range(0, len(t_cashes0)-1): # 最后一根强平了无法比较 self.assertTrue(np.isclose(t_cashes0[i],s_cashes0[i]), 'cash接口测试失败!') self.assertTrue(len(all_holdings) == len(s_equity0), 'all_holdings接口测试失败!') for i, hd in enumerate(all_holdings0): self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertTrue(np.isclose(hd['equity'], s_equity0[i]), 'all_holdings接口测试失败!') # 确保资金够用,所以不影响 e0, c0, dts = holdings_buy_maked_curbar(source, capital*0.3/2, lmg, multi) e1, c1, dts = holdings_short_maked_curbar(source, capital*0.3/2, smg, multi) s_equity1 = [x + y for x, y in zip(e0, e1)] s_cashes1 = [x + y for x, y in zip(c0, c1)] self.assertTrue(len(t_cashes1) == len(s_cashes1), 'cash接口测试失败!') for i in range(0, len(t_cashes1)-1): # 最后一根强平了无法比较 self.assertTrue(np.isclose(t_cashes1[i],s_cashes1[i]), 'cash接口测试失败!') for i, hd in enumerate(profile.all_holdings(1)): self.assertTrue(np.isclose(s_equity0[i]-capital*0.3, 0-(s_equity1[i]-capital*0.3)), '测试代码错误!') self.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') self.assertTrue(np.isclose(hd['equity'], s_equity1[i]), 'all_holdings接口测试失败!') for i in range(0, len(profile.all_holdings())): hd = all_holdings[i] hd0 = all_holdings0[i] hd1 = all_holdings1[i] hd2 = all_holdings2[i] self.assertTrue(hd['cash'] == hd0['cash']+hd1['cash']+hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue(hd['commission'] == hd0['commission']+ hd1['commission']+hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue(hd['equity'] == hd0['equity']+hd1['equity']+hd2['equity'], 'all_holdings接口测试失败!') # holding hd0 = profile.holding(0) hd1 = profile.holding(1) hd2 = profile.holding(2) hd = profile.holding() self.assertTrue(hd0['equity']+hd1['equity']+hd2['equity']==hd['equity'], 'holdings接口测试失败!') self.assertTrue(hd0['cash']+hd1['cash']+hd2['cash']==hd['cash'], 'holdings接口测试失败!') self.assertTrue(hd0['commission']+hd1['commission']+hd2['commission']==hd['commission'], 'holdings接口测试失败!') self.assertTrue(hd0['history_profit']+hd1['history_profit']+hd2['history_profit']==hd['history_profit'], 'holdings接口测试失败!') hd0last = profile.all_holdings(0)[-1] self.assertTrue(hd0last['equity'] == hd0['equity'], 'holdings接口测试失败!') self.assertTrue(hd0last['cash'] == hd0['cash'], 'holdings接口测试失败!') self.assertTrue(hd0last['commission'] == hd0['commission'], 'holdings接口测试失败!') self.assertTrue(len(profile.all_holdings()) == len(s_equity0) and len(s_equity0) > 0, 'holdings接口测试失败!')
def test_case2(self): """ 测试限价的延迟成交, 与是否是期货还是股票无关。 测试延迟成交的资金占用 """ buy_entries, sell_entries = [], [] short_entries, cover_entries = [], [] cashes0, cashes1, cashes2 = [], [], [] class DemoStrategyBuy(Strategy): """ 只开多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0] in buy_entries: ctx.buy(ctx.low - OFFSET, 1) # 确保在下一根Bar成交 # 默认多头 elif ctx.pos() > 0 and ctx.datetime[0].time() == st1: ctx.sell(ctx.close, ctx.pos()) cashes0.append(ctx.test_cash()) class DemoStrategyShort(Strategy): """ 只开空头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0] in short_entries: ctx.short(ctx.high + OFFSET, 1) elif ctx.pos('short') > 0 and ctx.datetime[0].time() == st1: ctx.cover(ctx.close, ctx.pos('short')) cashes1.append(ctx.test_cash()) class DemoStrategySell(Strategy): """ 只开多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0].time() == bt1: ctx.buy(ctx.close, 1) elif ctx.pos('long') > 0 and ctx.datetime[0] in sell_entries: ctx.sell(ctx.high + OFFSET, ctx.pos()) elif ctx.pos('long') > 0 and ctx.datetime[0].time() == st3: ctx.sell(ctx.close, ctx.pos()) cashes2.append(ctx.test_cash()) class DemoStrategyCover(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): if ctx.datetime[0].time() == bt1: ctx.short(ctx.close, 1) elif ctx.pos('short') > 0 and ctx.datetime[0] in cover_entries: ctx.cover(ctx.low - OFFSET, ctx.pos('short')) elif ctx.pos('short') > 0 and ctx.datetime[0].time() == st3: ctx.cover(ctx.close, ctx.pos('short')) set_symbols(['future.TEST-1.Minute']) profile = add_strategy([ DemoStrategyBuy('B1'), DemoStrategySell('B2'), DemoStrategyShort('B3'), DemoStrategyCover('B4') ], { 'capital': capital, 'ratio': [0.25, 0.25, 0.25, 0.25] }) buy_entries, sell_entries, short_entries, cover_entries = entries_maked_nextbar( source) run() # buy lmg = Contract.long_margin_ratio('future.TEST') multi = Contract.volume_multiple('future.TEST') smg = Contract.short_margin_ratio('future.TEST') target, cashes, dts = holdings_buy_maked_nextbar( source, buy_entries, capital / 4, lmg, multi) self.assertTrue( len(profile.all_holdings(0)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(0)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) for i in range(0, len(cashes0) - 1): # 最后一根强平了无法比较 self.assertAlmostEqual(cashes0[i], cashes[i]) # short target, cashes, dts = holdings_short_maked_nextbar( source, short_entries, capital / 4, smg, multi) self.assertTrue( len(profile.all_holdings(2)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(2)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) for i in range(0, len(cashes1) - 1): self.assertAlmostEqual(cashes1[i], cashes[i]) ## sell target, cashes, dts = holdings_sell_maked_nextbar( source, sell_entries, capital / 4, lmg, multi) self.assertTrue( len(profile.all_holdings(1)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(1)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) self.assertAlmostEqual(hd['cash'], cashes[i]) for i in range(0, len(cashes2) - 1): self.assertAlmostEqual(cashes2[i], cashes[i]) # cover target, cashes, dts = holdings_cover_maked_nextbar( source, cover_entries, capital / 4, smg, multi) self.assertTrue( len(profile.all_holdings(3)) == len(target) and len(target) > 0, '模拟器测试失败!') for i, hd in enumerate(profile.all_holdings(3)): self.assertTrue(hd['datetime'] == dts[i], '模拟器测试失败!') self.assertAlmostEqual(hd['equity'], target[i]) self.assertAlmostEqual(hd['cash'], cashes[i]) #from quantdigger.digger import plotting #plotting.plot_strategy(profile.data(), deals=profile.deals(0)) ## @TODO 模拟器make_market的运行次数 return
def test_case(self): lmg = Contract.long_margin_ratio('stock.TEST') multi = Contract.volume_multiple('stock.TEST') smg = Contract.short_margin_ratio('stock.TEST') profile = None class DemoStrategy1(Strategy): """ 限价只买多头仓位的策略 """ def on_init(self, ctx): """初始化数据""" self.cashes = [] self.equities = [] def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [bt1, bt2, bt3]: ctx.buy(ctx.close, 1) elif ctx.pos() >= 2 and curtime == st1: ctx.sell(ctx.close, 2) elif ctx.pos() >= 1 and curtime == st2: ctx.sell(ctx.close, 1) self.cashes.append(ctx.cash()) self.equities.append(ctx.equity()) def test(self, test): equities, cashes, open_equities, open_casheses, dts =\ trade_closed_curbar(source, capital * 0.3, lmg, smg, multi, 1) test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes)): test.assertAlmostEqual(self.cashes[i], open_casheses[i]) test.assertAlmostEqual(self.equities[i], open_equities[i]) for i, hd in enumerate(profile.all_holdings(0)): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], equities[i]) test.assertAlmostEqual(hd['cash'], cashes[i]) class DemoStrategy2(Strategy): """ 限价买多卖空的策略 """ def on_init(self, ctx): """初始化数据""" self.cashes = [] def on_bar(self, ctx): curtime = ctx.datetime[0].time() if curtime in [bt1, bt2, bt3]: ctx.buy(ctx.close, 1) ctx.short(ctx.close, 1) elif curtime == st1: if ctx.pos() >= 3: assert(ctx.pos() == 3 and '默认持仓查询测试失败!') ctx.sell(ctx.close, 2) if ctx.pos('short') >= 3: assert(ctx.pos('short') == 3 and '默认持仓查询测试失败!') ctx.cover(ctx.close, 2) elif curtime == st2: if ctx.pos() >= 1: ctx.sell(ctx.close, 1) if ctx.pos('short') >= 1: ctx.cover(ctx.close, 1) self.cashes.append(ctx.test_cash()) def test(self, test): e0, c0, oe0, oc0, dts = trade_closed_curbar(source, capital * 0.3 / 2, lmg, smg, multi, 1) e1, c1, oe1, oc1, dts = trade_closed_curbar(source, capital * 0.3 / 2, lmg, smg, multi, -1) equities = [x + y for x, y in zip(e0, e1)] cashes = [x + y for x, y in zip(c0, c1)] for i, hd in enumerate(profile.all_holdings(1)): test.assertTrue(hd['datetime'] == dts[i], 'all_holdings接口测试失败!') test.assertAlmostEqual(hd['equity'], equities[i]) test.assertTrue(len(self.cashes) == len(cashes), 'cash接口测试失败!') for i in range(0, len(self.cashes) - 1): # 最后一根强平了无法比较 test.assertAlmostEqual(self.cashes[i], cashes[i]) class DemoStrategy3(Strategy): def on_init(self, ctx): """初始化数据""" pass def on_bar(self, ctx): return set_symbols(['stock.TEST-1.Minute']) a1 = DemoStrategy1('A1') a2 = DemoStrategy2('A2') a3 = DemoStrategy3('A3') profile = add_strategy([a1, a2, a3], { 'capital': capital, 'ratio': [0.3, 0.3, 0.4] }) run() a1.test(self) a2.test(self) all_holdings = profile.all_holdings() self.assertTrue(len(source) > 0 and len(source) == len(all_holdings), '模拟器测试失败!') for i in range(0, len(profile.all_holdings())): hd = all_holdings[i] hd0 = profile.all_holdings(0)[i] hd1 = profile.all_holdings(1)[i] hd2 = profile.all_holdings(2)[i] self.assertTrue(hd['cash'] == hd0['cash'] + hd1['cash'] + hd2['cash'], 'all_holdings接口测试失败!') self.assertTrue(hd['commission'] == hd0['commission'] + hd1['commission'] + hd2['commission'], 'all_holdings接口测试失败!') self.assertTrue(hd['equity'] == hd0['equity'] + hd1['equity'] + hd2['equity'], 'all_holdings接口测试失败!')