コード例 #1
0
ファイル: test_ma.py プロジェクト: alexcwyu/python-trading
    def test_nan_before_size(self):
        bar = self.app_context.inst_data_mgr.get_series("bar")
        bar.start(self.app_context)

        sma = SMA(bar, 'close', 3)
        sma.start(self.app_context)

        t1 = datetime.datetime.now()
        t2 = t1 + datetime.timedelta(0, 3)
        t3 = t2 + datetime.timedelta(0, 3)

        bar.add({"timestamp": t1, "close": 2.0, "open": 0})
        self.assertEquals([{"name": "'SMA('bar',close,3)'",
                            "timestamp": t1, 'value': np.nan}],
                          sma.get_data())

        bar.add({"timestamp": t2, "close": 2.4, "open": 1.4})
        self.assertEquals([{"name": "'SMA('bar',close,3)'", "timestamp": t1, 'value': np.nan},
                           {"name": "'SMA('bar',close,3)'", "timestamp": t2, 'value': np.nan}],
                          sma.get_data())

        bar.add({"timestamp": t3, "close": 2.8, "open": 1.8})
        self.assertEquals([{"name": "'SMA('bar',close,3)'", "timestamp": t1, 'value': np.nan},
                           {"name": "'SMA('bar',close,3)'", "timestamp": t2, 'value': np.nan},
                           {"name": "'SMA('bar',close,3)'", "timestamp": t3, 'value': 2.4}],
                          sma.get_data())
コード例 #2
0
class SMAStrategy(Strategy):
    def __init__(self, stg_id: str, stg_cls: str, state: StrategyState = None):
        super(SMAStrategy, self).__init__(stg_id=stg_id, stg_cls=stg_cls, state=state)
        self.buy_order = None

    def _start(self, app_context: Context) -> None:
        self.instruments = app_context.config.get_app_config("instrumentIds")
        self.qty = self._get_stg_config("qty", default=1)
        self.bar = self.app_context.inst_data_mgr.get_series(
            "Bar.%s.Time.86400" % self.instruments[0])

        self.sma_fast = SMA(self.bar, 'close', 10)
        self.sma_fast.start(app_context)

        self.sma_slow = SMA(self.bar, 'close', 25)
        self.sma_slow.start(app_context)

        super(SMAStrategy, self)._start(app_context)

    def _stop(self):
        super(SMAStrategy, self)._stop()

    def on_bar(self, bar):
        if self.buy_order is None and self.sma_fast.now('value') > self.sma_slow.now('value'):
            self.buy_order = self.market_order(inst_id=bar.inst_id, action=Buy, qty=self.qty)
            logger.info("%s,B,%s,%s,%.2f,%.2f,%.2f" % (
                bar.timestamp, self.buy_order.cl_id, self.buy_order.cl_ord_id, bar.close, self.sma_fast.now('value'),
                self.sma_slow.now('value')))
        elif self.buy_order is not None and self.sma_fast.now('value') < self.sma_slow.now('value'):
            sell_order = self.market_order(inst_id=bar.inst_id, action=Sell, qty=self.qty)
            logger.info("%s,S,%s,%s,%.2f,%.2f,%.2f" % (
                bar.timestamp, sell_order.cl_id, sell_order.cl_ord_id, bar.close, self.sma_fast.now('value'),
                self.sma_slow.now('value')))
            self.buy_order = None
コード例 #3
0
    def test_nan_before_size(self):
        bar = self.app_context.inst_data_mgr.get_series("bar")
        bar.start(self.app_context)

        sma = SMA(inputs=bar, input_keys='close', length=3)
        sma.start(self.app_context)

        t1 = 1
        t2 = t1 + 3
        t3 = t2 + 3

        bar.add(timestamp=t1, data={"close": 2.0, "open": 0})
        self.assertEquals([{'value': np.nan}], sma.get_data())

        bar.add(timestamp=t2, data={"close": 2.4, "open": 1.4})
        self.assertEquals([{
            'value': np.nan
        }, {
            'value': np.nan
        }], sma.get_data())

        bar.add(timestamp=t3, data={"close": 2.8, "open": 1.8})
        self.assertEquals([{
            'value': np.nan
        }, {
            'value': np.nan
        }, {
            'value': 2.4
        }], sma.get_data())
