コード例 #1
0
def test_get_ids_for_model_data():
    GIVEN("a data handler with some data and two fixed probabilities")
    GIVEN("a data handler and the directory and file name of a test file")
    directory = "./data/29184567"
    file_name = "1.156230797.txt"
    file = HistoricalExternalAPIFileHander(directory=directory, file=file_name)
    record = file.get_file_as_list()[0]
    market_start_time = file.get_market_start_time()

    adapter = ExternalAPIMarketRecordAdapter(
        market_start_time=market_start_time)
    mediator = MockMediator()

    handler = DataHandler(
        mediator=mediator,
        adapter=adapter,
        container=DataContainer(),
    )
    handler.process_data(record)

    WHEN(
        "we set the probabilities of two items and get the ids required for the next model run"
    )
    ids = handler.get_unique_ids()
    for runner_id in ids[0:2]:
        handler._set_probability(runner_id=runner_id, probability=0.1)
        ids.pop(0)

    THEN("the list omits the items which have fixed probabilities")
    model_ids = handler._get_ids_for_model_data()
    assert model_ids == ids
    assert len(model_ids) < len(handler.get_unique_ids())
コード例 #2
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_calc_order_size():
    GIVEN("a handler and a list of items with risk_percentages")
    bank = 1000
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=bank)
    items = [
        {
            "id": 123,
            "risk_percentage": -5
        },
        {
            "id": 101,
            "risk_percentage": 0.001
        },
        {
            "id": 456,
            "risk_percentage": 0.01
        },
        {
            "id": 789,
            "risk_percentage": 0.1
        },
        {
            "id": 202,
            "risk_percentage": 0.156788
        },
    ]
    WHEN("we calculate the size of the orders")
    for item in items:
        size = handler._calc_order_size(item=item)
        THEN("the correct sizes are returned")
        assert size == round(max(item.get("risk_percentage"), 0) * bank, 2)
コード例 #3
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_add_mixed_processed_orders():
    GIVEN("a handler and a set of processed orders (2 valid, 1 invalid)")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=100000000000)
    processed_orders = [
        {
            "id": 1234,
            "probability": 0.2,
            "type": "BUY",
            "ex_price": 9.1,
            "returns_price": 8.65,
            "min_size": 5,
            "size": 50000,
            "risk_percentage": 0.05,
        },
        {
            "id": 5678,
            "probability": 0.26,
            "type": "SELL",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {},
    ]
    WHEN("we add the orders to the handler")
    handler.prevent_reorder(orders=processed_orders)
    existing_orders = handler.get_orders()
    THEN("the correct number of orders have been added to the handler")
    assert len(existing_orders) == 2
    THEN("the correct order data has been added to the handler")
    assert existing_orders == processed_orders[0:2]
コード例 #4
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_post_order(mock_notify):
    GIVEN("a file, a directory and a mock mediator")
    directory = "./dev"
    file = "1.163093692.bz2"
    mediator = MockMediator()

    WHEN("we instantiate the handler and post a valid order")
    handler = HistoricalDownloadFileHandler(file=file, directory=directory)
    handler.set_mediator(mediator)
    runner_id = 2121212
    orders = [{
        "id": runner_id,
        "type": "BUY",
        "ex_price": 2.5,
        "size": 1000000
    }]
    handler.post_order(orders)

    THEN("the correct data is passed to the mediator")
    args, kwargs = mock_notify.call_args
    assert args == ()
    data = kwargs.get("data")
    assert data.get("response") == [{
        "instruction": {
            "selectionId": runner_id
        },
        "status": "SUCCESS"
    }]
    assert data.get("orders") == orders
コード例 #5
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_valid_and_invalid_orders():
    GIVEN("a market handler two valid orders and two invalid orders")
    market_handler = ExternalAPIMarketHandler(mediator=MockMediator(),
                                              environment="Dev",
                                              headers={},
                                              market_id=123456)
    orders = [
        {
            "id": 9999999,
            "size": 100,
            "ex_price": 2.0
        },
        {
            "id": 8888888,
            "type": "SELL",
            "size": 6.18,
            "ex_price": 75.0
        },
        {
            "id": 7777777,
            "type": "BUY",
            "size": 5,
            "ex_price": 12.6
        },
        {
            "id": 7777777,
            "type": "BUY",
            "size": 5,
            "ex_price": "THE BEST YOU HAVE"
        },
    ]
    valid_orders = market_handler._validate_orders(orders=orders)
    THEN("the valid orders are returned")
    assert valid_orders == orders[1:3]
コード例 #6
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_single_item(mock_notify):
    GIVEN("an orders handler and some items")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=5000)
    items = [{
        "id": 16397186,
        "probability": 0.19889500121124917,
        "type": "BUY",
        "ex_price": 6.4,
        "returns_price": 6.13,
    }]

    WHEN("we call get_new_orders")
    handler.get_new_orders(items=items)

    THEN("the mediator's notify method is called with the correct paramaters")
    args, kwargs = mock_notify.call_args
    assert args == ()
    assert kwargs.get("event") == "new orders"
    new_orders = kwargs.get("data")

    THEN("the correct order information is returned")
    assert new_orders == [{
        "id": 16397186,
        "probability": 0.19889500121124917,
        "type": "BUY",
        "ex_price": 6.4,
        "returns_price": 6.13,
        "min_size": 5,
        "size": 250.0,
        "risk_percentage": 0.05,
    }]

    WHEN("we add the order to the handler (after processing)")
    handler.prevent_reorder(orders=new_orders)
    THEN("the correct information has been added to the handler")
    assert handler.get_orders() == new_orders

    WHEN("we try to add the order to the handler a second time")
    handler.prevent_reorder(orders=new_orders)
    THEN("the order has not been added again to the handler")
    assert handler.get_orders() == new_orders

    WHEN("we try to get new orders again using the same item")
    handler.get_new_orders(items=items)

    THEN("the mediator's notify method is called with the correct paramaters")
    args, kwargs = mock_notify.call_args
    assert args == ()
    assert kwargs.get("event") == "finished processing"
    new_orders = kwargs.get("data")

    THEN("there are no new orders")
    assert not new_orders
    assert new_orders is None
