Example #1
0
    def test_update_and_draw(self):
        """
        Tests: Evaluator#inspect_over_time

        Inspects portfolios over time and checks the results
        """
        trader = SimpleTrader(RandomPredictor(), RandomPredictor())

        evaluator = PortfolioEvaluator([trader] * 3, draw_results=False)

        full_stock_market_data = read_stock_market_data(
            [CompanyEnum.COMPANY_A, CompanyEnum.COMPANY_B],
            [PERIOD_1, PERIOD_2])

        # Calculate and save the initial total portfolio value (i.e. the cash reserve)
        portfolio1 = Portfolio(50000.0, [], 'portfolio 1')
        portfolio2 = Portfolio(100000.0, [], 'portfolio 2')
        portfolio3 = Portfolio(150000.0, [], 'portfolio 3')

        portfolios_over_time = evaluator.inspect_over_time(
            full_stock_market_data, [portfolio1, portfolio2, portfolio3],
            evaluation_offset=100)

        last_date = list(portfolios_over_time['portfolio 1'].keys())[-1]

        assert last_date == datetime.strptime('2015-12-30', '%Y-%m-%d').date()

        data_row_lengths = set(
            [len(value_set) for value_set in portfolios_over_time.values()])
        assert len(data_row_lengths) == 1
        assert data_row_lengths.pop() == 100
Example #2
0
    def test_different_mappings(self):
        """
        Tests: Evaluator#inspect_over_time and #inspect_over_time_with_mappings

        Compares if both methods return the same values
        """
        stock_market_data = read_stock_market_data(
            [CompanyEnum.COMPANY_A], [PERIOD_1, PERIOD_2, PERIOD_3])

        portfolio_1 = Portfolio(20000,
                                [SharesOfCompany(CompanyEnum.COMPANY_A, 200)])
        portfolio_2 = Portfolio(20000,
                                [SharesOfCompany(CompanyEnum.COMPANY_A, 200)])
        portfolios = [portfolio_1, portfolio_2]

        perfect_predictor = PerfectPredictor(CompanyEnum.COMPANY_A)

        trader_1 = SimpleTrader(perfect_predictor, perfect_predictor)
        trader_2 = SimpleTrader(perfect_predictor, perfect_predictor)
        trader_3 = SimpleTrader(RandomPredictor(), RandomPredictor())
        traders = [trader_1, trader_2]

        portfolio_trader_mappings = list(
            zip(portfolios, traders, [None] * len(portfolios)))

        evaluator_1 = PortfolioEvaluator([trader_1, trader_1])
        evaluator_2 = PortfolioEvaluator([])
        evaluator_3 = PortfolioEvaluator([trader_3, trader_3])

        # 1 Use evaluator that is initialized *with* traders and call `#inspect_over_time` (i.e. without traders)
        result_1 = evaluator_1.inspect_over_time(stock_market_data, portfolios,
                                                 100)

        # 2 Use evaluator that is initialized *without* traders and call `#inspect_over_time_with_mapping`
        # (i.e. with traders)
        result_2 = evaluator_2.inspect_over_time_with_mapping(
            stock_market_data, portfolio_trader_mappings, 100)

        # 3 Use evaluator that is initialized *with* traders and call `#inspect_over_time_with_mapping`
        # (i.e. with traders) - this should be no problem, because the traders given at initialization time are ignored
        result_3 = evaluator_3.inspect_over_time_with_mapping(
            stock_market_data, portfolio_trader_mappings, 100)

        assert result_1 == result_2 == result_3
