Ejemplo n.º 1
0
 def test_gen_signal():
     """
     Tests two stocks with freezed data set
     """
     config = TraderBase.get_config()
     db_tool = Db(config['sql'], TEST_LOGGER)
     db_tool.connect()
     symbols = [["LHA", 0.6, 2], ["MRK", 0.4, 0]]
     for symbol in symbols:
         stock = db_tool.session.query(Stock).filter(
             symbol[0] == Stock.symbol).first()
         arguments = {
             'stock': stock,
             'name': 'StockIsHot2Month',
             'bars': None,
             'threshold_buy': 0.8,
             'threshold_sell': 0.5,
             'intervals': [7, 30],
             'secure_value': 0.84,
             'lookback': 2
         }
         my_filter = Sih(arguments, TEST_LOGGER)
         bars = stock.get_bars(my_filter.look_back_date(),
                               output_type=BARS_NUMPY)
         my_filter.set_bars(bars)
         status = my_filter.analyse()
         TEST_LOGGER.info("%s score is: %s and status %s", symbol[0],
                          my_filter.get_calculation(), status)
         npt.assert_almost_equal(my_filter.get_calculation(),
                                 symbol[1],
                                 decimal=4)
         assert symbol[2] == status
         db_tool.session.close()
Ejemplo n.º 2
0
 def test_gen_signal():
     """
     Tests two stocks with freezed data set
     """
     config = TraderBase.get_config()
     db_tool = Db(config['sql'], TEST_LOGGER)
     db_tool.connect()
     symbols = [["LHA", 5, 0], ["MRK", -6, 0]]
     for symbol in symbols:
         stock = db_tool.session.query(Stock).filter(
             symbol[0] == Stock.symbol).first()
         arguments = {
             'stock': stock,
             'name': Pr.NAME,
             'bars': stock.get_bars(output_type=BARS_NUMPY),
             'threshold_buy': 10,
             'threshold_sell': 5,
             'intervals': None,
             'lookback': 2
         }
         my_filter = Pr(arguments, TEST_LOGGER)
         status = my_filter.analyse()
         TEST_LOGGER.info("%s score is: %s and status %s", symbol[0],
                          my_filter.get_calculation(), status)
         assert symbol[1] == my_filter.get_calculation()
         assert symbol[2] == status
         db_tool.session.close()
Ejemplo n.º 3
0
    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()
Ejemplo n.º 4
0
 def test2_signal_quick(self):
     """
     Tests the update precess
     """
     self.test1_signal_full()
     my_signals = self.db_tool.session.query(Signal).all()
     len_signals_after = len(my_signals)
     len_stocks = len(self.db_tool.session.query(Stock).all())
     assert len_signals_after == len_stocks
     arguments = {
         'signals': AroonSignal.SHORT_NAME,
         'stocks': ["ALL"],
         'look_back': 300,
         'offline': True,
         'db_tool': self.db_tool
     }
     exit_code = BuildIndicatorsBackTest(self.config, arguments, self.test_logger).build()
     assert exit_code == 0
     self.db_tool.session = None
     self.db_tool = Db(self.config['sql'], self.test_logger)
     self.db_tool.connect()
     my_signals = self.db_tool.session.query(Signal).all()
     len_signals_after = len(my_signals)
     assert len_signals_after == len_stocks
     len_plot_after = len(self.db_tool.session.query(Plot).all())
     len_parameter_after = len(self.db_tool.session.query(Parameter).all())
     assert len_parameter_after == len_plot_after == len_signals_after
     for my_signal in my_signals:
         now_date = datetime.datetime.now().date()
         refresh_date = my_signal.refresh_date.date()
         assert now_date == refresh_date
Ejemplo n.º 5
0
 def setUpClass(cls):
     """
     create test basics
     :return:
     """
     cls.config = TraderBase.get_config()
     cls.test_logger = logging.getLogger()
     cls.test_logger.setLevel(logging.WARNING)
     cls.db_tool = Db(cls.config['sql'], cls.test_logger)
     cls.db_tool.connect()
     assert 'PYCHARM' in os.environ or cls.config['sql']['address'] == 'mysqltest'
Ejemplo n.º 6
0
 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()
Ejemplo n.º 7
0
 def setUpClass(cls):
     """
     create test basics
     :return:
     """
     cls.config = TraderBase.get_config()
     cls.test_logger = logging.getLogger()
     cls.test_logger.setLevel(logging.WARNING)
     cls.db_tool = Db(cls.config['sql'], cls.test_logger)
     cls.db_tool.connect()
     cls.portfolio_name = "TestDemoSimpleMarket"
     arguments_broker = {
         "portfolio_name": cls.portfolio_name,
         "portfolio_user": "******",
         "database_data": True,
         "db_tool": cls.db_tool,
         "cash": 20000000
     }
     cls.broker = DemoBroker(cls.config, arguments_broker, cls.test_logger)
     assert 'PYCHARM' in os.environ or cls.config['sql'][
         'address'] == 'mysqltest'