コード例 #7
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_valid_orders():
    GIVEN("a market handler and a set of valid orders")
    market_handler = ExternalAPIMarketHandler(mediator=MockMediator(),
                                              environment="Dev",
                                              headers={},
                                              market_id=123456)
    orders = get_test_orders()
    WHEN("we validate the orders")
    valid_orders = market_handler._validate_orders(orders=orders)
    THEN("all of the orders are shown to be valid")
    assert valid_orders == orders
コード例 #8
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_calc_reduced_risk_percentage():
    GIVEN(
        "a set of risk percentages and an orders handler with an existing order"
    )
    items = [
        {
            "id": 123,
            "risk_percentage": 0.01
        },
        {
            "id": 456,
            "risk_percentage": 0.01
        },
        {
            "id": 789,
            "risk_percentage": 0.02
        },
        {
            "id": 101,
            "risk_percentage": 0
        },
    ]
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=5000)
    existing_orders = [{
        "id": 999,
        "probability": 0.26,
        "type": "SELL",
        "ex_price": 5,
        "returns_price": 4.75,
        "min_size": 5,
        "size": 10000,
        "risk_percentage": 0.03,
    }]
    handler.prevent_reorder(existing_orders)

    WHEN("we calculate the reduced risk percentages")
    reduced_risk_percentages = handler._calc_reduced_risk_percentage(
        initial_risk_percentage=items)

    THEN("the percentages have been reduced")
    assert reduced_risk_percentages.get(
        123) == 0.01 * (1 - 0.01) * (1 - 0.02) * (1 - 0.03)
    assert reduced_risk_percentages.get(
        456) == 0.01 * (1 - 0.01) * (1 - 0.02) * (1 - 0.03)
    assert reduced_risk_percentages.get(
        789) == 0.02 * (1 - 0.01) * (1 - 0.01) * (1 - 0.03)
    assert reduced_risk_percentages.get(101) == 0
    assert reduced_risk_percentages.get(999) is None
