Python Bloomberg API not connecting from ipython notebook

Martin Dudler

based on following code example of a simple historical data request and the Python API example provided by Bloomberg I constructed the bdh function below which works fine when directly called from ipython (see the testing lines after the function definition).

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 exactly the same example (see the lines after the bdh function definition) from ipython notebook, then I get 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

My understanding is that the options needed to connect to Bloomberg work fine if I call the bdh function from a local ipython session but are wrong if bdh is called from the kernel notebook initiates???

Hope to get some help, thanks a lot in advance.

Alex Chamberlain

When you call parseCmdLine(), it looks at sys.argv, which is probably not what you're expecting.

What about this?

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'])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python Bloomberg API not connecting from ipython notebook

From Dev

Execute IPython notebook cell from python script

From Dev

IPython notebook connecting to wrong tcp address

From Dev

Converting to (not from) ipython Notebook format

From Dev

Connecting IPython notebook to spark master running in different machines

From Dev

Python 2.7 with Bloomberg API import blpapi failure

From Dev

Bloomberg Api for Python: Parts of result missing in response

From Dev

How can I start Bloomberg API in python?

From Dev

Launching ipython notebook via the api (script)

From Dev

Connecting to a Windows IPython kernel from Linux

From Dev

Connecting to a Windows IPython kernel from Linux

From Dev

Ipython notebook - Create a new notebook (Python conda or default Python)

From Dev

Run ipython notebook from a remote server

From Dev

Install new package from inside ipython Notebook

From Dev

can not start ipython notebook from anaconda

From Dev

Get Output From the logging Module in IPython Notebook

From Dev

Matplotlib: Save figure as file from iPython notebook

From Dev

ipython notebook output from child process

From Dev

Sending data from a web app to an ipython notebook

From Dev

Display SVG in IPython notebook from a function

From Dev

IPython Notebook - early exit from cell

From Dev

Locally save data from remote iPython notebook

From Dev

Load iPython/Jupyter Notebook from URL

From Dev

Python dictionary as html table in ipython notebook

From Dev

Ipython Notebook: Default Initialization Python Code

From Dev

ipython notebook R cell magic as a python function

From Dev

IPython Notebook in a virtualenv, using Python 3.3

From Dev

Anaconda: Python 3 and 2 in IPython/Jupyter Notebook

From Dev

iPython/Jupyter Notebook: How to Embed Interactive Graph Using Desmos API?

Related Related

  1. 1

    Python Bloomberg API not connecting from ipython notebook

  2. 2

    Execute IPython notebook cell from python script

  3. 3

    IPython notebook connecting to wrong tcp address

  4. 4

    Converting to (not from) ipython Notebook format

  5. 5

    Connecting IPython notebook to spark master running in different machines

  6. 6

    Python 2.7 with Bloomberg API import blpapi failure

  7. 7

    Bloomberg Api for Python: Parts of result missing in response

  8. 8

    How can I start Bloomberg API in python?

  9. 9

    Launching ipython notebook via the api (script)

  10. 10

    Connecting to a Windows IPython kernel from Linux

  11. 11

    Connecting to a Windows IPython kernel from Linux

  12. 12

    Ipython notebook - Create a new notebook (Python conda or default Python)

  13. 13

    Run ipython notebook from a remote server

  14. 14

    Install new package from inside ipython Notebook

  15. 15

    can not start ipython notebook from anaconda

  16. 16

    Get Output From the logging Module in IPython Notebook

  17. 17

    Matplotlib: Save figure as file from iPython notebook

  18. 18

    ipython notebook output from child process

  19. 19

    Sending data from a web app to an ipython notebook

  20. 20

    Display SVG in IPython notebook from a function

  21. 21

    IPython Notebook - early exit from cell

  22. 22

    Locally save data from remote iPython notebook

  23. 23

    Load iPython/Jupyter Notebook from URL

  24. 24

    Python dictionary as html table in ipython notebook

  25. 25

    Ipython Notebook: Default Initialization Python Code

  26. 26

    ipython notebook R cell magic as a python function

  27. 27

    IPython Notebook in a virtualenv, using Python 3.3

  28. 28

    Anaconda: Python 3 and 2 in IPython/Jupyter Notebook

  29. 29

    iPython/Jupyter Notebook: How to Embed Interactive Graph Using Desmos API?

HotTag

Archive