1 | initial version |
To obtain intraday data using the blp.bdh function in Python Bloomberg, follow these steps:
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()