Search code examples
pythonbloomberg

Python / Bloomberg API: Return single query as int


Disclaimer: New to Python and Bloomberg API.

I am trying to query a single data point for a security using Python - not using any other modules due to 3rd party module constraints.

I have taken BBG's SimpleHistoryExample and edited to my needs. Now I just need to find a way to return the value of PX_LAST only.

# SimpleHistoryExample.py
from __future__ import print_function
from __future__ import absolute_import

import blpapi
from optparse import OptionParser
prevMonthEnd = "20191031"

def parseCmdLine():
    parser = OptionParser(description="Retrieve reference data.")
    parser.add_option("-a",
                      "--ip",
                      dest="host",
                      help="server name or IP (default: %default)",
                      metavar="ipAddress",
                      default="localhost")
    parser.add_option("-p",
                      dest="port",
                      type="int",
                      help="server port (default: %default)",
                      metavar="tcpPort",
                      default=8194)

    (options, args) = parser.parse_args()

    return options


def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost(options.host)
    sessionOptions.setServerPort(options.port)

    print("Connecting to %s:%s" % (options.host, options.port))
    # Create a Session
    session = blpapi.Session(sessionOptions)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    try:
        # Open service to get historical data from
        if not session.openService("//blp/refdata"):
            print("Failed to open //blp/refdata")
            return

        # Obtain previously opened service
        refDataService = session.getService("//blp/refdata")

        # Create and fill the request for the historical data
        request = refDataService.createRequest("HistoricalDataRequest")
        request.getElement("securities").appendValue("EURUSD Curncy")
        request.getElement("fields").appendValue("PX_LAST")
        request.set("periodicityAdjustment", "ACTUAL")
        request.set("periodicitySelection", "DAILY")
        request.set("startDate", "20191130")
        request.set("endDate", "20191130")
        request.set("maxDataPoints", 1000)

        print("Sending Request:", request)
        # Send the request
        session.sendRequest(request)

        # Process received events
        while(True):
            # We provide timeout to give the chance for Ctrl+C handling:
            ev = session.nextEvent(500)
            for msg in ev:
                print(msg)

            if ev.eventType() == blpapi.Event.RESPONSE:
                # Response completely received, so we could exit
                break
    finally:
        # Stop the session
        session.stop()

if __name__ == "__main__":
    print("SimpleHistoryExample")
    try:
        main()
    except KeyboardInterrupt:
        print("Ctrl+C pressed. Stopping...")

Solution

  • You have a historical data request, which in most cases means you're requesting multiple days, so you'll have to deal with that and how you want the format for each day. In this case you're requesting just one day, so let's talk about that.

    First off, don't pick a weekend. You need a day where data is expected to exist. Try the day before. The raw response looks like:

    HistoricalDataResponse = {
        securityData = {
            security = "EURUSD Curncy"
            eidData[] = {
            }
            sequenceNumber = 0
            fieldExceptions[] = {
            }
            fieldData[] = {
                fieldData = {
                    date = 2019-11-29
                    PX_LAST = 1.101800
                }
            }
        }
    }
    

    For each of those, the blpapi data structures can be accessed. Ultimately, it's up to you to decide how you want to structure it.

    Don't use this as is, because it's flawed, but here is an example of getting the data. This is putting it into a dict for a single date, focusing on your response section that you have in the question above:

    # inside your existing while loop above
    if ev.eventType() == blpapi.Event.RESPONSE:
        response = {}
        sec_data = msg.getElement("securityData")
        field_data = sec_data.getElement("fieldData")
        for individual_date_quote in field_data.values():
            for elem in individual_date_quote.elements():
                response[str(elem.name())] = elem.getValueAsString()
        print("response dict:", response)
        # Response completely received, so we could exit
        break
    

    Which will give you:

    response dict: {'date': '2019-11-29', 'PX_LAST': '1.101800'}
    

    You'll also want to consider ev.eventType() == blpapi.Event.PARTIAL_RESPONSE, and also how to handle multiple securities and multiple dates per security. Take a look at {WAPI} for the full documentation, but hopefully this gives you a better idea of how to get started.