Exemple #1
0
            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])
Exemple #2
0
    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])
Exemple #3
0
    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])
Exemple #4
0
def pcontract(contract, period):
    """ 构建周期合约结构的便捷方式。
    
       :param str contract: 合约如:'IF000.SHEF'
       :param str Period: 周期如:'10.Minute' 
       :return: 周期合约
       :rtype: PContract
    """
    from quantdigger.datastruct import PContract, Contract, Period
    return PContract(Contract(contract), Period(period))
Exemple #5
0
def stock(code, period='1.Day'):
    """ 构建周期合约结构的便捷方式。
    
       :param str code: 股票代码。
       :param str period: 回测周期。
       :return: 周期合约。
       :rtype: PContract
    """
    from quantdigger.datastruct import PContract, Contract, Period
    return PContract(Contract('%s.stock' % code), Period(period))
Exemple #6
0
    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_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])
Exemple #8
0
def stock(code, period='1.Day'):
    """ 构建周期合约结构的便捷方式。
    
    Args:
        code (str) : 股票代码
        period(str): 回测周期

    Returns:
        PContract. 周期合约
    """
    from quantdigger.datastruct import PContract, Contract, Period
    return PContract(Contract('%s.stock' % code), Period(period))
Exemple #9
0
            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])
Exemple #10
0
 def buy(self, direction, price, quantity, price_type='LMT', contract=None):
     """ 开仓。
     
        :param str/int direction: 下单方向。多头 - 'long' / 1 ;空头 - 'short'  / 2
        :param float price: 价格。
        :param int quantity: 数量。
        :param str/int price_type: 下单价格类型。限价单 - 'lmt' / 1;市价单 - 'mkt' / 2
     """
     contract = None
     con = Contract(contract) if contract else self._main_contract
     self._orders.append(
         Order(self.datetime, con,
               PriceType.arg_to_type(price_type), TradeSide.KAI,
               Direction.arg_to_type(direction), float(price), quantity))
Exemple #11
0
 def test(self, test, profiles):
     lmg = Contract.long_margin_ratio('600522.SH')
     multi = Contract.volume_multiple('600522.SH')
     test.assertTrue(lmg == 1)
     test.assertTrue(multi == 1)
     fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600522.csv')
     source = pd.read_csv(fname, parse_dates=True, index_col=0)
     equities, cashes, open_equities, open_cashes, dts = \
         buy_monday_sell_friday(source, capital * 0.3, lmg, multi)
     count = 0
     all_holdings0 = profiles[0].all_holdings()
     for i, hd in enumerate(all_holdings0):
         dt = hd['datetime']
         if dt in cashes:
             test.assertAlmostEqual(hd['cash'], cashes[dt])
             test.assertAlmostEqual(hd['equity'], equities[dt])
             test.assertAlmostEqual(self._cashes[dt], open_cashes[dt])
             test.assertAlmostEqual(self._equities[dt], open_equities[dt])
             count += 1
         else:
             # 两支股票的混合,总数据长度和source不一样。
             test.assertAlmostEqual(all_holdings0[i - 1]['cash'], hd['cash'])
             test.assertAlmostEqual(all_holdings0[i - 1]['equity'], hd['equity'])
     test.assertTrue(count == len(dts))
Exemple #12
0
 def cover(self, price, quantity, symbol=None):
     """ 平空仓。
     
     Args:
        price (float): 价格, 0表市价。
        quantity (int): 数量。
        symbol (str): 合约
     """
     if not self._trading:
         raise Exception('只有on_bar函数内能下单!')
     contract = Contract(symbol) if symbol else copy.deepcopy(
         self._cur_data_context.contract)
     price_type = PriceType.MKT if price == 0 else PriceType.LMT
     self._cur_strategy_context.sell(Direction.SHORT, price, quantity,
                                     price_type, contract)
