Exemplo n.º 1
0
    def test_volume_share_slippage(self):
        event = Event({
            'volume':
            200,
            'type':
            4,
            'price':
            3.0,
            'datetime':
            datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'high':
            3.15,
            'low':
            2.85,
            'sid':
            133,
            'source_id':
            'test_source',
            'close':
            3.0,
            'dt':
            datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'open':
            3.0
        })

        slippage_model = VolumeShareSlippage()

        open_orders = [
            Order(
                **{
                    'dt': datetime.datetime(
                        2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                    'amount': 100,
                    'filled': 0,
                    'sid': 133
                })
        ]

        txns = slippage_model.simulate(event, open_orders)

        self.assertEquals(len(txns), 1)
        txn = txns[0]

        expected_txn = {
            'price': float(3.01875),
            'dt': datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'amount': int(50),
            'sid': int(133),
            'commission': None,
            'type': DATASOURCE_TYPE.TRANSACTION,
            'order_id': open_orders[0].id
        }

        self.assertIsNotNone(txn)

        # TODO: Make expected_txn an Transaction object and ensure there
        # is a __eq__ for that class.
        self.assertEquals(expected_txn, txn.__dict__)
Exemplo n.º 2
0
    def transaction_sim(self, **params):
        """ This is a utility method that asserts expected
        results for conversion of orders to transactions given a
        trade history"""

        trade_count = params['trade_count']
        trade_interval = params['trade_interval']
        order_count = params['order_count']
        order_amount = params['order_amount']
        order_interval = params['order_interval']
        expected_txn_count = params['expected_txn_count']
        expected_txn_volume = params['expected_txn_volume']
        # optional parameters
        # ---------------------
        # if present, alternate between long and short sales
        alternate = params.get('alternate')
        # if present, expect transaction amounts to match orders exactly.
        complete_fill = params.get('complete_fill')

        sid = 1
        sim_params = factory.create_simulation_parameters()
        trade_sim = TransactionSimulator()
        price = [10.1] * trade_count
        volume = [100] * trade_count
        start_date = sim_params.first_open

        generated_trades = factory.create_trade_history(
            sid, price, volume, trade_interval, sim_params)

        if alternate:
            alternator = -1
        else:
            alternator = 1

        order_date = start_date
        for i in xrange(order_count):
            order = Order(
                **{
                    'sid': sid,
                    'amount': order_amount * alternator**i,
                    'dt': order_date
                })

            trade_sim.place_order(order)

            order_date = order_date + order_interval
            # move after market orders to just after market next
            # market open.
            if order_date.hour >= 21:
                if order_date.minute >= 00:
                    order_date = order_date + timedelta(days=1)
                    order_date = order_date.replace(hour=14, minute=30)

        # there should now be one open order list stored under the sid
        oo = trade_sim.open_orders
        self.assertEqual(len(oo), 1)
        self.assertTrue(sid in oo)
        order_list = oo[sid]
        self.assertEqual(order_count, len(order_list))

        for i in xrange(order_count):
            order = order_list[i]
            self.assertEqual(order.sid, sid)
            self.assertEqual(order.amount, order_amount * alternator**i)

        tracker = PerformanceTracker(sim_params)

        # this approximates the loop inside TradingSimulationClient
        transactions = []
        for dt, trades in itertools.groupby(generated_trades,
                                            operator.attrgetter('dt')):
            for trade in trades:
                trade_sim.update(trade)
                if trade.TRANSACTION:
                    transactions.append(trade.TRANSACTION)

                tracker.process_event(trade)

        if complete_fill:
            self.assertEqual(len(transactions), len(order_list))

        total_volume = 0
        for i in xrange(len(transactions)):
            txn = transactions[i]
            total_volume += txn.amount
            if complete_fill:
                order = order_list[i]
                self.assertEqual(order.amount, txn.amount)

        self.assertEqual(total_volume, expected_txn_volume)
        self.assertEqual(len(transactions), expected_txn_count)

        cumulative_pos = tracker.cumulative_performance.positions[sid]
        self.assertEqual(total_volume, cumulative_pos.amount)

        # the open orders should now be empty
        oo = trade_sim.open_orders
        self.assertTrue(sid in oo)
        order_list = oo[sid]
        self.assertEqual(0, len(order_list))
Exemplo n.º 3
0
    def test_orders_limit(self):

        events = self.gen_trades()

        slippage_model = VolumeShareSlippage()

        # long, does not trade

        open_orders = {133: [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'sid': 133,
                'limit': 3.5})
        ]}

        txn = slippage_model.simulate(
            events[2],
            open_orders
        )

        expected_txn = {}

        self.assertIsNone(txn)

        # long, does trade

        open_orders = {133: [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'sid': 133,
                'limit': 3.5})
        ]}

        txn = slippage_model.simulate(
            events[3],
            open_orders
        )

        expected_txn = {
            'price': float(3.500875),
            'dt': datetime.datetime(
                2006, 1, 5, 14, 34, tzinfo=pytz.utc),
            'amount': int(100),
            'sid': int(133)
        }

        self.assertIsNotNone(txn)

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

        # short, does not trade

        open_orders = {133: [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'sid': 133,
                'limit': 3.5})
        ]}

        txn = slippage_model.simulate(
            events[0],
            open_orders
        )

        expected_txn = {}

        self.assertIsNone(txn)

        # short, does trade

        open_orders = {133: [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'sid': 133,
                'limit': 3.5})
        ]}

        txn = slippage_model.simulate(
            events[1],
            open_orders
        )

        expected_txn = {
            'price': float(3.499125),
            'dt': datetime.datetime(
                2006, 1, 5, 14, 32, tzinfo=pytz.utc),
            'amount': int(-100),
            'sid': int(133)
        }

        self.assertIsNotNone(txn)

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])
Exemplo n.º 4
0
    def test_orders_stop(self):
        events = self.gen_trades()

        slippage_model = VolumeShareSlippage()

        # long, does not trade

        open_orders = [
            Order(
                **{
                    'dt': datetime.datetime(
                        2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                    'amount': 100,
                    'filled': 0,
                    'sid': 133,
                    'stop': 3.5
                })
        ]

        txns = slippage_model.simulate(events[2], open_orders)

        self.assertEquals(len(txns), 0)

        # long, does trade

        open_orders = [
            Order(
                **{
                    'dt': datetime.datetime(
                        2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                    'amount': 100,
                    'filled': 0,
                    'sid': 133,
                    'stop': 3.6
                })
        ]

        txns = slippage_model.simulate(events[3], open_orders)

        self.assertEquals(len(txns), 1)
        txn = txns[0]

        expected_txn = {
            'price': float(3.500875),
            'dt': datetime.datetime(2006, 1, 5, 14, 34, tzinfo=pytz.utc),
            'amount': int(100),
            'sid': int(133),
            'order_id': open_orders[0].id
        }

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

        # short, does not trade

        open_orders = [
            Order(
                **{
                    'dt': datetime.datetime(
                        2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                    'amount': -100,
                    'filled': 0,
                    'sid': 133,
                    'stop': 3.5
                })
        ]

        txns = slippage_model.simulate(events[0], open_orders)

        self.assertEquals(len(txns), 0)

        # short, does trade

        open_orders = [
            Order(
                **{
                    'dt': datetime.datetime(
                        2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                    'amount': -100,
                    'filled': 0,
                    'sid': 133,
                    'stop': 3.4
                })
        ]

        txns = slippage_model.simulate(events[1], open_orders)

        self.assertEquals(len(txns), 1)
        txn = txns[0]

        expected_txn = {
            'price': float(3.499125),
            'dt': datetime.datetime(2006, 1, 5, 14, 32, tzinfo=pytz.utc),
            'amount': int(-100),
            'sid': int(133)
        }

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])