Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

I recently started using Python so I could interact with the Bloomberg API, and I'm having some trouble storing the data into a Pandas dataframe (or a panel). I can get the output in the command prompt just fine, so that's not an issue.

Could some benevolent users show me how to get this data into Pandas? 

 I believe I'll need to modify mostly around the 'while(True)' loop toward the end of the 'main()' function, but everything I've tried so far has had issues.

Thanks in advance, and I hope this can be of help to anyone using Pandas for finance.

# SimpleHistoryExample.py

import blpapi

from optparse import OptionParser

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("IBM US Equity")

        request.getElement("securities").appendValue("MSFT US Equity")

        request.getElement("fields").appendValue("PX_LAST")

        request.getElement("fields").appendValue("OPEN")

        request.set("periodicityAdjustment", "ACTUAL")

        request.set("periodicitySelection", "DAILY")

        request.set("startDate", "20061227")

        request.set("endDate", "20061231")

        request.set("maxDataPoints", 100)

        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 completly 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..."

1 Answer

0 votes
by (107k points)

https://github.com/bpsmith/tia/blob/master/examples/datamgr.ipynb

You can refer to the above link as it already downloads data as a panda dataframe from Bloomberg. You can download history for multiple tickers in one single call and you can even download some of Bloomberg's reference data.

And you just install it with pip. This link is full of cases but to download historical data is as easy as:

import pandas as pd

import tia.bbg.datamgr as dm

mgr = dm.BbgDataManager()

sids = mgr['MSFT US EQUITY', 'IBM US EQUITY', 'CSCO US EQUITY']

df = sids.get_historical('PX_LAST', '1/1/2014', '11/12/2014')

and df is a pandas dataframe.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...