Esempio n. 1
0
def get_multidata_bbg(requests):
    """function for multiple asynchronous refdata requests, returns a
    dictionary of the form correlationID:result.

    Function Parameters
    ----------
    requests : dictionary of correlationID:request pairs. CorrelationIDs
        are unique integers (cannot reuse until previous requests have
        returned). Requests can be either dicts of named arguments or
        list-likes of ordered arguments. Although technically anything
        can be made into a blpapi.CorrelationId, integers simplify usage.

    Request Parameters
    ----------
    identifiers : list-like object of bloomberg identifiers of the form
        'symbol [exchange] <yellow key>'. Symbol can be ticker/name/
        cusip/etc.

    fields : list-like object of bloomberg field mnemonics or CALCRT ID.
        Although either can be input, only the mnemonic will be output.

    overrides : list-like object of tuples or dictionary. Tuples must be of
        the form [(fieldId, value), ], while dictionaries are
        {fieldId: value, }.
        FieldId(s) are mnemonics or CALCRT IDs, values will be converted
        to the proper type if possible.
    """
    with bs.Session() as session:
        try:
            if not isinstance(requests, dict):
                raise be.InputError('request_mult_refdata requires a '
                                    'dictionary of correlationId:input pairs')
            for corr_id, req in requests.items():
                if isinstance(req, dict):
                    inputs = req
                elif hasattr(req, '__iter__'):
                    if len(req) == 3:
                        pass
                    elif len(req) == 2:
                        req = list(req)
                        req.append(None)
                    else:
                        raise be.InputError('Request {0} has {1} items'
                                            ', expected 2-3.'.format(
                                                corr_id, len(req)))
                    inputs = dict(zip((IDS, FLDS, OVDS), req))
                else:
                    raise be.InputError('Request {0} is of type: {0}, '
                                        'expected dict or list-like'.format(
                                            corr_id, type(req)))
                _ref_req_queue(session, corr_id, inputs)
        except be.InputError as err:
            print err
        _refdata_to_bloomberg(session)
        session.queue.join()
        rtn = session.correlation_ids
    return rtn
Esempio n. 2
0
def _append_value(element, values, err_msg=''):
    """append values to request"""
    try:
        map(element.appendValue, values)
    except Exception as err:
        print err
        raise be.InputError(err_msg)
Esempio n. 3
0
def _add_calendar_overrides(request, ovds_lst=(), ovds_op='CDR_AND'):
    """"append calendar overrides to historical request"""
    try:
        if ovds_lst:
            cdr_ovds_info = request.getElement(bn.CAL_OVDS_INFO)
            cdr_ovds_info.setElement(bn.CAL_OVDS_OP, ovds_op)
            cdr_ovds = cdr_ovds_info.getElement(bn.CAL_OVDS)
            for ovd in ovds_lst:
                cdr_ovds.appendValue(ovd)
    except Exception as err:
        print err
        raise be.InputError("Error with Calendar Override input values")
Esempio n. 4
0
def _append_overrides(ovds_elem, overrides):
    """append overrides to request"""
    def _add_ovd(ovd_tuple):
        """append override to overrides"""
        ovd = ovds_elem.appendElement()
        ovd.setElement(bn.FLD_ID, ovd_tuple.fieldId)
        ovd.setElement(bn.VAL, ovd_tuple.value)

    try:
        if overrides is not None:
            map(_add_ovd, overrides)
    except Exception as err:
        print err
        raise be.InputError("Error with Override input values")
