Beispiel #1
0
 def generate_signals(self):
     stoch_k, stoch_d = self.get_indicators()
     if self.mode == 1:
         # calculate signal for smooth stochastic
         d_signal = np.zeros(stoch_d.shape, dtype='int')
         d_mask_buy = (stoch_d > self.upper_threshold)
         d_signal[d_mask_buy] = 1
         d_mask_sell = (self.lower_threshold > stoch_d)
         d_signal[d_mask_sell] = -1
         self.signal = BaseIndicator.set_signal_osc(d_signal)
     elif self.mode == 2:
         # calculate signal for %k stochastic
         k_signal = np.zeros(stoch_k.shape, dtype='int')
         k_mask_buy = (stoch_k > self.upper_threshold)
         k_signal[k_mask_buy] = 1
         k_mask_sell = (self.lower_threshold > stoch_k)
         k_signal[k_mask_sell] = -1
         self.signal = BaseIndicator.set_signal_osc(k_signal)
     elif self.mode == 3:
         kd_signal = np.zeros(stoch_d.shape, dtype='int')
         kd_mask_buy = (stoch_d > self.upper_threshold) & (
             stoch_k > self.upper_threshold)
         kd_signal[kd_mask_buy] = 1
         kd_mask_sell = (self.lower_threshold >
                         stoch_d) & (self.lower_threshold > stoch_k)
         kd_signal[kd_mask_sell] = -1
         self.signal = BaseIndicator.set_signal_osc(kd_signal)
     self.signal_shift = abs(len(self.times) - len(stoch_d))
     if self.plot_result:
         self.plot([self.times, self.close, stoch_k, stoch_d])
     return self.signal
Beispiel #2
0
 def generate_signals(self):
     kvo, kvo_signal = self.get_indicators()
     self.signal = np.zeros(kvo.shape, dtype='int')
     mask_buy = (kvo_signal > kvo)
     self.signal[mask_buy] = 1
     mask_sell = (kvo > kvo_signal)
     self.signal[mask_sell] = -1
     self.signal = BaseIndicator.set_signal_osc(self.signal)
     self.signal_shift = 1
     if self.plot_result:
         self.plot([self.times, self.close, kvo, kvo_signal])
     return self.signal
Beispiel #3
0
 def generate_signals(self):
     """Returns the DataFrame of symbols containing the indicators
     to go long, short or hold (1, -1 or 0)."""
     short_ema, long_ema = self.get_indicators()
     # Create a 'signal' (invested or not invested) when the short ema crosses the
     # long ema, but only for the period greater than the shortest moving average
     # window
     self.signal = np.zeros(long_ema.shape, dtype='int')
     signal_indices = np.where(short_ema > long_ema)
     self.signal[signal_indices] = 1
     self.signal = BaseIndicator.set_signal(self.signal)
     if self.plot_result:
         self.plot([self.times, self.close, self.open, short_ema, long_ema])
     return self.signal
 def generate_signals(self):
     """Returns the DataFrame of symbols containing the indicators
     to go long, short or hold (1, -1 or 0)."""
     long_period = int(self.strategy_value['long_period'])
     macd, macd_signal, macd_histogram = self.get_indicators()
     self.signal = np.zeros(macd_histogram.shape, dtype='int')
     signal_indices_buy = np.where(macd_histogram > 0)
     self.signal[signal_indices_buy] = 1
     self.signal = BaseIndicator.set_signal(self.signal)
     self.signal_shift = long_period - 1
     if self.plot_result:
         self.plot(
             [self.times, self.open, macd_histogram, macd, macd_signal])
     return self.signal
 def generate_signals(self):
     ultimate, ma_short, ma_long = self.get_indicators()
     self.signal = np.zeros(ultimate.shape, dtype='int')
     # find gabs between two overbought areas in uc signal
     uc_signal = np.zeros(ultimate.shape, dtype='int')
     uc_mask = (ultimate > 25) & (ultimate < 75)
     uc_signal[uc_mask] = 1
     signal_indices = np.where(ma_short > ma_long)
     self.signal[signal_indices] = 1
     mask = (self.signal == 1) & (uc_signal == 1)
     self.signal[self.signal == 1] = 0
     self.signal[mask] = 1
     self.signal[signal_indices] = 1
     self.signal = BaseIndicator.set_signal(self.signal)
     if self.plot_result:
         self.plot([self.times, self.open, ma_long, ma_short, ultimate])
     return self.signal
Beispiel #6
0
    def generate_signals(self):
        """Returns the DataFrame of symbols containing the indicators
        to go long, short or hold (1, -1 or 0)."""
        aroon_down, aroon_up = self.get_indicators()

        # Create a 'signal' (invested or not invested) when the short ema crosses the
        # long ema, but only for the period greater than the shortest moving average
        # window
        self.signal = np.zeros(aroon_down.shape, dtype='int')
        signal_indices = np.where(aroon_up > aroon_down)
        self.signal[signal_indices] = 1
        self.signal = BaseIndicator.set_signal(self.signal)
        self.signal_shift = int(self.strategy_value['period'])
        if self.plot_result:
            self.plot(
                [self.times, self.close, self.open, aroon_down, aroon_up])
        return self.signal
