Esempio n. 1
0
 def __init__(self, time_series=None, inputs=None, input_keys=None, desc="Bollinger Bands", length=14, num_std=3):
     super(SMA, self).__init__(time_series=time_series, inputs=inputs, input_keys=input_keys, desc=desc,
                               length=length, num_std=num_std)
     self.length = self.get_int_config("length", 14)
     self.num_std = self.get_int_config("num_std", 3)
     self.__sma = SMA(inputs=inputs, length=self.length)
     self.__std_dev = STD(inputs=inputs, length=self.length)
Esempio n. 2
0
 def __init__(self, input=None, length=14, desc="Average True Range"):
     self.length = int(length)
     self.__prev_close = None
     self.__value = None
     self.__average = SMA(input, self.length)
     super(ATR,
           self).__init__(Indicator.get_name(ATR.__name__, input, length),
                          input, ['high', 'low', 'close'], desc)
Esempio n. 3
0
    def test_name(self):
        bar = self.app_context.inst_data_mgr.get_series("bar")
        sma = SMA(inputs=bar, input_keys='close', length=3)
        self.assertEquals("SMA(bar[close],length=3)", sma.name)

        sma2 = SMA(inputs=sma, input_keys='value', length=10)
        self.assertEquals("SMA(SMA(bar[close],length=3)[value],length=10)",
                          sma2.name)
Esempio n. 4
0
 def __init__(self, time_series=None, inputs=None, input_keys=['high', 'low', 'close'], desc="Average True Range",
              length=14):
     super(ATR, self).__init__(time_series=time_series, inputs=inputs, input_keys=input_keys, desc=desc,
                               length=length)
     self.length = self.get_int_config("length", 14)
     self.__prev_close = None
     self.__value = None
     self.__average = SMA(inputs=inputs, length=self.length)
Esempio n. 5
0
    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)
Esempio n. 6
0
 def __init__(self,
              input=None,
              input_key=None,
              length=14,
              num_std=3,
              desc="Bollinger Bands"):
     self.length = int(length)
     self.num_std = int(num_std)
     self.__sma = SMA(input, self.length)
     self.__std_dev = STD(input, self.length)
     super(BB, self).__init__(
         Indicator.get_name(BB.__name__, input, input_key, length, num_std),
         input, input_key, desc)
Esempio n. 7
0
    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)
Esempio n. 8
0
    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)
Esempio n. 9
0
 def __init__(self, input=None, input_key=None, length=14, num_std=3, desc="Bollinger Bands"):
     self.length = int(length)
     self.num_std = int(num_std)
     self.__sma = SMA(input, self.length)
     self.__std_dev = STD(input, self.length)
     super(BB, self).__init__(Indicator.get_name(BB.__name__, input, input_key, length, num_std), input, input_key,
                              desc)
Esempio n. 10
0
 def __init__(self, input=None, length=14, desc="Average True Range"):
     self.length = int(length)
     self.__prev_close = None
     self.__value = None
     self.__average = SMA(input, self.length)
     super(ATR, self).__init__(Indicator.get_name(ATR.__name__, input, length), input, ['high', 'low', 'close'],
                               desc)
Esempio n. 11
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())
Esempio n. 12
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)
Esempio n. 13
0
class ATR(Indicator):
    __slots__ = (
        'length',
        '__prev_close',
        '__value',
        '__average',
    )

    def __init__(self, input=None, length=14, desc="Average True Range"):
        self.length = int(length)
        self.__prev_close = None
        self.__value = None
        self.__average = SMA(input, self.length)
        super(ATR,
              self).__init__(Indicator.get_name(ATR.__name__, input, length),
                             input, ['high', 'low', 'close'], desc)

    def on_update(self, data):
        sma_input = {}
        sma_input['timestamp'] = data['timestamp']
        high = data['high']
        low = data['low']
        close = data['close']

        if self.__prev_close is None:
            tr = high - low
        else:
            tr1 = high - low
            tr2 = abs(high - self.__prev_close)
            tr3 = abs(low - self.__prev_close)
            tr = max(max(tr1, tr2), tr3)

        self.__prev_close = close

        sma_input[Indicator.VALUE] = tr
        self.__average.add(sma_input)

        result = {}
        result['timestamp'] = data['timestamp']
        result[Indicator.VALUE] = self.__average.now(Indicator.VALUE)
        self.add(result)