Exemple #13
0
 def buy(self, price, quantity, symbol=None):
     """ 开多仓    
     
     Args:
         price (float): 价格, 0表市价。
         quantity (int): 数量。
         symbol (str): 合约
     """
     if not self._trading:
         raise Exception('只有on_bar函数内能下单!')
     contract = Contract(
         symbol) if symbol else self._cur_data_context.contract
     price_type = PriceType.MKT if price == 0 else PriceType.LMT
     self._cur_strategy_context.buy(Direction.LONG, price, quantity,
                                    price_type, contract)
Exemple #14
0
 def test(self, test, profile):
     lmg = Contract.long_margin_ratio('600522.SH')
     multi = Contract.volume_multiple('600522.SH')
     test.assertTrue(lmg == 1)
     test.assertTrue(multi == 1)
     fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600522.csv')
     source = pd.read_csv(fname, parse_dates=True, index_col=0)
     equities, cashes, open_equities, open_cashes, dts = \
         buy_monday_sell_friday(source, capital * 0.3, lmg, multi)
     count = 0
     all_holdings0 = profile.all_holdings(0)
     for i, hd in enumerate(all_holdings0):
         dt = hd['datetime']
         if dt in cashes:
             test.assertAlmostEqual(hd['cash'], cashes[dt])
             test.assertAlmostEqual(hd['equity'], equities[dt])
             test.assertAlmostEqual(self._cashes[dt], open_cashes[dt])
             test.assertAlmostEqual(self._equities[dt], open_equities[dt])
             count += 1
         else:
             # 两支股票的混合,总数据长度和source不一样。
             test.assertAlmostEqual(all_holdings0[i - 1]['cash'], hd['cash'])
             test.assertAlmostEqual(all_holdings0[i - 1]['equity'], hd['equity'])
     test.assertTrue(count == len(dts))
Exemple #15
0
    def cover(self, price, quantity, symbol=None):
        """ 平空仓。

        Args:
           price (float): 价格, 0表市价。
           quantity (int): 数量。
           symbol (str): 合约
        """
        if not self._trading:
            raise Exception('只有on_bar函数内能下单!')
        if symbol:
            contract = Contract(symbol) if isinstance(symbol, str) else symbol
        else:
            contract = self._cur_data_context.contract
        price_type = PriceType.MKT if price == 0 else PriceType.LMT
        self._cur_strategy_context.cover(price, quantity, price_type, contract)
Exemple #16
0
    def sell(self, price, quantity, symbol=None):
        """ 平多仓。

        Args:
           price (float): 价格, 0表市价。
           quantity (int): 数量。
           symbol (str): 合约
        """
        if not self.on_bar:
            raise Exception('只有on_bar函数内能下单!')
        if symbol:
            contract = Contract(symbol) if isinstance(symbol, str) else symbol
        else:
            contract = self.contract
        price_type = PriceType.MKT if price == 0 else PriceType.LMT
        self._orders.append(
            Order(None, contract, price_type, TradeSide.CLOSE, Direction.LONG,
                  float(price), quantity))
Exemple #17
0
    def position(self, direction='long', symbol=None):
        """ 当前仓位。

        Args:
            direction (str/int): 持仓方向。多头 - 'long' / 1 ;空头 - 'short'  / 2
            , 默认为多头。

            symbol (str): 字符串合约,默认为None表示主合约。

        Returns:
            Position. 该合约的持仓
        """
        if not self._trading:
            raise Exception('只有on_bar函数内能查询当前持仓!')
        direction = Direction.arg_to_type(direction)
        contract = Contract(symbol) if symbol else \
            self._cur_data_context.contract
        # @TODO assert direction
        return self._cur_strategy_context.position(contract, direction)
