Python / Bloomberg API: Return 单个查询作为 int

Python / Bloomberg API: Return single query as int

免责声明:Python 和 Bloomberg API 的新手。

我正在尝试使用 Python 查询单个数据点的安全性 - 由于第 3 方模块限制,未使用任何其他模块。

我使用了 BBG 的 SimpleHistoryExample 并根据我的需要进行了编辑。现在我只需要找到一种方法来 return 的值 PX_LAST 而已。

# SimpleHistoryExample.py
from __future__ import print_function
from __future__ import absolute_import

import blpapi
from optparse import OptionParser
prevMonthEnd = "20191031"

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("EURUSD Curncy")
        request.getElement("fields").appendValue("PX_LAST")
        request.set("periodicityAdjustment", "ACTUAL")
        request.set("periodicitySelection", "DAILY")
        request.set("startDate", "20191130")
        request.set("endDate", "20191130")
        request.set("maxDataPoints", 1000)

        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 completely 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...")

您有一个历史数据请求,这在大多数情况下意味着您要请求多天,因此您必须处理它以及您希望如何处理每一天的格式。在这种情况下,您只要求一天,所以让我们谈谈吧。

首先,不要选择周末。您需要一天的时间来存放数据。前一天试试。原始响应如下所示:

HistoricalDataResponse = {
    securityData = {
        security = "EURUSD Curncy"
        eidData[] = {
        }
        sequenceNumber = 0
        fieldExceptions[] = {
        }
        fieldData[] = {
            fieldData = {
                date = 2019-11-29
                PX_LAST = 1.101800
            }
        }
    }
}

对于其中的每一个,都可以访问 blpapi 数据结构。最终,由您决定如何构建它。

不要按原样使用它,因为它有缺陷,但这是获取数据的示例。这是将它放入一个日期的字典中,重点关注您在上述问题中的回答部分:

# inside your existing while loop above
if ev.eventType() == blpapi.Event.RESPONSE:
    response = {}
    sec_data = msg.getElement("securityData")
    field_data = sec_data.getElement("fieldData")
    for individual_date_quote in field_data.values():
        for elem in individual_date_quote.elements():
            response[str(elem.name())] = elem.getValueAsString()
    print("response dict:", response)
    # Response completely received, so we could exit
    break

哪个会给你:

response dict: {'date': '2019-11-29', 'PX_LAST': '1.101800'}

您还需要考虑 ev.eventType() == blpapi.Event.PARTIAL_RESPONSE,以及如何处理多个证券和每个证券的多个日期。查看 {WAPI} 以获取完整文档,但希望这能让您更好地了解如何开始。

如果您只想访问该值并打印它而不将其存储在字典或对象中,您可以按如下方式进行:

while(True):
    ev = session.nextEvent(500)
    for msg in ev:
        print(msg.getElement("securityData").getElement("fieldData").getElement("fieldData").getElementAsInt("PX_LAST"))

您还可以使用 getElementAsFloat() 获取浮点值,这是我建议的格式,而不是整数。

如果你想将它存储在某个地方,你可以为它创建一个字典并执行类似的操作:

while(True):
    ev = session.nextEvent(500)
    for msg in ev:
        oneDateForEquity = msg.getElement("securityData").getElement("fieldData").getElement("fieldData").getElementAsString("date")
        someDict[oneDateForEquity]['PX_LAST'] = msg.getElement("securityData").getElement("fieldData").getElement("fieldData").getElementAsString("PX_LAST")

并存储其他 PX_LAST 值和日期。