コード例 #9
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_calc_no_risk_percentage():
    GIVEN("a handler, a probability and an equal price")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=1)
    probability = 0.5
    price = 2

    WHEN("we calculate cap the risk percentage at 10%")
    no_risk = handler._calc_risk_percentage(probability=probability,
                                            price=price)
    THEN("the correct risk percentage is returned")
    assert no_risk == 0

    GIVEN("a handler, a probability and a smaller price")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=1)
    probability = 0.5
    price = 1.5

    WHEN("we calculate cap the risk percentage at 10%")
    no_risk = handler._calc_risk_percentage(probability=probability,
                                            price=price)
    THEN("the correct risk percentage is returned")
    assert no_risk == 0

    GIVEN("a handler, a negative probability and negative price")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=1)
    probability = -0.5
    price = -2.1

    WHEN("we calculate cap the risk percentage at 10%")
    no_risk = handler._calc_risk_percentage(probability=probability,
                                            price=price)
    THEN("the correct risk percentage is returned")
    assert no_risk == 0
コード例 #10
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_invalid_order():
    GIVEN("a market handler and an invalid order")
    market_handler = ExternalAPIMarketHandler(mediator=MockMediator(),
                                              environment="Dev",
                                              headers={},
                                              market_id=123456)
    orders = [
        {
            "type": "BUY",
            "size": 100,
            "ex_price": 2.0
        },
    ]
    valid_orders = market_handler._validate_orders(orders=orders)
    THEN("the order is marked as invalid and omitted from the returned list")
    assert not valid_orders
コード例 #11
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_empty_items(mock_notify):
    GIVEN("an orders handler and some items")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=5000)
    items = []

    WHEN("we call get_new_orders")
    handler.get_new_orders(items=items)

    THEN("the mediator's notify method is called with the correct paramaters")
    args, kwargs = mock_notify.call_args
    assert args == ()
    assert kwargs.get("event") == "finished processing"
    new_orders = kwargs.get("data")

    THEN("there are no new orders")
    assert not new_orders
    assert new_orders is None
コード例 #12
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_post_data(mock_call_exchange):

    GIVEN("a market handler and some orders")
    market_handler = ExternalAPIMarketHandler(mediator=MockMediator(),
                                              environment="Dev",
                                              headers={},
                                              market_id=123456)
    orders = get_test_orders()

    WHEN("we post the orders")
    market_handler.post_order(orders=orders)
    THEN("the exchange was called with the correct request")
    args, kwargs = mock_call_exchange.call_args
    request = make_dict(kwargs.get("request"))
    expected_request = get_expected_request()
    assert args == ()
    assert request.get("params").get("instructions") == expected_request.get(
        "params").get("instructions")
コード例 #13
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_get_market(mock_notify):
    GIVEN("a file and a directory with the correct market type")
    directory = "./dev"
    file = "1.163093692.bz2"

    WHEN("we instantiate the handler")
    handler = HistoricalDownloadFileHandler(file=file, directory=directory)
    mediator = MockMediator()
    handler.set_mediator(mediator)

    WHEN("we call get market for every record in the file")
    for record in handler.get_file_as_list():
        handler.get_market()

        THEN("the correct data is sent to the mediator")
        args, kwargs = mock_notify.call_args
        assert args == ()
        data = kwargs.get("data")
        assert data == record
コード例 #14
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_incorrect_type(mock_notify):
    GIVEN("a file and in a directory which contains the incorrect market type")
    directory = "./dev"
    file = "1.156749791.bz2"

    WHEN("we instantiate the handler")
    handler = HistoricalDownloadFileHandler(file=file, directory=directory)
    mediator = MockMediator()
    handler.set_mediator(mediator)

    THEN("it has loaded not loaded the file as an iterator")
    assert handler.get_file_as_list() == []

    WHEN("we call get_market")
    market = handler.get_market()

    THEN("no data is returned")
    assert market is None

    THEN("the mediator was not called")
    assert mock_notify.call_args is None