Exemple #18
0
    def position(self, direction='long', symbol=None):
        """ 合约当前持仓仓位。

        Args:
            direction (str/int): 持仓方向。多头 - 'long' / 1 ;空头 - 'short'  / 2
            , 默认为多头。

            symbol (str): 字符串合约,默认为None表示主合约。

        Returns:
            Position. 该合约的持仓
        """
        if not self.on_bar:
            raise Exception('只有on_bar函数内能查询当前持仓!')
        direction = Direction.arg_to_type(direction)
        contract = Contract(symbol) if symbol else \
            self.contract
        # @TODO assert direction
        try:
            poskey = PositionKey(contract, direction)
            return self.blotter.positions[poskey]
        except KeyError:
            return None
Exemple #19
0
    entries_maked_nextbar,
    market_trade_closed_curbar,
    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:
           隔夜未成交订单自动清空。
Exemple #20
0
    entries_maked_nextbar,
    market_trade_closed_curbar,
    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:
           隔夜未成交订单自动清空。
 def _mk_contract(code, exchage):
     s = '%s.%s' % (code, exchage)
     return Contract(s)
Exemple #22
0
    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接口测试失败!')
Exemple #23
0
    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接口测试失败!')
Exemple #24
0
    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接口测试失败!')
Exemple #25
0
    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
Exemple #26
0
    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接口测试失败!')
Exemple #27
0
    def test_case(self):
        t_cashes0, t_equity0 = {}, {}
        t_cashes1, t_equity1 = {}, {}

        class DemoStrategy1(Strategy):
            """ 限价只买多头仓位的策略 """
            def on_init(self, ctx):
                """初始化数据"""
                ctx.tobuy = False
                ctx.tosell = False

            def on_symbol(self, ctx):
                """"""
                weekday = ctx.datetime[0].weekday()
                if weekday == 0:
                    ctx.tobuy = True
                elif weekday == 4:
                    ctx.tosell = True

            def on_bar(self, ctx):
                #weekday = ctx.datetime[0].weekday()
                if ctx['600521'].tobuy:
                    ctx.buy(ctx['600521'].close, 1)
                if ctx['600521'].tosell and ctx.pos(symbol='600521.SH') > 0:
                    ctx.sell(ctx['600521'].close, ctx.pos(symbol='600521.SH'))
                ctx['600521'].tobuy = False
                ctx['600521'].tosell = False
                t_cashes0[ctx.datetime[0]] = ctx.test_cash()
                t_equity0[ctx.datetime[0]] = ctx.test_equity()

        class DemoStrategy2(Strategy):
            """ 限价买多卖空的策略 """
            def __init__(self, name):
                super(DemoStrategy2, self).__init__(name)
                self.tobuys = []
                self.tosells = []

            def on_symbol(self, ctx):
                """"""
                weekday = ctx.datetime[0].weekday()
                if weekday == 0:
                    self.tobuys.append(ctx.symbol)
                elif weekday == 4:
                    self.tosells.append(ctx.symbol)

            def on_bar(self, ctx):
                """初始化数据"""
                ## @TODO all_positions
                for symbol in self.tobuys:
                    ctx.buy(ctx[symbol].close, 1, symbol)
                for symbol in self.tosells:
                    if ctx.pos(symbol=symbol) > 0:
                        ctx.sell(ctx[symbol].close, ctx.pos(symbol=symbol),
                                 symbol)

                t_equity1[ctx.datetime[0]] = ctx.test_equity()
                t_cashes1[ctx.datetime[0]] = ctx.test_cash()
                self.tobuys = []
                self.tosells = []

        class DemoStrategy3(Strategy):
            """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """
            def on_init(self, ctx):
                """初始化数据"""
                pass

            def on_bar(self, ctx):
                return

        set_symbols(['600521', '600522'])
        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)
        lmg = Contract.long_margin_ratio('600521.SH')
        multi = Contract.volume_multiple('600521.SH')
        fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600521.csv')
        source = pd.read_csv(fname, parse_dates=True, index_col=0)
        s_equity0, s_cashes0, dts = buy_monday_sell_friday(
            source, capital * 0.3, lmg, multi)
        count = 0
        for i, hd in enumerate(all_holdings0):
            # 刚好最后一根没持仓,无需考虑强平, 见weekday输出
            dt = hd['datetime']
            if dt in s_cashes0:
                self.assertAlmostEqual(hd['cash'], s_cashes0[dt])
                self.assertAlmostEqual(t_cashes0[dt], s_cashes0[dt])
                self.assertAlmostEqual(hd['equity'], s_equity0[dt])
                self.assertAlmostEqual(t_equity0[dt], s_equity0[dt])
                count += 1
            else:
                self.assertAlmostEqual(all_holdings0[i - 1]['cash'],
                                       hd['cash'])
                self.assertAlmostEqual(all_holdings0[i - 1]['equity'],
                                       hd['equity'])
        self.assertTrue(count == len(dts))

        # test Strategy2
        fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600522.csv')
        source2 = pd.read_csv(fname, parse_dates=True, index_col=0)
        s_equity0, s_cashes0, dts = buy_monday_sell_friday(
            source, capital * 0.3 / 2, lmg, multi)
        s_equity1, s_cashes1, dts = buy_monday_sell_friday(
            source2, capital * 0.3 / 2, 1, 1)
        last_equity0 = 0
        last_equity1 = 0
        last_cash0 = 0
        last_cash1 = 0
        for i, hd in enumerate(all_holdings1):
            # 刚好最后一根没持仓,无需考虑强平, 见weekday输出
            dt = hd['datetime']
            equity = 0
            cash = 0
            if dt in s_equity0:
                equity += s_equity0[dt]
                cash += s_cashes0[dt]
                last_equity0 = s_equity0[dt]
                last_cash0 = s_cashes0[dt]
            else:
                equity += last_equity0
                cash += last_cash0
            if dt in s_equity1:
                equity += s_equity1[dt]
                cash += s_cashes1[dt]
                last_equity1 = s_equity1[dt]
                last_cash1 = s_cashes1[dt]
            else:
                equity += last_equity1
                cash += last_cash1
            self.assertAlmostEqual(hd['equity'], equity)
            self.assertAlmostEqual(hd['cash'], cash)
            self.assertAlmostEqual(t_cashes1[dt], cash)
            self.assertAlmostEqual(t_equity1[dt], equity)
