Example #1
0
def actual_contract_position(data):
    diag_positions = diagPositions(data)

    instrument_code_list = diag_positions.get_list_of_instruments_with_any_position(
    )
    instrument_code = get_valid_code_from_list(instrument_code_list)
    if instrument_code is user_exit:
        return None

    contract_code_list = (
        diag_positions.
        get_list_of_contracts_with_any_contract_position_for_instrument(
            instrument_code))
    contract_code = get_valid_code_from_list(contract_code_list)
    if contract_code is user_exit:
        return None

    pos_series = diag_positions.get_position_df_for_instrument_and_contract_id(
        instrument_code, contract_code)
    print(pos_series)
    return None
Example #2
0
    def get_actual_positions_for_strategy(self):
        """
        Actual positions held by a strategy

        Useful to know, usually

        :return: dict, keys are instrument codes, values are positions
        """
        data = self.data
        strategy_name = self.strategy_name

        diag_positions = diagPositions(data)
        list_of_instruments = (
            diag_positions.get_list_of_instruments_for_strategy_with_position(
                strategy_name))
        actual_positions = dict([(
            instrument_code,
            diag_positions.get_position_for_strategy_and_instrument(
                strategy_name, instrument_code),
        ) for instrument_code in list_of_instruments])
        return actual_positions
def actual_instrument_position(data):
    diag_positions = diagPositions(data)

    strategy_name_list = diag_positions.get_list_of_strategies_with_positions()
    strategy_name = print_menu_of_values_and_get_response(strategy_name_list)
    if strategy_name is user_exit:
        return None

    instrument_code_list = (
        diag_positions.get_list_of_instruments_for_strategy_with_position(
            strategy_name, ignore_zero_positions=False))
    instrument_code = get_valid_code_from_list(instrument_code_list)
    if instrument_code is user_exit:
        return None
    instrument_strategy = instrumentStrategy(strategy_name=strategy_name,
                                             instrument_code=instrument_code)

    pos_series = diag_positions.get_position_df_for_instrument_strategy(
        instrument_strategy)
    print(pos_series)
    return None
Example #4
0
def setup_roll_data(data: dataBlob, instrument_code: str) -> RollData:
    diag_positions = diagPositions(data)
    diag_contracts = dataContracts(data)

    original_roll_status = diag_positions.get_roll_state(instrument_code)
    priced_contract_date = diag_contracts.get_priced_contract_id(
        instrument_code)

    contract = futuresContract(instrument_code, priced_contract_date)

    position_priced_contract = (
        diag_positions.get_position_for_contract(contract)
    )

    allowable_roll_states = allowable_roll_state_from_current_and_position(
        original_roll_status, position_priced_contract
    )

    roll_data = RollData(instrument_code, original_roll_status, position_priced_contract, allowable_roll_states)

    return roll_data
Example #5
0
def get_position_for_instrument_code_at_timestamp(data_backtest, data,
                                                  instrument_code):
    diag_positions = diagPositions(data)

    strategy_name = data_backtest.strategy_name
    instrument_strategy = instrumentStrategy(strategy_name=strategy_name,
                                             instrument_code=instrument_code)

    positions_over_time = diag_positions.get_position_df_for_instrument_strategy(
        instrument_strategy)
    if positions_over_time is missing_data:
        return np.nan

    datetime_cutoff = from_marker_to_datetime(data_backtest.timestamp)
    positions_over_time_ffill = positions_over_time.ffill()
    positions_before_cutoff = positions_over_time_ffill[:datetime_cutoff]

    if len(positions_before_cutoff) == 0:
        return np.nan
    final_position = positions_before_cutoff.iloc[-1].position

    return final_position