コード例 #15
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_calc_risk_percentage():
    GIVEN("a handler, a probability and price")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=1)
    probability = 0.6
    price = 2

    WHEN("we calculate the uncapped risk percentage")
    risk = handler._calc_risk_percentage(probability=probability,
                                         price=price,
                                         kelly_fraction=1,
                                         cap=1)
    THEN("the correct risk percentage is returned")
    assert almost_equal(risk,
                        ((probability * price) - (1 - probability)) / price)

    WHEN("we calculate cap the risk percentage at 10%")
    capped_risk = handler._calc_risk_percentage(probability=probability,
                                                price=price,
                                                kelly_fraction=1,
                                                cap=0.1)
    THEN("the correct risk percentage is returned")
    assert capped_risk == 0.1

    WHEN("we calculate the risk percentage based on a reduced kelly fraction")
    fraction = 0.1
    reduced_risk = handler._calc_risk_percentage(probability=probability,
                                                 price=price,
                                                 kelly_fraction=fraction,
                                                 cap=1)
    THEN("the reduced risk is less than the original risk")
    assert reduced_risk < risk
    THEN("the correct risk percentage is returned")
    assert almost_equal(
        reduced_risk,
        (((probability * price)**fraction - (1 - probability)**fraction) /
         ((price * probability)**fraction + (price *
                                             (1 - probability))**fraction)),
    )
コード例 #16
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_order_response(mock_notify, mock_open_url):
    GIVEN("a market handler and some orders")
    market_handler = ExternalAPIMarketHandler(mediator=MockMediator(),
                                              environment="Dev",
                                              headers={},
                                              market_id=123456)
    orders = get_test_orders()
    mock_open_url.return_value = get_test_orders_post_response()
    WHEN("we post the orders")
    response = market_handler.post_order(orders=orders)
    THEN("the notify method was called with the correct parameters")
    args, kwargs = mock_notify.call_args
    assert args == ()
    data = kwargs.get("data")
    assert data.get("orders") == orders
    assert kwargs.get("event") == "orders posted"

    response = data.get("response")
    assert isinstance(response, list)
    assert len(response) == 3
    for order in response:
        assert order.get("status") == "SUCCESS"
コード例 #17
0
def test_confirm_market_closed():
    GIVEN("a data handler and the directory and file name of a test file")
    adapter = ExternalAPIMarketRecordAdapter(
        market_start_time="2019-01-01T00:00:00.000Z")
    mediator = MockMediator()

    handler = DataHandler(mediator=mediator,
                          adapter=adapter,
                          container=DataContainer())

    WHEN("we check if the market is closed")
    closed = handler._confirm_market_closed()
    THEN("it is not")
    assert not closed

    GIVEN("the handler's container has the required column" +
          " but it does not indicate that the market is closed")
    closed_record = handler._container.new(
        data={("closed_indicator", ""): [0]})
    handler._container.add_rows(container=closed_record)

    WHEN("we check if the market is closed")
    closed = handler._confirm_market_closed()
    THEN("it is not")
    assert not closed

    GIVEN(
        "the handler's container has the required column indicating that the market is closed"
    )
    closed_record = handler._container.new(
        data={("closed_indicator", ""): [1]})
    handler._container.add_rows(container=closed_record)

    WHEN("we check if the market is closed")
    closed = handler._confirm_market_closed()
    THEN("it is")
    assert closed
コード例 #18
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_get_data(mock_notify):

    GIVEN(
        "a schedule handler and a market handler connected to the dev environment"
    )
    schedule_handler = ExternalAPIScheduleHandler(environment="Dev")
    headers = schedule_handler.get_headers()
    markets = schedule_handler.get_schedule("7",
                                            DateTime.utc_5_minutes_from_now())

    WHEN(
        "we create an instance of the market handler for each market and ask for data"
    )
    for market in markets:
        market_id = market.get("marketId")

        market_handler = ExternalAPIMarketHandler(
            mediator=MockMediator(),
            environment="Dev",
            headers=headers,
            market_id=market_id,
        )
        market_info = market_handler.get_market()

        THEN("the notify method was called with the correct parameters")
        args, kwargs = mock_notify.call_args
        assert args == ()
        assert kwargs.get("event") == "external data fetched"
        market_info = kwargs.get("data")
        assert isinstance(market_info, dict)
        if market_info:
            THEN("the dict contains a list of items")
            items = market_info.get("runners")
            assert isinstance(items, list)
            THEN("the dict has an extract time")
            process_time = market_info.get("process_time")
            assert isinstance(process_time, str)