Esempio n. 5
0
def get_sensitivity_bbg(identifier,
                        dependent,
                        independents,
                        values,
                        overrides=None):
    """function for calculating sensitivities on a dependent field.
    Returns a pandas DataFrame of results.

    Parameters
    ----------
    identifier : bloomberg identifier of the form symbol [exchange]
        <yellow key>'. Symbol can be ticker/name/cusip/etc.

    dependent : bloomberg field mnemonics or CALCRT ID. This is the
        field for which you want results

    independents : list-like object of bloomberg field mnemonics or
        CALCRT ID.  These are the fields you would like to override.
        Function supports 1-3 independent variables.

    values : list-like object of list-likes containing the override
        values for the independent fields. Must have the same number
        of list-likes as there are independents.

    overrides : list-like object of tuples or dictionary. Tuples must
        be of the form [(fieldId, value), ], while dictionaries are
        {fieldId: value, }. FieldId(s) are mnemonics or CALCRT IDs,
        values will be converted to the proper type if possible. If
        an independent field is also included in the overrides list,
        the override will be ignored.

    Examples
    --------
    >>> import numpy as np
    >>> sec = 'CT10 Govt'
    >>> dep = 'YLD_CNV_BID'
    >>> inds = ['PX_BID', 'SETTLE_DT']
    >>> px = get_data_bbg(sec, 'PX_LAST')
    >>> pxs = px * np.arange(0.9,1.1,0.05)
    >>> settle = get_data_bbg(sec, 'SETTLE_DT')
    >>> settles = [settle, settle + datetime.timedelta(30)]
    >>> vals = [pxs, settles]
    >>> data = get_sensitivity_bbg(sec, dep, inds, vals)
    """
    try:
        if not isinstance(identifier, str):
            raise be.InputError('Expected a single bloomberg identifier of '
                                'string type, got {0}'.format(
                                    type(identifier)))
        if not isinstance(dependent, str):
            raise be.InputError('Expected a single bloomberg field of '
                                'string type for dependent, got {0}'.format(
                                    type(identifier)))
        if (not hasattr(independents, '__iter__')
                and not all(isinstance(x, str) for x in independents)):
            raise be.InputError('Expected a list-like of  bloomberg fields of '
                                'string type for independents, got {0}'.format(
                                    [type(x) for x in identifier]))
        if not all(hasattr(val, '__iter__') for val in values):
            raise be.InputError('Expected a list-like of override values for '
                                'values, got {0}'.format(type(values)))
        if not len(independents) == len(values):
            raise be.InputError('Must have the same number of independents '
                                'and list-likes of values')
        try:
            ovds_base = {
                key.replace(' ', '_').upper(): val
                for key, val in dict(overrides).items()
            }
        except TypeError:
            raise be.InputError('overrides must be convertible to a dict')
    except be.InputError as err:
        print err
    sec_id = identifier.upper()
    fld = dependent.upper()
    flds = list(_sorted_unq_tuple([fld, 'NAME'] + list(independents)))
    #Create a list of dicts with all the combinations of independent/value
    #override pairs. These dicts are then used to update the base override.
    if len(independents) > 1:
        inds = [[ind.replace(' ', '_').upper()] for ind in independents]
    scens = [dict(x) for x in product(*map(product, inds, values))]

    #Create the requests dictionary for input into get_multidata_bbg
    reqs = {}
    for i, scen in enumerate(scens):
        ovds = ovds_base.copy()
        ovds.update(scen)
        reqs[i] = {IDS: sec_id, FLDS: flds, OVDS: ovds}
    results = get_multidata_bbg(reqs)
    # rtn_arr = []
    rtn_df = []
    for x in xrange(len(scens)):
        ovds = {
            ovd[0].replace(' ', '_').upper(): ovd[1]
            for ovd in reqs[x][OVDS]
        }
        res = results[x][sec_id]
        # rtn_arr.append(res[fld])
        res.update(ovds)
        rtn_df.append(res)
    rtn_df = pd.DataFrame(rtn_df)
    # rtn_df = [x.update(reqs[i].update({CUSIP:sec_id})) for
    #           i, x in enumerate(rtn_df)]
    # rtn_df = pd.DataFrame(rtn_df)

    # arr_sz = [len(x) for x in values]
    # rtn_arr = shape_list(rtn_arr, arr_sz)

    return rtn_df