def actual_contract_position(data):
    diag_positions = diagPositions(data)

    instrument_code_list = diag_positions.get_list_of_instruments_with_any_position()
    instrument_code = get_valid_code_from_list(instrument_code_list)
    if instrument_code is user_exit:
        return None

    contract_code_list = (
        diag_positions.get_list_of_contracts_with_any_contract_position_for_instrument(
            instrument_code
        )
    )
    contract_date_str = get_valid_code_from_list(contract_code_list)
    if contract_date_str is user_exit:
        return None
    # ignore warnings can be str
    contract = futuresContract(instrument_code, contract_date_str)

    pos_series = diag_positions.get_position_df_for_contract(contract)
    print(pos_series)
    return None
    def apply_overrides_for_instrument_and_strategy(self, proposed_order):
        """
        Apply an override to a trade

        :param strategy_name: str
        :param instrument_code: str
        :return: int, updated position
        """

        diag_overrides = diagOverrides(self.data)
        diag_positions = diagPositions(self.data)

        strategy_name = proposed_order.strategy_name
        instrument_code = proposed_order.instrument_code

        original_position = diag_positions.get_position_for_strategy_and_instrument(
            strategy_name, instrument_code)

        override = diag_overrides.get_cumulative_override_for_strategy_and_instrument(
            strategy_name, instrument_code)
        revised_order = override.apply_override(
            original_position, proposed_order)

        if revised_order.trade != proposed_order.trade:
            self.log.msg(
                "%s/%s trade change from %d to %d because of override %s"
                % (
                    strategy_name,
                    instrument_code,
                    revised_order.trade,
                    proposed_order.trade,
                    str(override),
                ),
                strategy_name=strategy_name,
                instrument_code=instrument_code,
            )

        return revised_order
def view_positions(data):
    data_broker = dataBroker(data)

    diag_positions = diagPositions(data)
    ans1=diag_positions.get_all_current_strategy_instrument_positions()
    ans2 = diag_positions.get_all_current_contract_positions()
    ans3 = data_broker.get_all_current_contract_positions()
    print("Strategy positions")
    print(ans1)
    print("\n Contract level positions")
    print(ans2)
    breaks = diag_positions.get_list_of_breaks_between_contract_and_strategy_positions()
    if len(breaks)>0:
        print("\nBREAKS between strategy and contract positions: %s\n" % str(breaks))
    else:
        print("(No breaks positions consistent)")
    print("\n Broker positions")
    print(ans3)
    breaks = data_broker.get_list_of_breaks_between_broker_and_db_contract_positions()
    if len(breaks)>0:
        print("\nBREAKS between broker and DB stored contract positions: %s\n" % str(breaks))
    else:
        print("(No breaks positions consistent)")
    return None
Example #9
0
def get_my_positions(data):
    diag_positions = diagPositions(data)
    my_positions = diag_positions.get_all_current_contract_positions().as_pd_df()
    my_positions  = my_positions.sort_values("instrument_code")

    return my_positions
def get_required_contract_trade_for_instrument(data, instrument_order):
    """
    Return the contract to trade for a given instrument

    Depends on roll status and trade vs position:
     - roll_states = ['No_Roll', 'Passive', 'Force', 'Force_Outright', 'Roll_Adjusted']

    If 'No Roll' then trade current contract
    If 'Passive', and no position in current contract: trade next contract
    If 'Passive', and reducing trade which leaves zero or something in current contract: trade current contract
    If 'Passive', and reducing trade which is larger than current contract position: trade current and next contract
    If 'Passive', and increasing trade: trade next contract
    If 'Force' or 'Force Outright' or 'Roll_Adjusted': don't trade

    :param instrument_order:
    :param data: dataBlog
    :return: tuple: list of child orders: each is a tuple: contract str or missing_contract, trade int
    """
    instrument_code = instrument_order.instrument_code
    log = instrument_order.log_with_attributes(data.log)
    trade = instrument_order.trade.as_int()
    if trade is missing_order:
        log.critical("Instrument order can't be a spread order")
        return missing_contract

    diag_contracts = diagContracts(data)
    current_contract = diag_contracts.get_priced_contract_id(instrument_code)
    next_contract = diag_contracts.get_forward_contract_id(instrument_code)

    diag_positions = diagPositions(data)
    roll_state = diag_positions.get_roll_state(instrument_code)

    position_current_contract = (
        diag_positions.get_position_for_instrument_and_contract_date(
            instrument_code, current_contract
        )
    )
    if roll_state == "No_Roll":
        log.msg(
            "No roll, allocating entire order %s to current contract %s"
            % (str(instrument_order), current_contract)
        )
        return [(current_contract, trade)]

    elif roll_state in ["Force", "Force_Outright", "Roll_Adjusted"]:
        log.msg(
            "Roll state %s is rolling, not going to generate trade for order %s" %
            (roll_state, str(instrument_order)))
        return rolling_cant_trade

    elif roll_state == "Passive":
        return passive_roll_child_order(
            position_current_contract,
            current_contract,
            next_contract,
            trade,
            log,
            instrument_order,
        )
    else:
        log.critical(
            "Roll state %s not understood: can't generate trade for %s"
            % (roll_state, str(instrument_order))
        )
        return missing_contract