コード例 #4
0
class SMAStrategy(Strategy):
    def __init__(self, stg_id=None, stg_configs=None):
        super(SMAStrategy, self).__init__(stg_id=stg_id, stg_configs=stg_configs)
        self.buy_order = None

    def _start(self, app_context, **kwargs):
        self.qty = self.get_stg_config_value("qty", 1)
        self.bar = app_context.inst_data_mgr.get_series("Bar.%s.Time.86400" % self.app_context.app_config.instrument_ids[0])

        self.sma_fast = SMA(self.bar, 'close', 10)
        self.sma_fast.start(app_context)

        self.sma_slow = SMA(self.bar, 'close', 25)
        self.sma_slow.start(app_context)

        super(SMAStrategy, self)._start(app_context, **kwargs)

    def _stop(self):
        super(SMAStrategy, self)._stop()

    def on_bar(self, bar):
        if self.buy_order is None and self.sma_fast.now('value') > self.sma_slow.now('value'):
            self.buy_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty)
            logger.info("%s,B,%s,%s,%.2f,%.2f,%.2f" % (
                bar.timestamp, self.buy_order.cl_id, self.buy_order.cl_ord_id, bar.close, self.sma_fast.now('value'),
                self.sma_slow.now('value')))
        elif self.buy_order is not None and self.sma_fast.now('value') < self.sma_slow.now('value'):
            sell_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.SELL, qty=self.qty)
            logger.info("%s,S,%s,%s,%.2f,%.2f,%.2f" % (
                bar.timestamp, sell_order.cl_id, sell_order.cl_ord_id, bar.close, self.sma_fast.now('value'),
                self.sma_slow.now('value')))
            self.buy_order = None
コード例 #5
0
    def test_indicator(self, name, serializer):
        self.app_context = ApplicationContext()

        bar = self.app_context.inst_data_mgr.get_series("bar")
        sma = SMA(bar.name, 'close', 1, missing_value=0)
        bar.start(self.app_context)
        sma.start(self.app_context)

        t1 = datetime.datetime.now()
        t2 = t1 + datetime.timedelta(0, 3)
        t3 = t2 + datetime.timedelta(0, 3)

        bar.add({"timestamp": t1, "close": 2.0, "open": 0})
        bar.add({"timestamp": t2, "close": 2.4, "open": 1.4})

        bar.add({"timestamp": t3, "close": 2.8, "open": 1.8})

        SerializerTest.ser_deser(name, serializer, sma)
コード例 #6
0
ファイル: sma_strategy.py プロジェクト: vjaeng/python-trading
class SMAStrategy(Strategy):
    def __init__(self, stg_id=None, stg_configs=None):
        super(SMAStrategy, self).__init__(stg_id=stg_id,
                                          stg_configs=stg_configs)
        self.buy_order = None

    def _start(self, app_context, **kwargs):
        self.qty = self.get_stg_config_value("qty", 1)
        self.bar = app_context.inst_data_mgr.get_series(
            "Bar.%s.Time.86400" %
            self.app_context.app_config.instrument_ids[0])

        self.sma_fast = SMA(self.bar, 'close', 10)
        self.sma_fast.start(app_context)

        self.sma_slow = SMA(self.bar, 'close', 25)
        self.sma_slow.start(app_context)

        super(SMAStrategy, self)._start(app_context, **kwargs)

    def _stop(self):
        super(SMAStrategy, self)._stop()

    def on_bar(self, bar):
        if self.buy_order is None and self.sma_fast.now(
                'value') > self.sma_slow.now('value'):
            self.buy_order = self.market_order(inst_id=bar.inst_id,
                                               action=OrdAction.BUY,
                                               qty=self.qty)
            logger.info(
                "%s,B,%s,%s,%.2f,%.2f,%.2f" %
                (bar.timestamp, self.buy_order.cl_id, self.buy_order.cl_ord_id,
                 bar.close, self.sma_fast.now('value'),
                 self.sma_slow.now('value')))
        elif self.buy_order is not None and self.sma_fast.now(
                'value') < self.sma_slow.now('value'):
            sell_order = self.market_order(inst_id=bar.inst_id,
                                           action=OrdAction.SELL,
                                           qty=self.qty)
            logger.info("%s,S,%s,%s,%.2f,%.2f,%.2f" %
                        (bar.timestamp, sell_order.cl_id, sell_order.cl_ord_id,
                         bar.close, self.sma_fast.now('value'),
                         self.sma_slow.now('value')))
            self.buy_order = None
