如何将彭博API中的数据存储到Pandas数据框中? [英] How do I store data from the Bloomberg API into a Pandas dataframe?

查看:236
本文介绍了如何将彭博API中的数据存储到Pandas数据框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用Python,以便可以与Bloomberg API进行交互,并且在将数据存储到Pandas数据框(或面板)中时遇到一些麻烦.我可以在命令提示符下得到输出,所以这不是问题.

I recently started using Python so I could interact with the Bloomberg API, and I'm having some trouble storing the data into a Pandas dataframe (or a panel). I can get the output in the command prompt just fine, so that's not an issue.

这里提出了一个非常类似的问题: Bloomberg api的熊猫包装?

A very similar question was asked here: Pandas wrapper for Bloomberg api?

该问题的可接受答案中的引用代码适用于旧API,但是不适用于新的开放API.显然,提出这个问题的用户能够轻松地修改该代码以使其与新的API一起使用,但是我已经习惯了用R进行操作,这是我对Python的首次尝试.

The referenced code in the accepted answer for that question is for the old API, however, and it doesn't work for the new open API. Apparently the user who asked the question was able to easily modify that code to work with the new API, but I'm used to having my hand held in R, and this is my first endeavor with Python.

一些仁慈的用户可以告诉我如何将这些数据导入Pandas吗? Python API中有一个示例(可在此处找到: http://www.openbloomberg.com/open- api/),名为SimpleHistoryExample.py,我一直在使用它,下面已经包含了它.我相信我需要在'main()'函数末尾围绕'while(True)'循环进行大部分修改,但是到目前为止,我尝试过的所有操作都出现了问题.

Could some benevolent user show me how to get this data into Pandas? There is an example in the Python API (available here: http://www.openbloomberg.com/open-api/) called SimpleHistoryExample.py that I've been working with that I've included below. I believe I'll need to modify mostly around the 'while(True)' loop toward the end of the 'main()' function, but everything I've tried so far has had issues.

预先感谢,希望对使用熊猫金融服务的所有人有所帮助.

Thanks in advance, and I hope this can be of help to anyone using Pandas for finance.

# 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..."

推荐答案

我使用tia( https://github.com/bpsmith/tia/blob/master/examples/datamgr.ipynb )

它已经从Bloomberg下载数据作为熊猫数据框. 您可以在一个电话中下载多个股票的历史记录,甚至可以下载一些Bloombergs参考数据(中央银行日期会议,特定国家/地区的假期等)

It already downloads data as a panda dataframe from bloomberg. You can download history for multiple tickers in one single call and even download some bloombergs reference data (Central Bank date meetings, holidays for a certain country, etc)

您只需使用pip安装它. 该链接包含很多示例,但下载历史数据非常简单:

And you just install it with pip. This link is full of examples but to download historical data is as easy as:

import pandas as pd
import tia.bbg.datamgr as dm

mgr = dm.BbgDataManager()
sids = mgr['MSFT US EQUITY', 'IBM US EQUITY', 'CSCO US EQUITY']
df = sids.get_historical('PX_LAST', '1/1/2014', '11/12/2014')

和df是熊猫数据框.

and df is a pandas dataframe.

希望有帮助

这篇关于如何将彭博API中的数据存储到Pandas数据框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