Exemplo n.º 1
0
    def get_contract_object(self, instrument_code, contract_id):
        contract_object = self._get_contract_object_from_db(
            instrument_code, contract_id)
        if contract_object.empty():
            contract_object = futuresContract(instrument_code, contract_id)

        return contract_object
Exemplo n.º 2
0
    def contracts_with_price_data_for_instrument_code(self, instrument_code):
        """
        Valid contracts for a given instrument code

        :param instrument_code: str
        :return: list of contracts
        """
        new_log = self.log.setup(instrument_code=instrument_code)

        instrument_object_with_ib_config = self._get_instrument_object_with_IB_metadata(
            instrument_code)
        if instrument_object_with_ib_config is missing_instrument:
            new_log.warn(
                "Can't get list of contracts for illdefined instrument %s" %
                instrument_code,
                instrument_code=instrument_code)
            return listOfFuturesContracts([])

        list_of_contract_dates = self.ibconnection.broker_get_futures_contract_list(
            instrument_object_with_ib_config)
        list_of_contracts = [
            futuresContract(instrument_code, contract_date)
            for contract_date in list_of_contract_dates
        ]

        return listOfFuturesContracts(list_of_contracts)
Exemplo n.º 3
0
    def put_single_leg_order_on_stack(self, broker_order):
        """

        :param broker_order: key properties are instrument_code, contract_id, quantity
        :return: int with order ID or missing_order

        """

        log = broker_order.log_with_attributes(self.log)
        log.msg("Going to submit order %s to IB" % str(broker_order))
        instrument_code = broker_order.instrument_code

        ## Next two are because we are a single leg order, but both are lists
        contract_id = broker_order.contract_id[0]
        trade = broker_order.trade[0]

        order_type = broker_order.order_type
        limit_price = broker_order.limit_price
        account = broker_order.broker_account

        contract_object = futuresContract(instrument_code, contract_id)
        contract_object_with_ib_data = self.futures_contract_data.get_contract_object_with_IB_metadata(contract_object)

        placed_broker_trade_object = self.ibconnection.broker_submit_single_leg_order(contract_object_with_ib_data, trade, account,
                                                  order_type = order_type,
                                                  limit_price = limit_price)
        if placed_broker_trade_object is missing_order:
            log.warn("Couldn't submit order")
            return missing_order

        log.msg("Order submitted to IB")

        return placed_broker_trade_object
Exemplo n.º 4
0
    def put_single_leg_order_on_stack(self, broker_order):
        """

        :param broker_order: key properties are instrument_code, contract_id, quantity
        :return: int with order ID or missing_order

        """
        instrument_code = broker_order.instrument_code

        ## Next two are because we are a single leg order, but both are lists
        contract_id = broker_order.contract_id[0]
        trade = broker_order.trade[0]

        order_type = broker_order.order_type
        limit_price = broker_order.limit_price
        account = broker_order.broker_account

        contract_object = futuresContract(instrument_code, contract_id)
        contract_object_with_ib_data = self.futures_contract_data.get_contract_object_with_IB_metadata(
            contract_object)

        trade_object = self.ibconnection.broker_submit_single_leg_order(
            contract_object_with_ib_data,
            trade,
            account,
            order_type=order_type,
            limit_price=limit_price)

        return trade_object
