我最近开始使用 Python,以便可以与 Bloomberg API 进行交互,但在将数据存储到 Pandas 数据框(或面板)中时遇到了一些麻烦。我可以很好地在命令提示符下获得输出,所以这不是问题。
这里提出了一个非常相似的问题: Pandas wrapper for Bloomberg api?
但是,该问题的已接受答案中的引用代码适用于旧 API,不适用于新的开放 API。显然,提出这个问题的用户能够轻松地修改该代码以使用新的 API,但我习惯于将手握在 R 中,这是我第一次尝试使用 Python。
一些仁慈的用户可以告诉我如何将这些数据输入 Pandas 吗?Python API(可在此处获得:http ://www.openbloomberg.com/open-api/ )中有一个名为 SimpleHistoryExample.py 的示例,我一直在使用它,我已将其包含在下面。我相信我需要在'main()'函数结束时主要围绕'while(True)'循环进行修改,但到目前为止我尝试的一切都有问题。
在此先感谢,我希望这对使用 Pandas 进行金融的任何人都有帮助。
# 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..."