コード例 #19
0
def test_removed_runner():
    GIVEN(
        "the directory and file name of a test file which contains a removed runner"
    )
    directory = "./data/29201704"
    file_name = "1.156695742.txt"
    file = HistoricalExternalAPIFileHander(directory=directory, file=file_name)
    file_data = file.get_file_as_list()
    market_start_time = file.get_market_start_time()
    adapter = ExternalAPIMarketRecordAdapter(
        market_start_time=market_start_time)
    number_runners = __get_number_runners(data=file_data)
    mediator = MockMediator()

    WHEN("we feed the data into a handler one record at a time")

    handler = DataHandler(
        mediator=mediator,
        adapter=adapter,
        container=DataContainer(),
    )
    for i, record in enumerate(file_data):
        handler.process_data(record)
        THEN("the incoming record was processed")
        number_records_processed = i + 1
        THEN("the data container the correct number of records")
        assert handler._container.get_row_count() == number_records_processed

    WHEN("we have finished")
    THEN("the data container has the correct number of columns")
    assert handler._container.get_column_count() == __get_number_columns(
        number_runners)
    THEN("the data container has the same number of records as the raw data")
    assert handler._container.get_row_count() == len(file_data)
    THEN("the correct number of runners are contained in the object")
    assert len(handler.get_unique_ids()) == number_runners
コード例 #20
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_place_order(mock_notify, mock_open_url):

    GIVEN("a set of orders and a market handler")
    orders = get_test_orders()
    external_api = ExternalAPIMarketHandler(environment="Dev",
                                            headers={},
                                            market_id=123456)
    handler = MarketHandler(
        market_id=123456,
        external_api=external_api,
        market_start_time="2019-01-01T00:00:00.000Z",
    )
    external_api.set_mediator(mediator=MockMediator())
    mock_open_url.return_value = get_test_orders_post_response()
    WHEN("we place the orders")
    handler.notify(event="new orders", data=orders)
    THEN("the notify method was called with the correct parameters")
    args, kwargs = mock_notify.call_args
    assert args == ()
    data = kwargs.get("data")
    assert data.get("response") == get_test_orders_post_response().get(
        "instructionReports")
    assert data.get("orders") == orders
    assert kwargs.get("event") == "orders posted"
コード例 #21
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_handler():
    GIVEN("a file and a directory with the correct market type")
    directory = "./dev"
    file = "1.163093692.bz2"

    WHEN("we instantiate the handler")
    handler = HistoricalDownloadFileHandler(file=file, directory=directory)
    mediator = MockMediator()
    handler.set_mediator(mediator)

    THEN("the first of the eligible records has a process" +
         " time within 5 minutes of the market start time")

    market_data = handler.get_file_as_list()
    first_eligible = market_data[0]
    assert first_eligible.get("extract_time") >= -60 * 5

    THEN(
        "the first eligible record does not have a closed indicator set to true"
    )
    assert first_eligible.get("closed_indicator") is False

    THEN(
        "the last of the eligible records has a process time after the market start time"
    )
    last_eligible = market_data[-2]
    assert last_eligible.get("extract_time") > 0

    THEN("the last eligible record has a closed indicator set to false")
    assert last_eligible.get("closed_indicator") is False

    THEN(
        "the last of the records has a process time after the market start time"
    )
    last_record = market_data[-1]
    assert last_record.get("extract_time") > last_eligible.get("extract_time")

    THEN("the last eligible record has a closed indicator set to true")
    assert last_record.get("closed_indicator") is True

    THEN("the times in the list are unique")
    assert len(handler._data._existing_times) == len(
        set(handler._data._existing_times))

    THEN("the extract times in the eligible records are unique")
    extract_times = [record.get("extract_time") for record in market_data]
    assert len(extract_times) == len(set(extract_times))

    for index, record in enumerate(market_data):
        THEN("each of the extract times is within the expected range")
        extract_time = record.get("extract_time")
        assert -5 * 60 <= extract_time < 60 * 60
        THEN(
            "the extract time is a single second after the previous extract time"
        )
        if index > 0:
            assert extract_time == (
                market_data[index - 1].get("extract_time") + 1)
        THEN("each of the eligible records has a dict of items")
        items = record.get("items")
        assert isinstance(items, dict)
        THEN("the keys of the items dict matches the ids of the items")
        assert list(items.keys()) == __get_test_ids()
        THEN(
            "each of the items has no 0 value for each attribute and a starting price"
        )
        for runner_id in __get_test_ids():
            assert items[runner_id]["sp"]["spn"]
            assert 0 not in items[runner_id]["ex"]["atb"].values()
            assert 0 not in items[runner_id]["ex"]["atl"].values()
            assert 0 not in items[runner_id]["ex"]["trd"].values()
            assert 0 not in items[runner_id]["sp"]["spb"].values()
            assert 0 not in items[runner_id]["sp"]["spl"].values()
        THEN(
            "once the closed indicator becomes true is does not change back to false"
        )
        if index > 0 and market_data[index -
                                     1].get("closed_indicator") is True:
            assert record.get("closed_indicator") is True

    WHEN("we call get_outcome")
    result = handler.get_outcome()

    THEN("the result is as expected")
    assert result == 19795432