def get_contract_chain(instrument_code, data):
    diag_contracts = diagContracts(data)
    diag_prices = diagPrices(data)

    roll_parameters = diag_contracts.get_roll_parameters(instrument_code)

    # Get the last contract currently being used
    multiple_prices = diag_prices.get_multiple_prices(instrument_code)
    current_contract_dict = multiple_prices.current_contract_dict()
    current_contract_list = list(current_contract_dict.values())
    furthest_out_contract_date = max(current_contract_list)
    furthest_out_contract = contractDateWithRollParameters(
        roll_parameters, furthest_out_contract_date)

    # To give us wiggle room, and ensure we start collecting the new forward a
    # little in advance
    final_contract = furthest_out_contract.next_priced_contract()

    contract_date_chain = (
        final_contract.get_unexpired_contracts_from_now_to_contract_date())

    # We have a list of contract_date objects, need futureContracts
    # create a 'bare' instrument object
    instrument_object = futuresInstrument(instrument_code)

    contract_object_chain_as_list = [
        futuresContract(instrument_object, contract_date_object)
        for contract_date_object in contract_date_chain
    ]

    contract_object_chain = listOfFuturesContracts(
        contract_object_chain_as_list)

    return contract_object_chain
    def get_position_for_instrument_and_contract_date(self, instrument_code,
                                                      contract_date):
        contract_object = futuresContract(instrument_code, contract_date)

        position = self.get_position_for_contract(contract_object)

        return position
    def _perform_contract_method_for_order(self, order, method, **kwargs):
        contract_object = futuresContract(order.instrument_code, order.contract_id)
        trade_list_for_multiple_legs = order.trade.qty
        method_to_call = getattr(self, method)

        result = method_to_call(contract_object, trade_list_for_multiple_legs=trade_list_for_multiple_legs, **kwargs)

        return result
    def test_futuresContract(self):

        contract0 = futuresContract(futuresInstrument.create_empty(), "201801")

        contract1 = futuresContract.simple("EDOLLAR", "201812")

        self.assertEqual(contract1.date, "20181200")
        self.assertEqual(contract1.instrument_code, "EDOLLAR")
        self.assertTrue(contract1.expiry_date, datetime.datetime(2018,12,1))

        # dictionaries
        contract1_as_dict = contract1.as_dict()
        self.assertEqual(contract1_as_dict, dict(instrument_code = "EDOLLAR", expiry_date = (2018,12,1),
                                                 contract_date = "201812", approx_expiry_offset=0))

        contract1_fromdict = futuresContract.create_from_dict(contract1_as_dict)

        self.assertEqual(contract1_fromdict.instrument_code, "EDOLLAR")
        self.assertEqual(contract1_fromdict.expiry_date, datetime.datetime(2018,12,1))
        self.assertEqual(contract1_fromdict.date, "20181200")

        contract2 = futuresContract.simple("EDOLLAR", "20181215", expiry_date=(2018,12,15))
        self.assertEqual(contract2.expiry_date, datetime.datetime(2018,12,15))
        self.assertEqual(contract2.date, "20181215")

        contract3 = futuresContract.simple("EDOLLAR", "20181215", approx_expiry_offset = 4)
        self.assertEqual(contract3.expiry_date, datetime.datetime(2018,12,19))

        # rolling
        contract1_with_roll_data = futuresContract.create_from_dict_with_rolldata(dict(instrument_code = "EDOLLAR",
                                                                                       contract_date = "201812"),
                                                                                  dict(priced_rollcycle = "HMUZ",
                                                                                       hold_rollcycle = "Z",
                                                                                  carry_offset = 1))

        contract1a=contract1_with_roll_data.next_priced_contract()
        self.assertEqual(contract1a.date, "20190300")

        contract1b=contract1_with_roll_data.previous_priced_contract()
        self.assertEqual(contract1b.date, "20180900")

        contract1c = contract1_with_roll_data.carry_contract()
        self.assertEqual(contract1c.date, "20190300")

        contract1d = contract1_with_roll_data.next_held_contract()
        self.assertEqual(contract1d.date, "20191200")

        contract1e = contract1_with_roll_data.previous_held_contract()
        self.assertEqual(contract1e.date, "20171200")



        contract_ident = futuresContract.identGivenCodeAndContractDate("EDOLLAR", "201801")
        self.assertEqual(contract_ident, "EDOLLAR/20180100")
    def _object_given_instrumentCode_and_contractDate(self, instrument_code, contract_date):
        """
        Quickly go from eg "EDOLLAR" "201801" to an object

        :param instrument_code: str
        :param contract_date: str
        :return: futuresContract
        """

        contract_object = futuresContract(instrument_code, contract_date)

        return contract_object
Exemplo n.º 10
0
    def get_contracts_with_price_data(self):
        """

        :return: list of contracts
        """

        list_of_contract_tuples = self._get_contract_tuples_with_price_data()
        list_of_contracts = [
            futuresContract(contract_tuple[0], contract_tuple[1])
            for contract_tuple in list_of_contract_tuples
        ]

        return list_of_contracts
Exemplo n.º 11
0
    def get_list_of_order_ids_for_instrument_and_contract_id(
            self, instrument_code, contract_id):
        contract_object = futuresContract(instrument_code, contract_id)

        return self.get_list_of_order_ids_for_contract(contract_object)
Exemplo n.º 12
0
 def _perform_method_for_instrument_and_contract_date(
         self, method_name, instrument_code, contract_date, *args,
         **kwargs):
     contract_object = futuresContract(instrument_code, contract_date)
     method = getattr(self, method_name)
     return method(contract_object, *args, **kwargs)