Exemple #28
0
    def test_case(self):
        t_cashes0, t_equity0 = {}, { }
        t_cashes1, t_equity1 = {}, { }

        class DemoStrategy1(Strategy):
            """ 限价只买多头仓位的策略 """
            
            def on_init(self, ctx):
                """初始化数据""" 
                ctx.tobuy = False
                ctx.tosell = False

            def on_symbol(self, ctx):
                """""" 
                weekday = ctx.datetime[0].weekday()
                if weekday == 0:
                    ctx.tobuy = True
                elif weekday == 4:
                    ctx.tosell = True
                
            def on_bar(self, ctx):
                #weekday = ctx.datetime[0].weekday()
                if ctx['600521'].tobuy:
                    ctx.buy(ctx['600521'].close, 1) 
                if ctx['600521'].tosell and ctx.pos(symbol='600521.SH')>0:
                    ctx.sell(ctx['600521'].close, ctx.pos(symbol='600521.SH')) 
                ctx['600521'].tobuy = False
                ctx['600521'].tosell = False
                t_cashes0[ctx.datetime[0]] = ctx.test_cash()
                t_equity0[ctx.datetime[0]] = ctx.test_equity()


        class DemoStrategy2(Strategy):
            """ 限价买多卖空的策略 """
            def __init__(self, name):
                super(DemoStrategy2, self).__init__(name)
                self.tobuys = []
                self.tosells = []

            def on_symbol(self, ctx):
                """""" 
                weekday = ctx.datetime[0].weekday()
                if weekday == 0:
                    self.tobuys.append(ctx.symbol)
                elif weekday == 4:
                    self.tosells.append(ctx.symbol)
            
            def on_bar(self, ctx):
                """初始化数据""" 
                ## @TODO all_positions
                for symbol in self.tobuys:
                    ctx.buy(ctx[symbol].close, 1, symbol)
                for symbol in self.tosells:
                    if ctx.pos(symbol=symbol)>0:
                        ctx.sell(ctx[symbol].close, ctx.pos(symbol=symbol), symbol)

                t_equity1[ctx.datetime[0]] = ctx.test_equity()
                t_cashes1[ctx.datetime[0]] = ctx.test_cash()
                self.tobuys = []
                self.tosells = []


        class DemoStrategy3(Strategy):
            """ 测试平仓未成交时的持仓,撤单后的持仓,撤单。 """
            def on_init(self, ctx):
                """初始化数据""" 
                pass

            def on_bar(self, ctx):
                return
                
        set_symbols(['600521', '600522'])
        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)
        lmg = Contract.long_margin_ratio('600521.SH')
        multi = Contract.volume_multiple('600521.SH')
        fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600521.csv')
        source = pd.read_csv(fname, parse_dates=True, index_col=0)
        s_equity0, s_cashes0, dts = buy_monday_sell_friday(source, capital*0.3, lmg, multi)
        count = 0
        for i, hd in enumerate(all_holdings0):
            # 刚好最后一根没持仓,无需考虑强平, 见weekday输出
            dt = hd['datetime']
            if dt in s_cashes0:
                self.assertAlmostEqual(hd['cash'], s_cashes0[dt])
                self.assertAlmostEqual(t_cashes0[dt], s_cashes0[dt])
                self.assertAlmostEqual(hd['equity'], s_equity0[dt])
                self.assertAlmostEqual(t_equity0[dt], s_equity0[dt])
                count += 1
            else:
                self.assertAlmostEqual(all_holdings0[i-1]['cash'], hd['cash'])
                self.assertAlmostEqual(all_holdings0[i-1]['equity'], hd['equity'])
        self.assertTrue(count == len(dts))

        # test Strategy2
        fname = os.path.join(os.getcwd(), 'data', '1DAY', 'SH', '600522.csv')
        source2 = pd.read_csv(fname, parse_dates=True, index_col=0)
        s_equity0, s_cashes0, dts = buy_monday_sell_friday(source, capital*0.3/2, lmg, multi)
        s_equity1, s_cashes1, dts = buy_monday_sell_friday(source2, capital*0.3/2, 1, 1)
        last_equity0 = 0
        last_equity1 = 0
        last_cash0 = 0
        last_cash1 = 0
        for i, hd in enumerate(all_holdings1):
            # 刚好最后一根没持仓,无需考虑强平, 见weekday输出
            dt = hd['datetime']
            equity = 0
            cash = 0
            if dt in s_equity0:
                equity += s_equity0[dt] 
                cash += s_cashes0[dt] 
                last_equity0 = s_equity0[dt]
                last_cash0 = s_cashes0[dt]
            else:
                equity += last_equity0
                cash += last_cash0
            if dt in s_equity1:
                equity += s_equity1[dt] 
                cash += s_cashes1[dt] 
                last_equity1 = s_equity1[dt]
                last_cash1 = s_cashes1[dt]
            else:
                equity += last_equity1
                cash += last_cash1
            self.assertAlmostEqual(hd['equity'], equity)
            self.assertAlmostEqual(hd['cash'], cash)
            self.assertAlmostEqual(t_cashes1[dt], cash)
            self.assertAlmostEqual(t_equity1[dt], equity)
Exemple #29
0
def deserialize_all_contracts(contracts):
    return [Contract.from_string(strcon) for strcon in contracts]
Exemple #30
0
    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
Exemple #31
0
def deserialize_all_contracts(contracts):
    return [Contract.from_string(strcon) for strcon in contracts]
Exemple #32
0
    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接口测试失败!')
Exemple #33
0
    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接口测试失败!')