Esempio n. 14
0
    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())
Esempio n. 15
0
class ATR(Indicator):
    __slots__ = (
        'length',
        '__prev_close',
        '__value',
        '__average',
    )

    def __init__(self, input=None, length=14, desc="Average True Range"):
        self.length = int(length)
        self.__prev_close = None
        self.__value = None
        self.__average = SMA(input, self.length)
        super(ATR, self).__init__(Indicator.get_name(ATR.__name__, input, length), input, ['high', 'low', 'close'],
                                  desc)

    def on_update(self, data):
        sma_input = {}
        sma_input['timestamp'] = data['timestamp']
        high = data['high']
        low = data['low']
        close = data['close']

        if self.__prev_close is None:
            tr = high - low
        else:
            tr1 = high - low
            tr2 = abs(high - self.__prev_close)
            tr3 = abs(low - self.__prev_close)
            tr = max(max(tr1, tr2), tr3)

        self.__prev_close = close

        sma_input[Indicator.VALUE] = tr
        self.__average.add(sma_input)

        result = {}
        result['timestamp'] = data['timestamp']
        result[Indicator.VALUE] = self.__average.now(Indicator.VALUE)
        self.add(result)
Esempio n. 16
0
class ATR(Indicator):
    __slots__ = (
        'length',
        '__prev_close',
        '__value',
        '__average',
    )

    def __init__(self, time_series=None, inputs=None, input_keys=['high', 'low', 'close'], desc="Average True Range",
                 length=14):
        super(ATR, self).__init__(time_series=time_series, inputs=inputs, input_keys=input_keys, desc=desc,
                                  length=length)
        self.length = self.get_int_config("length", 14)
        self.__prev_close = None
        self.__value = None
        self.__average = SMA(inputs=inputs, length=self.length)

    def _process_update(self, source: str, timestamp: int, data: Dict[str, float]):
        sma_input = {}
        high = data['high']
        low = data['low']
        close = data['close']

        if self.__prev_close is None:
            tr = high - low
        else:
            tr1 = high - low
            tr2 = abs(high - self.__prev_close)
            tr3 = abs(low - self.__prev_close)
            tr = max(max(tr1, tr2), tr3)

        self.__prev_close = close

        sma_input[Indicator.VALUE] = tr
        self.__average.add(timestamp=timestamp, data=sma_input)

        result = {}
        # result['timestamp'] = data['timestamp']
        result[Indicator.VALUE] = self.__average.now(Indicator.VALUE)
        self.add(timestamp=timestamp, data=result)
Esempio n. 17
0
    def test_indicator(self, name, datastore):
        self.app_context = ApplicationContext()

        bar = self.app_context.inst_data_mgr.get_series("bar")
        sma = SMA(bar.name, 'close', 1, missing_value=0)
        t1 = datetime.now()
        t2 = t1 + timedelta(0, 3)
        t3 = t2 + 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})

        DataStoreTest.save_load(name, sma, datastore,
                                datastore.save_time_series, 'time_series')
Esempio n. 18
0
class BB(Indicator):
    UPPER = 'uppper'
    LOWER = 'lower'

    __slots__ = (
        'length',
        'num_std'
        '__sma',
        '__std_dev',
    )

    def __init__(self,
                 input=None,
                 input_key=None,
                 length=14,
                 num_std=3,
                 desc="Bollinger Bands"):
        self.length = int(length)
        self.num_std = int(num_std)
        self.__sma = SMA(input, self.length)
        self.__std_dev = STD(input, self.length)
        super(BB, self).__init__(
            Indicator.get_name(BB.__name__, input, input_key, length, num_std),
            input, input_key, desc)

    def on_update(self, data):
        result = {}
        result['timestamp'] = data['timestamp']
        sma = self.__sma.now(self.input_keys[0])
        std = self.__std_dev.now(self.input_keys[0])
        if not np.isnan(sma):
            upper = sma + std * self.num_std
            lower = sma - std * self.num_std

            result[BB.UPPER] = upper
            result[BB.LOWER] = lower
            result[Indicator.VALUE] = sma
        else:
            result[BB.UPPER] = np.nan
            result[BB.LOWER] = np.nan
            result[Indicator.VALUE] = np.nan

        self.add(result)