Exemplo n.º 13
0
def update_multiple_prices_on_roll(data, current_multiple_prices,
                                   instrument_code):
    """
    Roll multiple prices

    Adds rows to multiple prices

    First row: (optionally) Inferred price and forward prices
    If there is no (old) forward contract price, one needs to be inferred
    If there is no (old) price contract price, one needs to be inferred

    Time index = Last time index + 1 second

    Second row:
    Time index:  Last time index + 1 second

    PRICE = last price of the forward contract
    PRICE_CONTRACT = previous forward contract

    FORWARD_CONTRACT = the new forward contract
    FORWARD_PRICE = the new forward price, this can be Nan; it will get filled in

    CARRY_CONTRACT = the new carry contract
    CARRY_PRICE = the new carry price: if possible infer from price, this can be Nan

    :param data: dataBlob
    :param current_multiple_prices: futuresMultiplePrices
    :return: new futuresMultiplePrices
    """

    new_multiple_prices = futuresMultiplePrices(copy(current_multiple_prices))

    ## If the last row is all Nans, we can't do this
    new_multiple_prices = new_multiple_prices.sort_index()
    new_multiple_prices = new_multiple_prices.drop_trailing_nan()

    price_column = price_column_names['PRICE']
    fwd_column = price_column_names['FORWARD']

    current_contract_dict = new_multiple_prices.current_contract_dict()
    old_forward_contract = current_contract_dict[fwd_column]

    old_priced_contract_last_price, price_inferred = get_or_infer_latest_price(
        new_multiple_prices, price_col=price_column)
    old_forward_contract_last_price, forward_inferred = get_or_infer_latest_price(
        new_multiple_prices, price_col=fwd_column)

    diag_contracts = diagContracts(data)

    instrument_object = futuresInstrument(instrument_code)
    ## Old forward contract -> New price contract
    new_price_contract_date_object = diag_contracts.get_contract_date_object_with_roll_parameters(
        instrument_code, old_forward_contract)
    new_price_contract_object = futuresContract(
        instrument_object, new_price_contract_date_object)
    new_forward_contract_object = new_price_contract_object.next_held_contract(
    )
    new_carry_contract_object = new_price_contract_object.carry_contract()

    new_price_price = get_final_matched_price_from_contract_object(
        data, new_price_contract_object, new_multiple_prices)
    new_forward_price = get_final_matched_price_from_contract_object(
        data, new_forward_contract_object, new_multiple_prices)
    new_carry_price = get_final_matched_price_from_contract_object(
        data, new_carry_contract_object, new_multiple_prices)

    new_price_contractid = new_price_contract_object.date
    new_forward_contractid = new_forward_contract_object.date
    new_carry_contractid = new_carry_contract_object.date

    # If any prices had to be inferred, then add row with both current priced and forward prices
    # Otherwise adjusted prices will break
    if price_inferred or forward_inferred:
        new_multiple_prices = new_multiple_prices.add_one_row_with_time_delta(
            dict(price=old_priced_contract_last_price,
                 forward=old_forward_contract_last_price))

    ## SOME KIND OF WARNING HERE...?

    # Now we add a row with the new rolled contracts
    new_multiple_prices = new_multiple_prices.add_one_row_with_time_delta(
        dict(price=new_price_price,
             forward=new_forward_price,
             carry=new_carry_price,
             price_contract=new_price_contractid,
             forward_contract=new_forward_contractid,
             carry_contract=new_carry_contractid))

    return new_multiple_prices
    def update_position_for_instrument_and_contract_date(
            self, instrument_code, contract_date, new_position):
        contract_object = futuresContract(instrument_code, contract_date)
        self.update_position(contract_object, new_position)

        return success
Exemplo n.º 15
0
 def __init__(self, position, *args, **kwargs):
     tradeable_object = futuresContract(*args, **kwargs)
     super().__init__(position, tradeable_object)
