blp.blp module

class blp.blp.BlpParser(processor_steps: Sequence | None = None, raise_security_errors: bool = True)

Bases: object

A callable class with a default response parsing implementation.

The parse method parses the responses from BlpQuery.get_response into a simplified representation the can easily be collected using collectors in BlpQuery.

Parameters:
  • processor_steps – A list of processors which take in a response and request_data and returns a validated and possibly modified response. Processors are called sequentially at the start of parse()

  • raise_security_errors – If True, raise errors when response contains an INVALID_SECURITY error, otherwise log as a warning. This is ignored if processor_steps is not None.

class blp.blp.BlpQuery(host: str = 'localhost', port: int = 8194, timeout: int = 10000, parser: Callable | None = None, field_column_map: Dict[str, Callable] | None = None, **kwargs)

Bases: BlpSession

bdh(securities: Sequence[str], fields: List[str], start_date: str, end_date: str, overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg historical data request.

Parameters:
  • securities – list of strings of securities

  • fields – list of strings of fields

  • start_date – start date as ‘%Y%m%d’

  • end_date – end date as ‘%Y%m%d’

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A pandas.DataFrame with columns [‘date’, ‘security’, fields[0], …]

bdib(security: str, event_type: str, interval: int, start_datetime: str, end_datetime: str, overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg intraday bar data request.

Parameters:
  • security – Security name

  • event_type – Event type {TRADE, BID, ASK, BEST_BID, BEST_ASK}

  • interval – Length in minutes of bars {1,…1440}

  • start_datetime – UTC datetime as ‘%Y%-m%-dTHH:MM:SS’

  • end_datetime – UTC datetime as ‘%Y-%m-%dTHH:MM:SS’

  • overrides – List of tuples containing the field to override and its value

  • options – Key value pairs to to set in request

Returns: A pandas.DataFrame where columns are [‘time’, open’, ‘high’, ‘low’, ‘close’, ‘volume’, ‘numEvents’, ‘value’] time is UTC and value is the dollar volume (I believe)

bdit(security: str, event_types: Sequence[str], start_datetime: str, end_datetime: str, overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg tick data request.

Parameters:
  • security – Security name

  • event_types – List of event types {TRADE, BID, ASK, BID_BEST, ASK_BEST, BID_YIELD, ASK_YIELD, MID_PRICE, AT_TRADE, BEST_BID}

  • start_datetime – UTC datetime as ‘%Y%-m%-dTHH:MM:SS’

  • end_datetime – UTC datetime as ‘%Y-%m-%dTHH:MM:SS’

  • overrides – List of tuples containing the field to override and its value

  • options – Key value pairs to to set in request

Returns: A pandas.DataFrame where columns are [‘time’, ‘type’, ‘value’, ‘size’], time is in UTC. Certain options may add various columns

Examples

>>> bq = BlpQuery().start() 
>>> df = bq.bdit('USDCAD Curncy', ['TRADE'], '2019-04-23T08:00:00', '2019-04-23T13:00:00') 

Notes: Various options exist to add certain fields, such as (“includeConditionCodes”, True) and (“includeExchangeCodes”, True). See Bloomberg Schema for more info.

bdp(securities: Sequence[str], fields: List[str], overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg reference data point request.

Parameters:
  • securities – list of strings of securities

  • fields – list of strings of fields

  • overrides – list of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A pandas.DataFrame where columns are [‘security’, field[0], …]

bds(security: str, field: str, overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg reference data set request.

Parameters:
  • security – String representing security

  • field – String representing field

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A pandas.DataFrame where columns are data element names

beqs(screen_name: str, screen_type: str = 'PRIVATE', overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg equity screening request.

Parameters:
  • screen_name – name of the screen

  • screen_type – type of screen, either ‘PRIVATE’ or ‘GLOBAL’

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A pandas.DataFrame with columns [‘security’, eqs_data[0], …]

bql(expression: str, overrides: Sequence | None = None, options: Dict | None = None) DataFrame

Bloomberg query language request.

Parameters:
  • expression – BQL expression

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A pandas.DataFrame with columns [“security”, “field”, “secondary_name”, “secondary_value”, “value”]

Examples

>>> bquery = blp.BlpQuery().start() 
>>> bquery.bql(expression="get(px_last()) for(['AAPL US Equity', 'IBM US Equity'])") 
The resulting DataFrame will look like this:

security field secondary_name secondary_value value

0 AAPL US Equity px_last() CURRENCY USD 192.755005 1 IBM US Equity px_last() CURRENCY USD 139.289993 2 AAPL US Equity px_last() DATE 2023-07-24T00:00:00Z 192.755005 3 IBM US Equity px_last() DATE 2023-07-24T00:00:00Z 139.289993

cast_columns(df: DataFrame, fields: Iterable) DataFrame
collect_many_to_bds(responses) Dict

Collector to nested dictionary of DataFrames.

Top level keys are securities, next level keys are fields and values are DataFrame in bds() form

collect_to_bdh(responses: Iterable) Dict[str, DataFrame]

Collector for bdh().

collect_to_bdib(responses: Iterable) Dict

Collector for bdib().

collect_to_bdit(responses: Iterable) Dict

Collector for bdit().

collect_to_bdp(responses: Iterable) DataFrame

Collector for bdp().

collect_to_bds(responses: Iterable) DataFrame

Collector for bds().

collect_to_beqs(responses: Iterable) DataFrame

Collector for beqs().

collect_to_bql(responses: Iterable) DataFrame

Collector for bql().

create_request(request_data: Dict) Request

Create a blpapi.Request.

Parameters:

request_data – A dictionary representing a blpapi.Request, specifying both the service and the data

Returns: blpapi.Request

Examples

>>> bq = BlpQuery().start() 
>>> bq.create_request({
...  'HistoricalDataRequest': {
...    'securities': ['CL1 Comdty'],
...    'fields': ['PX_LAST'],
...    'startDate': '20190102',
...    'endDate': '20190102'
...   }
... }) 
get_response(data_queue: EventQueue, timeout: int | None = None) Generator

Yield dictionary representation of blpapi.Messages from a blpapi.EventQueue.

Parameters:
  • data_queue – Queue which contains response

  • timeout – Milliseconds to wait for service before the blpapi.EventQueue returns a blpapi.Event.TIMEOUT

Returns: A generator of messages translated into a dictionary representation

query(request_data: Dict, parse: Callable | None = None, collector: Callable | None = None, timeout: int | None = None)

Request and parse Bloomberg data.

Parameters:
  • request_data – A dictionary representing a blpapi.Request, specifying both the service and the data

  • parse – Callable which takes a dictionary response and request and yields 0 or more values. If None, use default parser. If False, do not parse the response

  • collector – Callable which takes an iterable

  • timeout – Milliseconds to wait for service before the blpapi.EventQueue returns a blpapi.Event.TIMEOUT

Returns: A result from collector, if collector=None default is a itertools.chain

Examples

>>> bq = BlpQuery().start() 

A historical data request collected into a list

>>> rd = {
...  'HistoricalDataRequest': {
...    'securities': ['CL1 Comdty'],
...    'fields': ['PX_LAST'],
...    'startDate': '20190102',
...    'endDate': '20190102'
...   }
... }
>>> bq.query(rd, collector=list) 
[
 {
  'security':'CL1 Comdty',
  'fields':['PX_LAST'],
  'data':[{'date': Timestamp('2019-01-02 00:00:00'), 'PX_LAST':46.54}]
 }
]

A historical data request with no parsing collected into a list

>>> bq.query(rd, collector=list, parse=False) 
[
   {
      'eventType':5,
      'eventTypeName':'blpapi.Event.RESPONSE',
      'messageNumber':0,
      'message':{
         'fragmentType':0,
         'correlationIds':[8],
         'messageType':'HistoricalDataResponse',
         'topicName':'',
         'timeReceived':None,
         'element':{
            'HistoricalDataResponse':{
               'securityData':{
                  'security':'CL1 Comdty',
                  'eidData':[],
                  'sequenceNumber':0,
                  'fieldExceptions':[],
                  'fieldData':[{'fieldData':{'date': Timestamp('2019-01-02 00:00:00'),'PX_LAST':46.54}}]
               }
            }
         }
      }
   }
]
send_request(request: Request, data_queue: EventQueue, correlation_id: CorrelationId | None = None) CorrelationId

Send a request who’s data will be populated into data_queue.

Parameters:
  • request – Request to send

  • data_queue – Queue which response populates

  • correlation_id – Id associated with request/response

Returns: blpapi.CorrelationId associated with the request

start()

Start the blpapi.Session and open relevant services.

stop()
class blp.blp.BlpSession(event_handler: Callable | None, host: str, port: int, app: str | None = None, **kwargs)

Bases: object

authenticate(timeout: int = 0) None

Authenticate the blpapi.Session.

Parameters:

timeout – Milliseconds to wait for service before the blpapi.EventQueue returns a blpapi.Event.TIMEOUT

static create_session_options(host: str, port: int, app: str | None = None, **kwargs) SessionOptions

Create blpapi.SessionOptions class used in blpapi.Session.

Parameters:
  • host – Host to connect session on

  • port – Port to connection session to

  • app – The app to use for the session identity

  • **kwargs – Keyword args passed to the blpapi.SessionOpts, if authentication is needed use setAuthenticationOptions

Returns: A blpapi.SessionOptions

class blp.blp.BlpStream(host: str = 'localhost', port: int = 8194, **kwargs)

Bases: BlpSession

static dict_to_sub(sub: Dict, use_topic: bool = True) SubscriptionList

Convert dictionary to blpapi.SubscriptionList.

Parameters:
  • sub – A dictionary containing topics (Bloomberg securities) with nested dictionaries containg optional keys ‘fields’, ‘options’, ‘correlationID’.

  • use_topic (boolean) – Indicate whether to use the topic as the correlationID if None (otherwise will be Bloomberg automatically generated)

Returns: A blpapi.SubscriptionList

event_handler: EventHandler
events(timeout: int | None = None) Generator

Generator of events.

Parameters:

timeout – Seconds before getting result from the queue.Queue returns a queue.Empty exception

Returns: A generator of events

Examples

>>> bs = BlpStream()
>>> events = []
>>> with bs: 
...   subs = bs.subscribe({'USDCAD Curncy': {'fields': ['LAST_PRICE']}})
...   for ev in bs.events():
...       events.append(ev)
...       if len(events) > 2: break
resubscribe(sub: Dict, timeout: int = 5) Dict

Resubscribe to all instruments.

Parameters:
  • sub – Dictionary used to build a blpapi.SubscriptionList of subscriptions

  • timeout – Seconds before getting result from the queue.Queue returns a queue.Empty exception

Returns: A dictionary where the key is the blpapi.correlationId value and the value is True if successful, False if there was an error and a list of invalid fields if there are exceptions

Notes: The documentation indicates that resubscribing to instruments with invalid correlationIds will be ignored however this does not seem to work in practice. All current activate subscriptions must be resubscribed to. This may be a quirk of DAPI.

subscribe(sub: Dict, timeout: int = 5) Dict

Subscribe to instruments.

Parameters:
  • sub – Dictionary used to build a blpapi.SubscriptionList of subscriptions

  • timeout – Seconds before getting result from the queue.Queue returns a queue.Empty exception

Returns: A dictionary where the key is the blpapi.correlationId value and the value is True if successful, False if there was an error and a list of invalid fields if there are exceptions

Examples

>>> bs = BlpStream()
>>> with bs: 
...     bs.subscribe(
...       {
...          'USDCAD Curncy': {'fields': ['LAST_PRICE']},
...          'EURUSD Curncy': {'fields': ['LAST_PRICE', 'BAD_FIELD']},
...          'BAD_TICKER': {'fields': ['LAST_PRICE']}
...       }
...     )
 {'USDCAD Curncy': True, 'EURUSD Curncy': ['BAD_FIELD'], 'BAD_TICKER': False}
unsubscribe(sub: Dict, timeout: int = 5) Dict

Unsubscribe from all instruments.

Parameters:
  • sub – Dictionary used to build a blpapi.SubscriptionList of subscriptions

  • timeout – Seconds before getting result from the queue.Queue returns a queue.Empty exception

Notes: The documentation is somewhat ambiguous but the docs suggest you can unsubscribe from only some subscriptions however this does not seem to work in practice. This may be a quirk of DAPI.

class blp.blp.EventHandler

Bases: object

A default implementation of an eventHandler used in blpapi.Session.

marketdata_event(event)
classmethod other_event(event)
static other_message(event_name, n, msg)
session_status_event(event)
subscription_status_event(event)
blp.blp.create_bql_query(expression: str, overrides: Sequence | None = None, options: Dict | None = None) Dict

Create a sendQuery dictionary request.

Parameters:

expression – BQL query string

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_eqs_query(screen_name: str, screen_type: str = 'PRIVATE', overrides: Sequence | None = None, options: Dict | None = None) Dict

Create a BeqsRequest dictionary request.

Parameters:
  • screen_name – name of the screen

  • screen_type – type of screen; either PRIVATE or GLOBAL

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_field_list_query(field_type: str | None = None, field_documentation: bool = True) Dict

Create a FieldListRequest dictionary request.

Parameters:
  • field_type – One of {‘All’, ‘Static’, ‘RealTime’}

  • field_documentation – Return field documentation

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_fills_query(start_datetime: str, end_datetime: str, uuids: Sequence[str]) Dict

Create a GetFills dictionary request.

Parameters:
  • start_datetime – UTC datetime as ‘%Y%-m%-dTHH:MM:SS’

  • end_datetime – UTC datetime as ‘%Y-%m-%dTHH:MM:SS’

  • uuids – List of user uuids to get fills associated with

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_historical_query(securities: str | Sequence[str], fields: str | Sequence[str], start_date: str, end_date: str, overrides: Sequence | None = None, options: Dict | None = None) Dict

Create a HistoricalDataRequest dictionary request.

Parameters:
  • securities – list of strings of securities

  • fields – list of strings of fields

  • start_date – start date as ‘%Y%m%d’

  • end_date – end date as ‘%Y%m%d’

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_instrument_list_query(values: Dict | None = None) Dict

Create an instrumentListRequest dictionary request.

Parameters:

values – Values to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_intraday_bar_query(security: str, event_type: str, interval: int, start_datetime: str, end_datetime: str, overrides: Sequence | None = None, options: Dict | None = None) Dict

Create an IntradayBarRequest dictionary request.

Parameters:
  • security – Security name

  • event_type – Event type {TRADE, BID, ASK, BEST_BID, BEST_ASK}

  • interval – Length in minutes of bars {1,…1440}

  • start_datetime – UTC datetime as ‘%Y%-m%-dTHH:MM:SS’

  • end_datetime – UTC datetime as ‘%Y-%m-%dTHH:MM:SS’

  • overrides – List of tuples containing the field to override and its value

  • options – Key value pairs to to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_intraday_tick_query(security: str, event_types: Sequence[str], start_datetime: str, end_datetime: str, overrides: Sequence | None = None, options: Dict | None = None) Dict

Create an IntradayTickRequest.

Parameters:
  • security – Security name

  • event_types – List of event types {TRADE, BID, ASK, BID_BEST, ASK_BEST, BID_YIELD, ASK_YIELD, MID_PRICE, AT_TRADE, BEST_BID}

  • start_datetime – UTC datetime as ‘%Y%-m%-dTHH:MM:SS’

  • end_datetime – UTC datetime as ‘%Y-%m-%dTHH:MM:SS’

  • overrides – List of tuples containing the field to override and its value

  • options – Key value pairs to to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.create_query(request_type: str, values: Dict, overrides: Sequence | None = None) Dict

Create a request dictionary used to construct a blpapi.Request.

Parameters:
  • request_type – Type of request

  • values – key value pairs to set in the request

  • overrides – List of tuples containing the field to override and its value

Returns: A dictionary representation of a blpapi.Request

Examples

Reference data request

>>> create_query(
...   'ReferenceDataRequest',
...   {'securities': ['CL1 Comdty', 'CO1 Comdty'], 'fields': ['PX_LAST']}
... )
{'ReferenceDataRequest': {'securities': ['CL1 Comdty', 'CO1 Comdty'], 'fields': ['PX_LAST']}}

Reference data request with overrides

>>> create_query(
...   'ReferenceDataRequest',
...   {'securities': ['AUD Curncy'], 'fields': ['SETTLE_DT']},
...   [('REFERENCE_DATE', '20180101')]
... )  # noqa: E501
{'ReferenceDataRequest': {'securities': ['AUD Curncy'], 'fields': ['SETTLE_DT'], 'overrides': [{'overrides': {'fieldId': 'REFERENCE_DATE', 'value': '20180101'}}]}}

Historical data request

>>> create_query(
...   'HistoricalDataRequest',
...   {
...    'securities': ['CL1 Comdty'],
...    'fields': ['PX_LAST', 'VOLUME'],
...    'startDate': '20190101',
...    'endDate': '20190110'
...   }
... )  # noqa: E501
{'HistoricalDataRequest': {'securities': ['CL1 Comdty'], 'fields': ['PX_LAST', 'VOLUME'], 'startDate': '20190101', 'endDate': '20190110'}}
blp.blp.create_reference_query(securities: str | Sequence[str], fields: str | Sequence[str], overrides: Sequence | None = None, options: Dict | None = None) Dict

Create a ReferenceDataRequest dictionary request.

Parameters:
  • securities – list of strings of securities

  • fields – list of strings of fields

  • overrides – List of tuples containing the field to override and its value

  • options – key value pairs to to set in request

Returns: A dictionary representation of a blpapi.Request

blp.blp.datetime_converter(value: str | date | datetime) Timestamp
blp.blp.dict_to_req(request: Request, request_data: Dict) Request

Populate request with data from request_data.

Parameters:
  • request – Request to populate

  • request_data – Data used for populating the request

Returns: A blpapi.Request

Notes: An example request data dictionary is

rdata = {‘fields’: [‘SETTLE_DT’], ‘securities’: [‘AUD Curncy’],

‘overrides’: [{‘overrides’: {‘fieldId’: ‘REFERENCE_DATE’, ‘value’: ‘20180101’}}]}

blp.blp.element_to_dict(elem: Element) Dict

Convert a blpapi.Element to an equivalent dictionary representation.

Parameters:

elem – A blpapi.Element

Returns: A dictionary representation of blpapi.Element

blp.blp.element_to_value(elem: Element) Timestamp | str | Number | None

Convert a blpapi.Element to its value defined in its datatype with some possible coercisions.

datetime.datetime -> pandas.Timestamp datetime.date -> pandas.Timestamp blp.name.Name -> str null value -> None ValueError Exception -> None

Parameters:

elem – Element to convert

Returns: A value

blp.blp.message_to_dict(msg: Message) Dict

Convert a blpapi.Message to a dictionary representation.

Parameters:

msg – A blpapi.Message

Returns: A dictionary with relevant message metadata and data