Example #11
0
def get_list_of_strategies(data):
    diag_positions = diagPositions(data)
    return diag_positions.get_list_of_strategies_with_positions()
Example #12
0
def get_list_of_strategies_from_positions(
        data: dataBlob = arg_not_supplied) -> list:
    diag_positions = diagPositions(data)
    list_of_strategies = diag_positions.get_list_of_strategies_with_positions()

    return list_of_strategies
Example #13
0
    def check_if_forced_roll_required(self, instrument_code: str) -> bool:
        diag_positions = diagPositions(self.data)
        forced_roll_required = diag_positions.is_forced_roll_required(instrument_code)

        return forced_roll_required
Example #14
0
def get_old_strategy_positions(data: dataBlob, old_strategy: str):
    diag_positions = diagPositions(data)
    old_positions = diag_positions.get_dict_of_actual_positions_for_strategy(
        old_strategy)

    return old_positions
def get_required_contract_trade_for_instrument(
    data: dataBlob, instrument_order: instrumentOrder
) -> list:
    """
    Return the contract to trade for a given instrument

    Depends on roll status and trade vs position:
     - roll_states = ['No_Roll', 'Passive', 'Force', 'Force_Outright', 'Roll_Adjusted']

    If 'No Roll' then trade current contract
    If 'Passive', and no position in current contract: trade next contract
    If 'Passive', and reducing trade which leaves zero or something in current contract: trade current contract
    If 'Passive', and reducing trade which is larger than current contract position: trade current and next contract
    If 'Passive', and increasing trade: trade next contract
    If 'Force' or 'Force Outright' or 'Roll_Adjusted': don't trade

    :param instrument_order:
    :param data: dataBlog
    :return: tuple: list of child orders: each is a tuple: contract str or missing_contract, trade int
    """
    instrument_code = instrument_order.instrument_code
    log = instrument_order.log_with_attributes(data.log)
    trade = instrument_order.as_single_trade_qty_or_error()
    if trade is missing_order:
        log.critical("Instrument order can't be a spread order")
        return []

    diag_positions = diagPositions(data)

    if diag_positions.is_roll_state_no_roll(instrument_code):
        diag_contracts = dataContracts(data)
        current_contract = diag_contracts.get_priced_contract_id(instrument_code)

        log.msg(
            "No roll, allocating entire order %s to current contract %s"
            % (str(instrument_order), current_contract)
        )
        return [contractIdAndTrade(current_contract, trade)]

    elif diag_positions.is_roll_state_close(instrument_code):
        diag_contracts = dataContracts(data)
        current_contract = diag_contracts.get_priced_contract_id(instrument_code)

        log.msg(
            "Closing roll state, allocating entire order %s to current contract %s"
            % (str(instrument_order), current_contract)
        )
        return [contractIdAndTrade(current_contract, trade)]


    elif diag_positions.is_roll_state_passive(instrument_code):
        # no log as function does it
        list_of_child_contract_dates_and_trades = passive_roll_child_order(
            data=data, instrument_order=instrument_order, trade=trade
        )

        return list_of_child_contract_dates_and_trades

    elif diag_positions.is_type_of_active_rolling_roll_state(instrument_code):
        log.msg(
            "Roll state is active rolling, not going to generate trade for order %s"
            % (str(instrument_order))
        )
        return []

    else:
        log.critical(
            "Roll state %s not understood: can't generate trade for %s"
            % (
                diag_positions.get_name_of_roll_state(instrument_code),
                str(instrument_order),
            )
        )
        return []