Ejemplo n.º 8
0
 def test_levermann():
     """
     Tests two stocks with freezed data set
     """
     config = TraderBase.get_config()
     db_tool = Db(config['sql'], TEST_LOGGER)
     db_tool.connect()
     symbols = [["LHA", 1, 0], ["MRK", -1, 0]]
     for symbol in symbols:
         stock = db_tool.session.query(Stock).filter(
             symbol[0] == Stock.symbol).first()
         arguments = {
             'stock':
             stock,
             'name':
             Ls.NAME,
             'bars':
             stock.get_bars(start=datetime.datetime(2016, 6, 1, 0, 0),
                            end=datetime.datetime(2017, 9, 1, 0, 0),
                            output_type=BARS_NUMPY),
             'threshold_buy':
             7,
             'threshold_sell':
             2,
             'intervals':
             None,
             'lookback':
             12
         }
         my_filter = Ls(arguments, TEST_LOGGER)
         status = my_filter.analyse()
         TEST_LOGGER.info("%s score is: %s - %s", symbol[0],
                          my_filter.get_calculation(), status)
         assert symbol[1] == my_filter.get_calculation(),\
             " Calc: %s != %s" % (symbol[1], my_filter.get_calculation())
         assert symbol[2] == status, " Status: %s != %s" % (symbol[2],
                                                            status)
     db_tool.session.close()
Ejemplo n.º 9
0
 def setUpClass(cls):
     cls.config = TraderBase.get_config()
     cls.db_tool = Db(cls.config['sql'], TEST_LOGGER)
     cls.db_tool.connect()
Ejemplo n.º 10
0
 def test2_trade(self):
     """
     Test order sell/buy
     :return:
     """
     portfolio_name = "degiro"
     portfolio_user = "******"
     arguments = {
         "portfolio_name": portfolio_name,
         "portfolio_user": portfolio_user,
         "database_data": True,
         "db_tool": self.db_tool,
         "cash": 2000
     }
     broker = DemoBroker(self.config, arguments, TEST_LOGGER)
     broker.delete_portfolio(portfolio_name, portfolio_user)
     self.db_tool.commit()
     broker.set_portfolio(portfolio_name, portfolio_user, 2000)
     order_data = {
         "orderType": OrderType.market,
         "timeType": 1,
         "price": -1,
         "size": 5
     }
     ads = self.db_tool.session.query(Stock).filter(
         Stock.symbol == 'ADS').first()
     ifx = self.db_tool.session.query(Stock).filter(
         Stock.symbol == 'IFX').first()
     lha = self.db_tool.session.query(Stock).filter(
         Stock.symbol == 'LHA').first()
     assert ads and ifx and lha
     self.assertRaises(RuntimeError, broker.buy, -1, "XETR", order_data)
     self.assertRaises(RuntimeError, broker.buy, ads.id, "TR", order_data)
     order_id = broker.buy(ads.id, "XETR", order_data)
     broker.commit_work()
     orders_by_id = list(
         broker.db_tool.session.query(Orders).filter(
             Orders.order_uuid == order_id))
     assert len(orders_by_id) == 1
     order_data["size"] = 5000
     self.assertRaises(RuntimeError, broker.buy, ads.id, "XETR", order_data)
     order_data["size"] = 6
     self.assertRaises(RuntimeError, broker.sell, ads.id, "XETR",
                       order_data)
     order_data["size"] = 5
     order_id = broker.sell(ads.id, "XETR", order_data)
     orders_by_id = list(
         broker.db_tool.session.query(Orders).filter(
             Orders.order_uuid == order_id))
     assert len(orders_by_id) == 1
     broker.delete_portfolio(portfolio_name, portfolio_user)
     broker.commit_work()
     broker.set_portfolio(portfolio_name, portfolio_user, 4000)
     broker.buy(ads.id, "XETR", order_data)
     broker.buy(ifx.id, "XETR", order_data)
     broker.buy(lha.id, "XETR", order_data)
     broker.sell(ads.id, "XETR", order_data)
     broker.sell(ifx.id, "XETR", order_data)
     order_data["size"] = 1
     broker.sell(lha.id, "XETR", order_data)
     broker.sell(lha.id, "XETR", order_data)
     broker.sell(lha.id, "XETR", order_data)
     broker.sell(lha.id, "XETR", order_data)
     broker.sell(lha.id, "XETR", order_data)
     self.assertRaises(RuntimeError, broker.sell, lha.id, "XETR",
                       order_data)
     order_data = {
         "orderType": OrderType.limit,
         "timeType": 1,
         "price": 15.25,
         "size": 5
     }
     order_id_limit = broker.buy(ifx.id, "XETR", order_data)
     assert order_id_limit
     orders_by_id = list(
         broker.db_tool.session.query(Orders).filter(
             Orders.order_uuid == order_id_limit))
     assert not orders_by_id
     broker.commit_work()
     orders_by_id = list(
         broker.db_tool.session.query(Orders).filter(
             Orders.order_uuid == order_id_limit))
     assert len(orders_by_id) == 1
     portfolio = broker.get_portfolio_object()
     assert portfolio
     broker.delete_portfolio(portfolio_name, portfolio_user)
     portfolio = broker.get_portfolio_object()
     assert portfolio is None
     db_tool_new = Db(self.config['sql'], TEST_LOGGER)
     db_tool_new.connect()
     broker.db_tool = db_tool_new
     portfolio = broker.get_portfolio_object()
     assert portfolio
     db_tool_new.session.close()