コード例 #7
0
    def test_moving_average_calculation(self):
        bar = self.app_context.inst_data_mgr.get_series("bar")
        bar.start(self.app_context)

        sma = SMA(inputs=bar, input_keys='close', length=3)
        sma.start(self.app_context)

        t1 = 1
        t2 = t1 + 3
        t3 = t2 + 3
        t4 = t3 + 3
        t5 = t4 + 3

        bar.add(data={"timestamp": t1, "close": 2.0, "open": 0})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add(data={"timestamp": t2, "close": 2.4, "open": 1.4})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add(data={"timestamp": t3, "close": 2.8, "open": 1.8})
        self.assertEquals(2.4, sma.now('value'))

        bar.add(data={"timestamp": t4, "close": 3.2, "open": 2.2})
        self.assertEquals(2.8, sma.now('value'))

        bar.add(data={"timestamp": t5, "close": 3.6, "open": 2.6})
        self.assertEquals(3.2, sma.now('value'))

        self.assertTrue(math.isnan(sma.get_by_idx(0, 'value')))
        self.assertTrue(math.isnan(sma.get_by_idx(1, 'value')))
        self.assertEquals(2.4, sma.get_by_idx(2, 'value'))
        self.assertEquals(2.8, sma.get_by_idx(3, 'value'))
        self.assertEquals(3.2, sma.get_by_idx(4, 'value'))

        self.assertTrue(math.isnan(sma.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma.get_by_time(t2, 'value')))
        self.assertEquals(2.4, sma.get_by_time(t3, 'value'))
        self.assertEquals(2.8, sma.get_by_time(t4, 'value'))
        self.assertEquals(3.2, sma.get_by_time(t5, 'value'))
コード例 #8
0
ファイル: test_ma.py プロジェクト: alexcwyu/python-trading
    def test_moving_average_calculation(self):
        bar = self.app_context.inst_data_mgr.get_series("bar")
        bar.start(self.app_context)

        sma = SMA(bar, input_key='close', length=3)
        sma.start(self.app_context)

        t1 = datetime.datetime.now()
        t2 = t1 + datetime.timedelta(0, 3)
        t3 = t2 + datetime.timedelta(0, 3)
        t4 = t3 + datetime.timedelta(0, 3)
        t5 = t4 + datetime.timedelta(0, 3)

        bar.add({"timestamp": t1, "close": 2.0, "open": 0})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add({"timestamp": t2, "close": 2.4, "open": 1.4})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add({"timestamp": t3, "close": 2.8, "open": 1.8})
        self.assertEquals(2.4, sma.now('value'))

        bar.add({"timestamp": t4, "close": 3.2, "open": 2.2})
        self.assertEquals(2.8, sma.now('value'))

        bar.add({"timestamp": t5, "close": 3.6, "open": 2.6})
        self.assertEquals(3.2, sma.now('value'))

        self.assertTrue(math.isnan(sma.get_by_idx(0, 'value')))
        self.assertTrue(math.isnan(sma.get_by_idx(1, 'value')))
        self.assertEquals(2.4, sma.get_by_idx(2, 'value'))
        self.assertEquals(2.8, sma.get_by_idx(3, 'value'))
        self.assertEquals(3.2, sma.get_by_idx(4, 'value'))

        self.assertTrue(math.isnan(sma.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma.get_by_time(t2, 'value')))
        self.assertEquals(2.4, sma.get_by_time(t3, 'value'))
        self.assertEquals(2.8, sma.get_by_time(t4, 'value'))
        self.assertEquals(3.2, sma.get_by_time(t5, 'value'))
コード例 #9
0
    def test_save_and_load_indicator(self):
        app_context = self.create_app_context(
            conf={
                "Application": {
                    "createDBAtStart": True,
                    "deleteDBAtStop": False,
                    "persistenceMode": "RealTime"
                }
            })
        app_context.start()

        bar = app_context.inst_data_mgr.get_series("bar")
        bar.start(app_context)

        sma = SMA(inputs=bar, input_keys='close', length=3)
        sma.start(app_context)

        t1 = 0
        t2 = t1 + 1
        t3 = t2 + 1
        t4 = t3 + 1
        t5 = t4 + 1

        bar.add(timestamp=t1, data={"close": 2.0, "open": 0})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add(timestamp=t2, data={"close": 2.4, "open": 1.4})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add(timestamp=t3, data={"close": 2.8, "open": 1.8})
        self.assertEquals(2.4, sma.now('value'))

        app_context.stop()

        ## restart...:

        app_context = self.create_app_context(
            conf={
                "Application": {
                    "createDBAtStart": False,
                    "deleteDBAtStop": True,
                    "persistenceMode": "RealTime"
                }
            })
        app_context.start()

        bar_new = app_context.inst_data_mgr.get_series("bar")
        bar_new.start(app_context)

        sma_new = app_context.inst_data_mgr.get_series(sma.id())
        sma_new.start(app_context)

        bar_new.add(timestamp=t4, data={"close": 3.2, "open": 2.2})
        self.assertEquals(2.8, sma_new.now('value'))

        bar_new.add(timestamp=t5, data={"close": 3.6, "open": 2.6})
        self.assertEquals(3.2, sma_new.now('value'))

        self.assertTrue(math.isnan(sma_new.get_by_idx(0, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_idx(1, 'value')))
        self.assertEquals(2.4, sma_new.get_by_idx(2, 'value'))
        self.assertEquals(2.8, sma_new.get_by_idx(3, 'value'))
        self.assertEquals(3.2, sma_new.get_by_idx(4, 'value'))

        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_time(t2, 'value')))
        self.assertEquals(2.4, sma_new.get_by_time(t3, 'value'))
        self.assertEquals(2.8, sma_new.get_by_time(t4, 'value'))

        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))

        old_bar_dict = bar.get_data_dict(['close'])
        old_sma_dict = sma.get_data_dict(['value'])

        new_bar_dict = bar_new.get_data_dict(['close'])
        new_sma_dict = sma_new.get_data_dict(['value'])

        self.assertEquals(3, len(old_bar_dict))
        self.assertEquals(3, len(old_sma_dict))

        self.assertEquals(5, len(new_bar_dict))
        self.assertEquals(5, len(new_sma_dict))

        self.assertEquals(2.0, new_bar_dict[t1])
        self.assertTrue(math.isnan(new_sma_dict[t1]))

        self.assertEquals(2.4, new_bar_dict[t2])
        self.assertTrue(math.isnan(new_sma_dict[t2]))

        self.assertEquals(2.8, new_bar_dict[t3])
        self.assertEquals(2.4, new_sma_dict[t3])

        self.assertEquals(3.2, new_bar_dict[t4])
        self.assertEquals(2.8, new_sma_dict[t4])

        self.assertEquals(3.6, new_bar_dict[t5])
        self.assertEquals(3.2, new_sma_dict[t5])

        db = app_context.get_data_store()
        app_context.stop()
        db.remove_database()
