Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain intraday data using the blp.bdh function in Python Bloomberg, follow these steps:

  1. Install the Bloomberg API package on your machine.
  2. Import the necessary packages in Python, including blpapi, pandas, and datetime.
  3. Establish a session with the Bloomberg terminal using the blpapi.SessionOptions() and blpapi.Session() functions.
  4. Open the session using session.start().
  5. Create a request using the Service identifier, the identifier of the security of interest, the start date and end date of the desired data, the frequency of the data (e.g. "1 minute"), and any additional optional parameters, such as the fields of interest ("LASTPRICE", "VOLUMETRADED", etc.).
  6. Send the request using session.sendRequest().
  7. Collect the response using a while loop, which waits for the response in a threaded manner using session.nextEvent().
  8. Using pandas, extract the data from the response and store it in a pandas dataframe.
  9. Convert any necessary data types (e.g. dates) and save the data to a csv file, or use it as needed for additional data analysis.

Here is an example code snippet for obtaining intraday data using the blp.bdh function in Python Bloomberg:

import blpapi
import pandas as pd
from datetime import datetime

# Establish the Bloomberg session
sessionOptions = blpapi.SessionOptions()
session = blpapi.Session(sessionOptions)
session.start()

# Define the request parameters
security = "AAPL US Equity"
startDateTime = datetime(2020, 2, 5, 15, 30, 0)
endDateTime = datetime(2020, 2, 5, 16, 0, 0)
interval = 1

# Create the request
request = blpapi.event.EventFormatter().formatRequest("bdh")
request.set("security", security)
request.set("fields", "LAST_PRICE,VOLUME_TRADED")
request.set("startDate", startDateTime.strftime("%Y%m%d %H:%M:%S"))
request.set("endDate", endDateTime.strftime("%Y%m%d %H:%M:%S"))
request.set("interval", interval)

# Send the request
session.sendRequest(request)

# Wait for the response
while True:
    event = session.nextEvent(500)
    if event.eventType() == blpapi.event.Event.RESPONSE:
        break

# Extract the data
data = pd.DataFrame(columns=["Datetime", "Last_Price", "Volume_Traded"])
for msg in event:
    for i in range(msg.getElement("securityData").numValues()):
        row = []
        fields = msg.getElement("securityData").getValue(i).getElement("fieldData")
        row.append(datetime.strptime(msg.getElement("securityData").getValue(i).getElementAsString("date"), "%Y%m%dT%H:%M:%S"))
        row.append(fields.getElementAsFloat("LAST_PRICE"))
        row.append(fields.getElementAsFloat("VOLUME_TRADED"))
        data.loc[len(data)] = row

# Convert data types and save to csv
data["Datetime"] = pd.to_datetime(data["Datetime"])
data.to_csv("AAPL_intraday.csv", index=False)

# Stop the session
session.stop()