Esempio n. 19
0
class BB(Indicator):
    UPPER = 'uppper'
    LOWER = 'lower'

    __slots__ = (
        'length',
        'num_std'
        '__sma',
        '__std_dev',
    )

    def __init__(self, input=None, input_key=None, length=14, num_std=3, desc="Bollinger Bands"):
        self.length = int(length)
        self.num_std = int(num_std)
        self.__sma = SMA(input, self.length)
        self.__std_dev = STD(input, self.length)
        super(BB, self).__init__(Indicator.get_name(BB.__name__, input, input_key, length, num_std), input, input_key,
                                 desc)

    def on_update(self, data):
        result = {}
        result['timestamp'] = data['timestamp']
        sma = self.__sma.now(self.input_keys[0])
        std = self.__std_dev.now(self.input_keys[0])
        if not np.isnan(sma):
            upper = sma + std * self.num_std
            lower = sma - std * self.num_std

            result[BB.UPPER] = upper
            result[BB.LOWER] = lower
            result[Indicator.VALUE] = sma
        else:
            result[BB.UPPER] = np.nan
            result[BB.LOWER] = np.nan
            result[Indicator.VALUE] = np.nan

        self.add(result)
Esempio n. 20
0
class BB(Indicator):
    UPPER = 'uppper'
    LOWER = 'lower'

    __slots__ = (
        'length',
        'num_std'
        '__sma',
        '__std_dev',
    )

    def __init__(self, time_series=None, inputs=None, input_keys=None, desc="Bollinger Bands", length=14, num_std=3):
        super(SMA, self).__init__(time_series=time_series, inputs=inputs, input_keys=input_keys, desc=desc,
                                  length=length, num_std=num_std)
        self.length = self.get_int_config("length", 14)
        self.num_std = self.get_int_config("num_std", 3)
        self.__sma = SMA(inputs=inputs, length=self.length)
        self.__std_dev = STD(inputs=inputs, length=self.length)

    def _process_update(self, source: str, timestamp: int, data: Dict[str, float]):
        result = {}
        sma = self.__sma.now(self.input_keys[0])
        std = self.__std_dev.now(self.input_keys[0])
        if not np.isnan(sma):
            upper = sma + std * self.num_std
            lower = sma - std * self.num_std

            result[BB.UPPER] = upper
            result[BB.LOWER] = lower
            result[Indicator.VALUE] = sma
        else:
            result[BB.UPPER] = np.nan
            result[BB.LOWER] = np.nan
            result[Indicator.VALUE] = np.nan

        self.add(timestamp=timestamp, data=result)
Esempio n. 21
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()
Esempio n. 22
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
Esempio n. 23
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
    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()
Esempio n. 25
0
 def test_empty_at_initialize(self):
     close = self.app_context.inst_data_mgr.get_series("bar")
     sma = SMA(close, 'close', 3)
     self.assertEquals(0, len(sma.get_data()))
Esempio n. 26
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
Esempio n. 27
0
    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'))
Esempio n. 28
0
    def test_get_full_cls_name(self):
        from algotrader.technical.ma import SMA
        ma = SMA(inputs="null")
        self.assertEqual("algotrader.technical.ma.SMA", get_full_cls_name(ma))

        self.assertEqual("algotrader.technical.ma.SMA", get_full_cls_name(SMA))
Esempio n. 29
0
 def test_empty_at_initialize(self):
     close = self.app_context.inst_data_mgr.get_series("bar")
     sma = SMA(inputs=close, input_keys='close', length=3)
     self.assertEquals(0, len(sma.get_data()))
Esempio n. 30
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'))