Example #3
0
    def test_inspect__date_offset(self):
        """
        Tests: Evaluator#inspect_over_time

        Flavour: Test with an date offset
        """
        data = StockData([(date(2017, 1, 1), 150.0), (date(2017, 1, 2), 200.0),
                          (date(2017, 1, 3), 250.0)])
        stock_market_data = StockMarketData({CompanyEnum.COMPANY_A: data})

        portfolio = Portfolio(20000,
                              [SharesOfCompany(CompanyEnum.COMPANY_A, 200)])

        evaluator = PortfolioEvaluator(
            [SimpleTrader(RandomPredictor(), RandomPredictor())])

        portfolio_over_time: dict = \
            evaluator.inspect_over_time(stock_market_data, [portfolio], date_offset=date(2017, 1, 2))['nameless']

        assert date(2016, 12, 31) not in portfolio_over_time.keys()
        assert date(2017, 1, 1) in portfolio_over_time.keys()
        assert date(2017, 1, 2) in portfolio_over_time.keys()
        assert date(2017, 1, 3) not in portfolio_over_time.keys()
                                                     2), dt.date(2011, 12, 29)
    start_test_day, final_test_day = dt.date(2012, 1, 3), dt.date(2015, 12, 30)

    # Define initial portfolio
    name = 'DQL trader portfolio'
    portfolio = Portfolio(10000.0, [], name)

    # Initialize trader: use perfect predictors, don't use an already trained model, but learn while trading
    # trader = DqlTrader(PerfectPredictor(CompanyEnum.COMPANY_A), PerfectPredictor(CompanyEnum.COMPANY_B), False, True, MODEL_FILENAME_DQLTRADER_PERFECT_PREDICTOR)
    # trader = DqlTrader(StockANnPerfectBinaryPredictor(), StockBNnPerfectBinaryPredictor(), False, True, MODEL_FILENAME_DQLTRADER_PERFECT_NN_BINARY_PREDICTOR)
    trader = TeamBlackDqlTrader(StockANnBinaryPredictor(),
                                StockBNnBinaryPredictor(), False, True,
                                MODEL_FILENAME_DQLTRADER_NN_BINARY_PREDICTOR)

    # Start evaluation and train correspondingly; don't display the results in a plot but display final portfolio value
    evaluator = PortfolioEvaluator([trader], False)
    final_values_training, final_values_test = [], []
    for i in range(EPISODES):
        logger.info(f"DQL Trader: Starting training episode {i}")
        all_portfolios_over_time = evaluator.inspect_over_time(
            training_data, [portfolio], date_offset=start_training_day)
        portfolio_over_time = all_portfolios_over_time[name]
        final_values_training.append(
            portfolio_over_time[final_training_day].total_value(
                final_training_day, training_data))
        trader.save_trained_model()

        # Evaluation over training and visualization
        # trader_test = TeamBlackDqlTrader(PerfectPredictor(CompanyEnum.COMPANY_A), PerfectPredictor(CompanyEnum.COMPANY_B), True, False, MODEL_FILENAME_DQLTRADER_PERFECT_PREDICTOR)
        # trader_test = TeamBlackDqlTrader(StockANnPerfectBinaryPredictor(), StockBNnPerfectBinaryPredictor(), True, False, MODEL_FILENAME_DQLTRADER_PERFECT_NN_BINARY_PREDICTOR)
        trader_test = TeamBlackDqlTrader(
Example #5
0
        ('Simple Trader (Team Blue prediction)',
         Traders.SimpleTrader_with_team_blue_prediction()),
        ('Simple Trader (Team Green prediction)',
         Traders.SimpleTrader_with_team_green_prediction()),
        ('Simple Trader (Team Pink prediction)',
         Traders.SimpleTrader_with_team_pink_prediction()),
        ('Simple Trader (Team Red prediction)',
         Traders.SimpleTrader_with_team_red_prediction()),

        # Code-Camp Task 2 traders
        ('Team Blue DQL Trader (perfect prediction)',
         Traders.TeamBlueDqlTrader_with_perfect_prediction()),
        ('Team Green DQL Trader (perfect prediction)',
         Traders.TeamGreenDqlTrader_with_perfect_prediction()),
        ('Team Pink DQL Trader (perfect prediction)',
         Traders.TeamPinkDqlTrader_with_perfect_prediction()),
        ('Team Red DQL Trader (perfect prediction)',
         Traders.TeamRedDqlTrader_with_perfect_prediction())
    ]

    # Define portfolios for the traders and create a portfolio/trader mapping
    portfolio_trader_mappings = initialize_portfolios(
        10000.0, portfolio_name_trader_mappings)

    # Evaluate their performance over the testing period
    evaluator = PortfolioEvaluator([], True)
    evaluator.inspect_over_time_with_mapping(stock_market_data,
                                             portfolio_trader_mappings,
                                             date_offset=datetime.date(
                                                 2012, 1, 3))