コード例 #22
0
def test_fixed_probability(mock_notify):
    GIVEN("a data handler and the directory and file name of a test file")

    directory = "./data/29451865"
    file_name = "1.162069495.txt"
    file = HistoricalExternalAPIFileHander(directory=directory, file=file_name)
    file_data = file.get_file_as_list()
    market_start_time = file.get_market_start_time()

    number_runners = __get_number_runners(data=file_data)
    unfixed_items = number_runners
    fixed_items = 0
    adapter = ExternalAPIMarketRecordAdapter(
        market_start_time=market_start_time)
    pricer = PriceHandler()
    metadata = MetadataHandler()
    mediator = MockMediator()
    correct_probability = 1

    number_records_processed = 0

    WHEN("we feed the data into a handler one record at a time")
    handler = DataHandler(
        mediator=mediator,
        adapter=adapter,
        container=DataContainer(),
    )
    for i, record in enumerate(file_data):
        number_records_processed = i + 1
        if number_records_processed % 10 == 0:
            WHEN("we randomly fix the probability of an item")
            id_to_fix = handler._get_ids_for_model_data()[0]
            fixed_probability = round(
                handler._container.get_last_column_entry(
                    name=("compositional_sp_probability", id_to_fix)),
                4,
            )
            handler._set_probability(runner_id=id_to_fix,
                                     probability=fixed_probability)
            correct_probability -= fixed_probability
            unfixed_items -= 1
            fixed_items += 1

        fixed_probability_ids = handler._get_fixed_probability_ids()
        THEN("the list of fixed probability ids is the correct length")
        assert len(fixed_probability_ids) == fixed_items

        handler.process_data(record)

        THEN("the handler's data has the correct number of records")
        assert handler._container.get_row_count() == number_records_processed

        THEN(
            "the mediator's notify method was called with the correct parameters"
        )
        model_data = handler._get_model_data()
        args, kwargs = mock_notify.call_args
        assert args == ()
        assert kwargs.get("data") == model_data
        assert kwargs.get("event") == "data added to container"

        THEN(
            "there is a record in the model data for each of the unfixed items"
        )
        assert len(model_data) == unfixed_items

        test_record = {
            each.get("id"): each
            for each in adapter.convert(record).get("items")
        }
        total_sp_probability = 0
        total_ex_probability = 0

        for data in model_data:
            THEN("each of the items in the model data has an non-zero id")
            runner_id = data.get("id")
            assert isinstance(runner_id, int)
            assert runner_id > 0

            THEN("the items probability has not been fixed")
            assert runner_id not in fixed_probability_ids

            test_item = test_record.get(runner_id)

            THEN("the data has the correct combined_back_size")
            combined_back_size = data.get("combined_back_size" +
                                          metadata.get_point_in_time_suffix())
            assert combined_back_size == (test_item.get("sp_back_size") +
                                          test_item.get("ex_back_size"))

            THEN(
                "the data contains the compositional sp probability which is between 0 and 1"
            )
            compositional_sp_probability = data.get(
                "compositional_sp_probability" +
                metadata.get_point_in_time_suffix())
            total_sp_probability += compositional_sp_probability
            assert 1 > compositional_sp_probability > 0

            THEN(
                "the data contains the compositional ex probability which is between 0 and 1"
            )
            compositional_ex_average_probability = data.get(
                "compositional_ex_average_probability" +
                metadata.get_point_in_time_suffix())
            total_ex_probability += compositional_ex_average_probability
            assert 1 > compositional_ex_average_probability > 0

            THEN("the data contains the correct offered price")
            offered_price = data.get("ex_offered_back_price" +
                                     metadata.get_point_in_time_suffix())
            assert offered_price > 0
            assert offered_price == test_item.get("ex_offered_back_price")

            THEN("the data contains the correct returns price")
            returns_price = data.get("ex_offered_back_price_mc" +
                                     metadata.get_point_in_time_suffix())
            assert returns_price > 0
            assert returns_price == pricer.remove_commission(
                test_item.get("ex_offered_back_price"))

            THEN(
                "the sp back price time series data returned is of the correct length"
            )
            compositional_sp_back_price_ts = (
                data.get("compositional_sp_back_price" +
                         metadata.get_time_series_suffix()) or [])
            assert len(
                compositional_sp_back_price_ts) == number_records_processed
            THEN(
                "the last record of the time series data matches the probability"
            )
            assert almost_equal(compositional_sp_back_price_ts[-1],
                                1 / compositional_sp_probability)

            THEN(
                "the extract time time series data returned is of the correct length"
            )
            extract_time_ts = (data.get("extract_time" +
                                        metadata.get_time_series_suffix())
                               or [])
            assert len(extract_time_ts) == number_records_processed
            for j, extract_time in enumerate(extract_time_ts):
                if j > 0:
                    THEN("the times in the series are ascending")
                    assert extract_time > extract_time_ts[j - 1]

            THEN(
                "the combined back size time series data returned is of the correct length"
            )
            combined_back_size_ts = (
                data.get("combined_back_size" +
                         metadata.get_time_series_suffix()) or [])
            assert len(combined_back_size_ts) == number_records_processed
            THEN(
                "the last entry in the time series is the same as point in time combined_back_size"
            )
            assert combined_back_size_ts[-1] == combined_back_size
            for j, combined_back_size in enumerate(combined_back_size_ts):
                if j > 0:
                    THEN("the sizes in the series are ascending")
                    assert combined_back_size >= combined_back_size_ts[j - 1]

        THEN("the total ex and sp probabilities from the model_data sum to 1")
        assert almost_equal(total_sp_probability, correct_probability)
        assert almost_equal(total_ex_probability, correct_probability)

    WHEN("we have finished")
    THEN("the data container has the correct number of columns")
    assert handler._container.get_column_count() == __get_number_columns(
        number_runners)
    THEN("the data container has the same number of records as the raw data")
    assert handler._container.get_row_count() == len(file_data)
    THEN("the correct number of runners are contained in the object")
    assert len(handler.get_unique_ids()) == number_runners
    THEN(
        "the correct number of fixed probabilities are contained in the object"
    )
    assert len(handler._get_fixed_probability_ids()) == round_down(
        number_records_processed / 10)