Beispiel #7
0
 def generate_signals(self):
     """Returns the DataFrame of symbols containing the indicators
     to go long, short or hold (1, -1 or 0)."""
     long_window = int(self.strategy_value['long_window'])
     short_window = int(self.strategy_value['short_window'])
     short_mavg, long_mavg = self.get_indicators()
     # Create a 'signal' (invested or not invested) when the short moving average crosses the
     # long moving average, but only for the period greater than the shortest moving average
     # window
     self.signal = np.zeros(long_mavg.shape, dtype='int')
     offset = long_window - short_window
     signal_indices = np.where(short_mavg[offset:] > long_mavg)
     self.signal[signal_indices] = 1
     self.signal = BaseIndicator.set_signal(self.signal)
     self.signal_shift = long_window - 1
     if self.plot_result:
         self.plot(
             [self.times, self.close, self.open, short_mavg, long_mavg])
     return self.signal
    def generate_signals(self):
        long_window = int(self.strategy_value['long_window'])
        ultimate, ema = self.get_indicators()
        self.signal = np.zeros(ultimate.shape, dtype='int')
        # find gabs between two overbought areas in uc signal
        uc_signal = np.zeros(ultimate.shape, dtype='int')
        uc_mask = (ultimate > 25) & (ultimate < 75)
        uc_signal[uc_mask] = 1
        # set signals if ema > close and uc in gab
        self.signal_shift = long_window

        signal_indices = np.where(ema[self.signal_shift:] > self.open[self.signal_shift:])
        self.signal[signal_indices] = 1
        mask = (self.signal == 1) & (uc_signal == 1)
        self.signal[self.signal == 1] = 0
        self.signal[mask] = 1
        self.signal[signal_indices] = 1
        self.signal = BaseIndicator.set_signal(self.signal)
        if self.plot_result:
            self.plot([self.times, self.open, ema, ultimate])
        return self.signal
    def generate_signals(self):
        """Returns the DataFrame of symbols containing the indicators
        to go long, short or hold (1, -1 or 0)."""
        long_window = int(self.strategy_value['long_window'])
        medium_window = int(self.strategy_value['medium_window'])
        short_window = int(self.strategy_value['short_window'])
        short_mavg, medium_mavg, long = self.get_indicators()

        self.signal = np.zeros(long.shape, dtype='int')
        offset_s = long_window - short_window
        offset_m = long_window - medium_window
        short = short_mavg[offset_s:]
        medium = medium_mavg[offset_m:]
        signal_long_indices = np.where((short > medium) & (short > long)
                                       & (medium > long))
        signal_short_indices = np.where(medium > short)
        self.signal[signal_long_indices] = 1
        self.signal[signal_short_indices] = 0
        self.signal = BaseIndicator.set_signal(self.signal)
        self.signal_shift = long_window - 1
        if self.plot_result:
            self.plot([self.times, self.close, self.open, medium, short, long])
        return self.signal
Beispiel #10
0
class TestBase(unittest.TestCase):
    """
    Base class for indicator unit tests
    """

    TEST_LOGGER = logging.getLogger()
    TEST_LOGGER.setLevel(logging.WARNING)

    test_strategy = BaseIndicator(None, None)
    test_params = None
    test_stocks = ["LHA", "MRK"]
    test_excepted_results = None

    @staticmethod
    def check_consistency():
        """
        Checks if results are stable. The method must produce same values after n runs.
        """
        config = TraderBase.get_config()
        db_tool = Db(config['sql'], TestBase.TEST_LOGGER)
        db_tool.connect()
        stock = db_tool.session.query(Stock).filter(
            Stock.symbol == TestBase.test_stocks[1]).first()
        status_list = []
        profits_list = []
        for _ in range(100):
            profit, status = TestBase.calculate_profit(stock,
                                                       TestBase.test_strategy,
                                                       TestBase.test_params)
            status_list.append(status)
            profits_list.append(profit)
        # check if profit elements are equal and status elements are equal
        assert status_list.count(status_list[0]) == len(status_list)
        assert profits_list.count(profits_list[0]) == len(profits_list)
        db_tool.session.close()

    @staticmethod
    def compare_excepted_with_results():
        """
        Tests two stocks with freezed data set
        """
        config = TraderBase.get_config()
        db_tool = Db(config['sql'], TestBase.TEST_LOGGER)
        db_tool.connect()
        symbols = TestBase.test_stocks
        excepted_results = TestBase.test_excepted_results
        results = []
        # collect results
        for symbol in symbols:
            stock = db_tool.session.query(Stock).filter(
                symbol == Stock.symbol).first()
            for param in TestBase.test_params:
                results.append(TestBase.calculate_profit(stock, None, param))

        # compare calculated results with excepted results
        for idx, result in enumerate(results):
            TestBase.TEST_LOGGER.info("Profit is %s and status %s", result[0],
                                      result[1])
            assert result[1] == excepted_results[idx][
                1], "Test%s: %s != %s" % (idx, result[1],
                                          excepted_results[idx][1])
        db_tool.session.close()

    @staticmethod
    def calculate_profit(stock, strategy, params):
        """
        Calculate profit and status for ema strategy
        :param stock: stock db object
        :param strategy: initialized strategy object
        :param params: params for strategy
        :return:
        """
        arguments = {
            'symbol': stock.symbol,
            'bars': None,
            'parameters': params,
            'optimizable': False,
            'name': TestBase.test_strategy.NAME,
            'plot_result': False
        }

        strategy = TestBase.test_strategy(arguments, TestBase.TEST_LOGGER)

        strategy.set_bars(
            stock.get_bars(start=datetime.datetime(2016, 6, 1, 0, 0),
                           end=datetime.datetime(2017, 9, 1, 0, 0),
                           output_type=BARS_NUMPY))

        profit, status = Optimizer(TestBase.TEST_LOGGER).calc_profit(
            strategy, None, params)
        return profit, status