基于以下代码example of a simple historical data request和Bloomberg提供的Python API示例,我构建了下面的bdh函数,当从ipython直接调用时,该函数工作正常(请参阅函数定义后的测试行)。
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'])
但是,当我尝试从ipython notebook运行完全相同的示例(请参阅bdh函数定义之后的行)时,我得到以下错误:
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
我的理解是,如果我从本地ipython会话中调用bdh函数,那么连接到Bloomberg所需的选项可以正常工作,但如果从内核笔记本调用bdh启动则错误
希望得到一些帮助,非常感谢。
答案 0 :(得分:2)
当您致电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'])