What am I doing wrong?
I'm trying to follow this: https://developers.lseg.com/en/article-catalog/article/using-tick-history-in-r-language-part-3
def preview_response(response, num_lines=100):
"""
Prints the first few lines of a streamed Refinitiv API response.
:param response: The streamed API response.
:param num_lines: Number of lines to preview.
"""
print("Previewing first few lines of response:...")
for i, line in enumerate(response.iter_lines(decode_unicode=True)):
if line:
print(line) # Print each line of data
if i >= num_lines - 1: # Stop after num_lines
break
def get_time_and_sales(ticker, query_start_date, query_end_date):
"""
Retrieves time and sales data for a given ticker from Refinitiv.
This method fetches historical time and sales data which includes trade information
such as price, volume, and timestamp for each trade.
Args:
ticker (str): The RIC identifier for the instrument (e.g., "AAPL.O")
query_start_date (str): Start date in ISO format (e.g., "2024-03-01T09:30:00Z")
query_end_date (str): End date in ISO format (e.g., "2024-03-01T16:00:00Z")
Returns:
requests.Response: A streaming response containing the time and sales data in CSV format
Example:
response = get_time_and_sales("AAPL.O", "2024-03-01T09:30:00Z", "2024-03-01T16:00:00Z")
# Process the response as needed
"""
logger.info(f"Fetching time and sales data for {ticker} from {query_start_date} to {query_end_date}...")
json_blob = {
"ExtractionRequest": {
"@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.TickHistoryTimeAndSalesExtractionRequest",
"ContentFieldNames": [
"Trade - Price",
"Trade - Volume",
"Trade - Exchange Time"
],
"IdentifierList": {
"@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.InstrumentIdentifierList",
"InstrumentIdentifiers": [
{
"Identifier": f"{ticker}",
"IdentifierType": "Ric"
}
],
},
"Condition": {
"MessageTimeStampIn": "GmtUtc",
"ReportDateRangeType": "Range",
"QueryStartDate": query_start_date,
"QueryEndDate": query_end_date
},
}
}
post_url = URL_BASE + "/Extractions/ExtractRaw"
# Make the request directly instead of using post_request_with_auth to include Content-Type header
request_response = requests.post(
post_url,
headers={
"Authorization": f"Token {REFINITIV_AUTH_TOKEN}",
"Content-Type": "application/json",
"Prefer": "respond-async"
},
json=json_blob
)
# Check for errors and log the response for debugging
if request_response.status_code != 200:
logger.error(f"Error response: {request_response.status_code} - {request_response.text}")
request_response.raise_for_status()
job_id = request_response.json()["JobId"]
logger.info(f"Time and sales data extraction job started with ID: {job_id}")
data_response = requests.get(
URL_BASE + f"/Extractions/RawExtractionResults('{job_id}')/$value",
headers={
"Authorization": f"Token {REFINITIV_AUTH_TOKEN}",
"Prefer": "respond-async"
}
)
data_response.raise_for_status()
logger.info(f"Time and sales data retrieved successfully for {ticker}")
return data_response
# Example usage:
if __name__ == "__main__":
t_s_data = get_time_and_sales(symbol, start_date, end_date)
preview_response(t_s_data)