Example #16
0
def get_instruments_with_positions(data, strategy_name):
    diag_positions = diagPositions(data)
    instrument_list = diag_positions.get_list_of_instruments_for_strategy_with_position(
        strategy_name)

    return instrument_list
Example #17
0
 def generate_force_roll_orders(self):
     diag_positions = diagPositions(self.data)
     list_of_instruments = diag_positions.get_list_of_instruments_with_current_positions()
     for instrument_code in list_of_instruments:
         self.generate_force_roll_orders_for_instrument(instrument_code)
Example #18
0
def get_list_of_instruments(data):
    diag_positions = diagPositions(data)
    instrument_list = diag_positions.get_list_of_instruments_with_any_position()

    return instrument_list
Example #19
0
 def check_if_forced_roll_required(self, instrument_code):
     diag_positions = diagPositions(self.data)
     return diag_positions.is_forced_roll_required(instrument_code)
Example #20
0
    def get_instruments_with_current_positions(self):
        diag_positions = diagPositions(self.data)
        instrument_list = diag_positions.get_list_of_instruments_with_current_positions(
        )

        return instrument_list
Example #21
0
def get_instruments_with_positions_all_strategies(data):
    diag_positions = diagPositions(data)
    instrument_list = diag_positions.get_list_of_instruments_with_current_positions(
    )
    return instrument_list
Example #22
0
    def get_current_position_for_instrument(self, instrument_code):
        diag_positions = diagPositions(self.data)
        position = diag_positions.get_current_instrument_position_across_strategies(
            instrument_code)

        return position
def passive_roll_child_order(
    data: dataBlob,
    trade: int,
    instrument_order: instrumentOrder,
) -> list:

    log = instrument_order.log_with_attributes(data.log)
    diag_positions = diagPositions(data)
    instrument_code = instrument_order.instrument_code

    diag_contracts = dataContracts(data)
    current_contract = diag_contracts.get_priced_contract_id(instrument_code)
    next_contract = diag_contracts.get_forward_contract_id(instrument_code)

    contract = futuresContract(instrument_code, current_contract)

    position_current_contract = diag_positions.get_position_for_contract(contract)

    # Break out because so darn complicated
    if position_current_contract == 0:
        # Passive roll and no position in the current contract, start trading
        # the next contract
        log.msg(
            "Passive roll handling order %s, no position in current contract, entire trade in next contract %s"
            % (str(instrument_order), next_contract)
        )
        return [contractIdAndTrade(next_contract, trade)]

    # ok still have a position in the current contract
    increasing_trade = sign(trade) == sign(position_current_contract)
    if increasing_trade:
        # Passive roll and increasing trade
        # Do it all in next contract
        log.msg(
            "Passive roll handling order %s, increasing trade, entire trade in next contract %s"
            % (str(instrument_order), next_contract)
        )
        return [contractIdAndTrade(next_contract, trade)]

    # ok a reducing trade
    new_position = position_current_contract + trade
    sign_of_position_is_unchanged = sign(position_current_contract) == sign(
        new_position
    )
    if new_position == 0 or sign_of_position_is_unchanged:
        # A reducing trade that we can do entirely in the current contract
        log.msg(
            "Passive roll handling order %s, reducing trade, entire trade in next contract %s"
            % (str(instrument_order), next_contract)
        )
        return [contractIdAndTrade(current_contract, trade)]

    # OKAY to recap: it's a passive roll, but the trade will be split between
    # current and next
    list_of_child_contract_dates_and_trades = passive_trade_split_over_two_contracts(
        trade=trade,
        current_contract=current_contract,
        next_contract=next_contract,
        position_current_contract=position_current_contract,
    )
    log.msg(
        "Passive roll handling order %s, reducing trade, split trade between contract %s and %s"
        % (str(instrument_order), current_contract, next_contract)
    )

    return list_of_child_contract_dates_and_trades
Example #24
0
def get_list_of_strategies_from_positions(data=arg_not_supplied):
    d = diagPositions(data)
    return d.get_list_of_strategies_with_positions()