コード例 #10
0
    def test_save_and_load_indicator(self):
        app_context = self.new_app_context()

        bar = app_context.inst_data_mgr.get_series("bar")
        bar.start(app_context)

        sma = SMA(bar, input_key='close', length=3)
        sma.start(app_context)

        t1 = 0
        t2 = t1 + 1
        t3 = t2 + 1
        t4 = t3 + 1
        t5 = t4 + 1

        bar.add({"timestamp": t1, "close": 2.0, "open": 0})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add({"timestamp": t2, "close": 2.4, "open": 1.4})
        self.assertTrue(math.isnan(sma.now('value')))

        bar.add({"timestamp": t3, "close": 2.8, "open": 1.8})
        self.assertEquals(2.4, sma.now('value'))

        app_context.stop()

        ## restart...:

        app_context = self.new_app_context()

        bar_new = app_context.inst_data_mgr.get_series("bar")
        bar_new.start(app_context)

        sma_new = app_context.inst_data_mgr.get_series(sma.id())
        sma_new.start(app_context)

        bar_new.add({"timestamp": t4, "close": 3.2, "open": 2.2})
        self.assertEquals(2.8, sma_new.now('value'))

        bar_new.add({"timestamp": t5, "close": 3.6, "open": 2.6})
        self.assertEquals(3.2, sma_new.now('value'))

        self.assertTrue(math.isnan(sma_new.get_by_idx(0, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_idx(1, 'value')))
        self.assertEquals(2.4, sma_new.get_by_idx(2, 'value'))
        self.assertEquals(2.8, sma_new.get_by_idx(3, 'value'))
        self.assertEquals(3.2, sma_new.get_by_idx(4, 'value'))

        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_time(t2, 'value')))
        self.assertEquals(2.4, sma_new.get_by_time(t3, 'value'))
        self.assertEquals(2.8, sma_new.get_by_time(t4, 'value'))

        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))
        self.assertTrue(math.isnan(sma_new.get_by_time(t1, 'value')))

        old_bar_dict = bar.get_data_dict(['close'])
        old_sma_dict = sma.get_data_dict(['value'])

        new_bar_dict = bar_new.get_data_dict(['close'])
        new_sma_dict = sma_new.get_data_dict(['value'])

        self.assertEquals(3, len(old_bar_dict))
        self.assertEquals(3, len(old_sma_dict))

        self.assertEquals(5, len(new_bar_dict))
        self.assertEquals(5, len(new_sma_dict))

        self.assertEquals(2.0, new_bar_dict['0'])
        self.assertTrue(math.isnan(new_sma_dict['0']))

        self.assertEquals(2.4, new_bar_dict['1'])
        self.assertTrue(math.isnan(new_sma_dict['1']))

        self.assertEquals(2.8, new_bar_dict['2'])
        self.assertEquals(2.4, new_sma_dict['2'])

        self.assertEquals(3.2, new_bar_dict['3'])
        self.assertEquals(2.8, new_sma_dict['3'])

        self.assertEquals(3.6, new_bar_dict['4'])
        self.assertEquals(3.2, new_sma_dict['4'])

        db = app_context.get_ref_data_store()
        app_context.stop()
        db.remove_database()