Python Bloomberg API not connecting from ipython laptop

based on the following code, an example of a simple request for historical data and an example of the Python API provided by Bloomberg I built a bdh function, below which it works fine when called directly from ipython (see the test lines after defining the function).

import blpapi
import pandas as pd
import datetime as dt
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 bdh(secList, fieldList,startDate,endDate=dt.date.today().strftime('%Y%m%d'),periodicity='Daily'):
""" Sends a historical request to Bloomberg.
Returns a panda.Panel object.
"""

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 requestuest for the historical data
    request = refDataService.createRequest("HistoricalDataRequest")
    for s in secList:
        request.getElement("securities").appendValue(s)
    for f in fieldList:
        request.getElement("fields").appendValue(f)
    request.set("periodicityAdjustment", "ACTUAL")
    request.set("periodicitySelection", "DAILY")
    request.set("startDate", startDate)
    request.set("endDate", endDate)

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

    # Process received events
    response={}
    while(True):
        # We provide timeout to give the chance for Ctrl+C handling:
        ev = session.nextEvent(500)
        if ev.eventType() == blpapi.Event.RESPONSE or ev.eventType() == blpapi.Event.PARTIAL_RESPONSE:
            for msg in ev:
                secData = msg.getElement('securityData')
                name = secData.getElement('security').getValue()
                response[name] = {}
                fieldData = secData.getElement('fieldData')
                for i in range(fieldData.numValues()):
                    fields = fieldData.getValue(i)
                    for n in range(1, fields.numElements()):
                        date = fields.getElement(0).getValue()
                        field = fields.getElement(n)
                    try:
                        response[name][field.name()][date] = field.getValue()
                    except KeyError:
                        response[name][field.name()] = {}
                        response[name][field.name()][date] = field.getValue()


        if ev.eventType() == blpapi.Event.RESPONSE:
            # Response completly received, so we could exit
            break

    #converting the response to a panda pbject
    tempdict = {}
    for r in response:
        td = {}
        for f in response[r]:
            td[f] = pd.Series(response[r][f])

        tempdict[r] = pd.DataFrame(td)
        data = pd.Panel(tempdict)


finally:
    # Stop the session
    session.stop()
    return(data)
#------------------------------------------------------------
secList = ['SP1 Index', 'GC1 Comdty']
fieldList = ['PX_LAST']
beg = (dt.date.today() - dt.timedelta(30)).strftime('%Y%m%d')
testData = bdh.bdh(secList,fieldList,beg)
testData = testData.swapaxes('items','minor')
print(testData['PX_LAST'])

However, when I try to run the exact same example (see the lines after defining the bdh function) from the ipython laptop, I get the following error:

    SystemExit                                Traceback (most recent call last)
<ipython-input-6-ad6708eabe39> in <module>()
----> 1 testData = bbg.bdh(tickers,fields,begin)
      2 #testData = testData.swapaxes('items','minor')
      3 #print(testData['PX_LAST'])

C:\Python27\bbg.py in bdh(secList, fieldList, startDate, endDate, periodicity)
     33     """
     34 
---> 35     options = parseCmdLine()
     36 
     37     # Fill SessionOptions

C:\Python27\bbg.py in parseCmdLine()
     24                       default=8194) 
     25 
---> 26     (options, args) = parser.parse_args()
     27 
     28     return options

C:\Python27\lib\optparse.pyc in parse_args(self, args, values)
   1400             stop = self._process_args(largs, rargs, values)
   1401         except (BadOptionError, OptionValueError), err:
-> 1402             self.error(str(err))
   1403 
   1404         args = largs + rargs

C:\Python27\lib\optparse.pyc in error(self, msg)
   1582         """
   1583         self.print_usage(sys.stderr)
-> 1584         self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
   1585 
   1586     def get_usage(self):

C:\Python27\lib\optparse.pyc in exit(self, status, msg)
   1572         if msg:
   1573             sys.stderr.write(msg)
-> 1574         sys.exit(status)
   1575 
   1576     def error(self, msg):

SystemExit: 2

I understand that the parameters necessary to connect to Bloomberg work fine if I call the bdh function from a local ipython session, but I am mistaken if bdh is called from the kernel initializer.

Hope to get help, thanks in advance.

+4
1

parseCmdLine(), sys.argv, , , , .

?

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 bdh(secList, fieldList,startDate,endDate=dt.date.today().strftime('%Y%m%d'),periodicity='Daily', host='localhost', port=8194):
""" Sends a historical request to Bloomberg.
Returns a panda.Panel object.
"""

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

...

if __name__ == '__main__':
    options = parseCmdLine()

    secList = ['SP1 Index', 'GC1 Comdty']
    fieldList = ['PX_LAST']
    beg = (dt.date.today() - dt.timedelta(30)).strftime('%Y%m%d')
    testData = bdh.bdh(secList,fieldList,beg, host=options.host, port=options.port)
    testData = testData.swapaxes('items','minor')
    print(testData['PX_LAST'])
+2

All Articles