Exemplo n.º 16
0
    def test_futuresContract(self):

        contract0 = futuresContract(futuresInstrument.create_empty(), "201801")

        contract1 = futuresContract.simple("EDOLLAR", "201812")

        self.assertEqual(contract1.date, "20181200")
        self.assertEqual(contract1.instrument_code, "EDOLLAR")
        self.assertTrue(contract1.expiry_date, datetime.datetime(2018, 12, 1))

        # dictionaries
        contract1_as_dict = contract1.as_dict()
        self.assertEqual(
            contract1_as_dict,
            dict(
                instrument_code="EDOLLAR",
                expiry_date=(2018, 12, 1),
                contract_date="201812",
                approx_expiry_offset=0,
            ),
        )

        contract1_fromdict = futuresContract.create_from_dict(
            contract1_as_dict)

        self.assertEqual(contract1_fromdict.instrument_code, "EDOLLAR")
        self.assertEqual(contract1_fromdict.expiry_date,
                         datetime.datetime(2018, 12, 1))
        self.assertEqual(contract1_fromdict.date, "20181200")

        contract2 = futuresContract.simple("EDOLLAR",
                                           "20181215",
                                           expiry_date=(2018, 12, 15))
        self.assertEqual(contract2.expiry_date,
                         datetime.datetime(2018, 12, 15))
        self.assertEqual(contract2.date, "20181215")

        contract3 = futuresContract.simple("EDOLLAR",
                                           "20181215",
                                           approx_expiry_offset=4)
        self.assertEqual(contract3.expiry_date,
                         datetime.datetime(2018, 12, 19))

        # rolling
        contract1_with_roll_data = futuresContract.create_from_dict_with_rolldata(
            dict(instrument_code="EDOLLAR", contract_date="201812"),
            dict(priced_rollcycle="HMUZ", hold_rollcycle="Z", carry_offset=1),
        )

        contract1a = contract1_with_roll_data.next_priced_contract()
        self.assertEqual(contract1a.date, "20190300")

        contract1b = contract1_with_roll_data.previous_priced_contract()
        self.assertEqual(contract1b.date, "20180900")

        contract1c = contract1_with_roll_data.carry_contract()
        self.assertEqual(contract1c.date, "20190300")

        contract1d = contract1_with_roll_data.next_held_contract()
        self.assertEqual(contract1d.date, "20191200")

        contract1e = contract1_with_roll_data.previous_held_contract()
        self.assertEqual(contract1e.date, "20171200")

        contract_ident = futuresContract.identGivenCodeAndContractDate(
            "EDOLLAR", "201801")
        self.assertEqual(contract_ident, "EDOLLAR/20180100")
    def test_futuresContract(self):

        contract0 = futuresContract(futuresInstrument.create_empty(), "201801")

        contract1 = futuresContract.simple("EDOLLAR", "201812")

        self.assertEqual(contract1.date, "20181200")
        self.assertEqual(contract1.instrument_code, "EDOLLAR")
        self.assertTrue(contract1.expiry_date, datetime.datetime(2018, 12, 1))

        # dictionaries
        contract1_as_dict = contract1.as_dict()
        self.assertEqual(
            contract1_as_dict,
            dict(instrument_code="EDOLLAR",
                 expiry_date=(2018, 12, 1),
                 contract_date="201812",
                 approx_expiry_offset=0))

        contract1_fromdict = futuresContract.create_from_dict(
            contract1_as_dict)

        self.assertEqual(contract1_fromdict.instrument_code, "EDOLLAR")
        self.assertEqual(contract1_fromdict.expiry_date,
                         datetime.datetime(2018, 12, 1))
        self.assertEqual(contract1_fromdict.date, "20181200")

        contract2 = futuresContract.simple("EDOLLAR",
                                           "20181215",
                                           expiry_date=(2018, 12, 15))
        self.assertEqual(contract2.expiry_date,
                         datetime.datetime(2018, 12, 15))
        self.assertEqual(contract2.date, "20181215")

        contract3 = futuresContract.simple("EDOLLAR",
                                           "20181215",
                                           approx_expiry_offset=4)
        self.assertEqual(contract3.expiry_date,
                         datetime.datetime(2018, 12, 19))

        # rolling
        contract1_with_roll_data = futuresContract.create_from_dict_with_rolldata(
            dict(instrument_code="EDOLLAR", contract_date="201812"),
            dict(priced_rollcycle="HMUZ"))

        contract1a = contract1_with_roll_data.next_priced_contract()
        self.assertEqual(contract1a.date, "20190300")

        contract1b = contract1_with_roll_data.previous_priced_contract()
        self.assertEqual(contract1b.date, "20180900")

        contract3 = futuresContract.approx_first_priced_futuresContract_after_date(
            futuresInstrument("EDOLLAR"),
            rollParameters(priced_rollcycle="HMUZ"),
            datetime.datetime(1970, 12, 1))
        self.assertEqual(contract3.date, "19710300")

        list_of_contracts = listOfFuturesContracts.series_of_price_contracts_within_daterange(
            futuresInstrument("EDOLLAR"),
            rollParameters(priced_rollcycle="HMUZ"),
            datetime.datetime(2016, 1, 1), datetime.datetime(2018, 1, 1))
        self.assertEqual(list_of_contracts[0].date, "20160300")
        self.assertEqual(list_of_contracts[-1].date, "20180300")

        contract_ident = futuresContract.identGivenCodeAndContractDate(
            "EDOLLAR", "201801")
        self.assertEqual(contract_ident, "EDOLLAR/20180100")
 def _filename_given_instrument_code_and_contract_date(
         self, instrument_code, contract_date):
     contract_object = futuresContract(instrument_code, contract_date)
     return get_filename_for_package(
         self._datapath,
         "%s_%s.csv" % (instrument_code, contract_object.date))