コード例 #23
0
ファイル: handler_test.py プロジェクト: mattseddon/billy_cart
def test_add_invalid_processed_orders():
    GIVEN("a handler and a set of valid processed orders")
    mediator = MockMediator()
    handler = OrdersHandler(mediator=mediator, bank=100000000000)
    processed_orders = [
        {
            "probability": 0.5,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "no probability",
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "negative probability",
            "probability": -0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "wrong probability",
            "probability": 1.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "no type",
            "probability": 0.26,
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "wrong type",
            "type": "FIXED",
            "probability": 0.26,
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "no buy price",
            "probability": 0.26,
            "type": "BUY",
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "negative buy price",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": -5,
            "returns_price": 4.75,
            "min_size": 5,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "no min size",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "0 min size",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 0,
            "size": 10000,
            "risk_percentage": 0.01,
        },
        {
            "id": "no size",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 0,
            "risk_percentage": 0.01,
        },
        {
            "id": "size below min size",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 2,
            "size": 1,
            "risk_percentage": 0.01,
        },
        {
            "id": "no risk percentage",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 2,
            "size": 1,
        },
        {
            "id": "negative risk percentage",
            "probability": 0.26,
            "type": "BUY",
            "ex_price": 5,
            "returns_price": 4.75,
            "min_size": 2,
            "size": 1,
            "risk_percentage": -0.01,
        },
    ]
    WHEN("we try to add the orders to the handler")
    handler.prevent_reorder(orders=processed_orders)
    existing_orders = handler.get_orders()
    THEN("no order data has been added to the handler")
    assert not existing_orders