Overview
This article is a sequel to my Part 2: Beyond REST APIs: Concurrent Data Requests with asyncio.gather() and the LSEG Data Library article. In Part III, we move from requesting multiple RICs concurrently with the LSEG Data Library for Python Historical Pricing get_data_async method using asyncio.gather() to the modern (Python 3.11+) asyncio.TaskGroup interface, which offers structured concurrency and a safer task lifecycle model.
Note: This article is based on the Data Library for Python version 2.1.1 using the Platform Session. The library behavior might change in future releases.
(Recap) What is Python Asyncio? And how it relate to Data Library for Python
Before diving deeper, let’s quickly recap Python Asyncio and explore how it enables Data library for Python to perform asynchronous operations efficiently. Python asyncio is a library for writing concurrent code with async/await. The three most common concurrency interfaces are:
- asyncio.create_task(coro) — wraps a coroutine in a Task and schedules it for execution.
- asyncio.gather(*aws) — runs multiple awaitables concurrently and returns their results.
- asyncio.TaskGroup — a modern (Python 3.11+) structured-concurrency API that manages a group of tasks together, ensuring all finish before the block exits.
This article shows how to use the Data Library for Python Historical Pricing get_data_async method to fetch multiple RICs concurrently using asyncio.TaskGroup.
This article uses a Platform Session. For other session types, see the Data Library Quickstart.
(Recap) What are Synchronous and Asynchronous Execution Models?
That bring us to the next step, a briefly recap the synchronous and asynchronous execution models as follows.
Synchronous code runs tasks one at a time — each request must complete before the next one starts. The program blocks and waits at every I/O-bound call, so if a request takes 60 seconds, nothing else runs for those 60 seconds. Fine for a single request, but a real bottleneck when fetching data with many calls.
Asynchronous code lets multiple tasks run concurrently. While one request is waiting for a network response, the event loop hands control to the next task instead of sitting idle.
The real payoff comes when you have many requests to make. With asyncio.gather and asyncio.TaskGroup, all requests are fired concurrently so the total time is roughly that of the single slowest response — not the sum of all response times.
That covers the basic of synchronous and asynchronous executions.
(Recap) Throttling and Rate Limits
My next point is the API calls rate limits. The Data Platform API request limits (throttles) to effectively manage and protect its service and ensure fair usage across the non-streaming content.
An application would receive an error from the API call if an application reached or exceeds a limit (especially with the Asynchronous HTTP calls). You required to make some necessary adjustments to rectify the interaction with the API and retry the respective API call.
Two different server errors on API request limits are:
| HTTP Status | Detail |
|---|---|
| 429 | Error Message: too many attempts |
| Description: A per account limit where the number of requests per second is limited for each account accessing the platform. If this limit is reached, applications will receive a standard HTTP error (HTTP 429 too many requests). | |
| Suggestion: Please reduce the number of requests per second and retry. |
Please find more detail regarding the Data Platform HTTP error status messages from the RDP API General Guidelines document page.
The Historical Pricing endpoint rate limits information is available on the Reference tab of the Data Platform API Playground page. The current rate limits (As of Mar 2026) is as follows:
Prerequisite
The basic knowledge of Python Asyncio library is required before proceeding. You can learn the basic of asyncio from the following resources:
- Python's asyncio: A Hands-On Walkthrough
- Asyncio Architecture in Python: Event Loops, Tasks, and Futures Explained
- A Conceptual Overview of asyncio
- Python Asynchronous I/O
Requirements
Make sure you have the following set up:
- Python 3.11+
- LSEG Data Platform credentials with Historical Pricing permission:
- Machine ID
- Password
- AppKey
Please your LSEG representative or account manager for the Data Platform Access.
Do I need to understand Asyncio.Gather before proceeding this example?
No, you don't. However, if you understand both approaches, you can choose which one is better for your application and business requirements.
That’s all I have to say about this article and example code prerequisite.
Code Walkthrough
Now we come to the code walkthrough. This article focuses primarily on the asynchronous code.
The first step is to import the required libraries. The main libraries are lseg.data and asyncio.
Import Required Libraries
Open a Platform Session
Moving on to the next step, create a Data Library session object to authenticate, manage the connection, and retrieve data.
The code below gets the Data Platform credential from the OS environment variables. You can use the python-dotenv library to load credentials from .env file as well.
If the library can open the session successfully, you should see the <OpenState.Opened: 'Opened'> output message. The library automatic manage the authentication, access token, refresh token, etc. for an application.
The session is opened, we can declare our historical data related variable. The next step is creating the data request variables such as dictionary of company RICs and Name, request fields, etc.
Declare Instruments and Request Parameters
Using Asyncio TaskGroup
Now we come to a brief introduction to Asyncio TaskGroup, how it different from asyncio.gather?
Introduced in Python 3.11, the Task Groups provides a modern and reliable way to manage multiple concurrent tasks using asyncio.TaskGroup interface. It supports structured concurrency, which means tasks created inside the group are managed together and automatically awaited when the group exits.
Although the TaskGroup lets developers run and get results for many tasks similar to asyncio.gather method. However, it behaves differently in several important ways.
TaskGroup must be used with Python async with statement
With Asyncio TaskGroup, developers must create tasks inside the asynchronous context manager using async with statement and the TaskGroup.create_task method. The group automatically waits for all tasks to finish when the async with block exits.
Example Code:
The async with block implicitly waiting for all tasks when the block exits. While the block is still active, new tasks can still be added to the same task group. Once the last task finishes and the async with block is exited, no new tasks may be added to the group.
Getting Result
Unlike the asyncio.gather that returns a list of results in the same order as input, TaskGroup does not directly return a list of results. Developers must keep references to the tasks and call .result() method after the async with block complete as an example above.
The completion, return results and execution order are definitely not guaranteed event if the coroutines are created sequentially, the actual network operations, I/O, OS, etc.
Failure Handling
This is the most important difference between TaskGroup and asyncio.gather(). If one task in the TaskGroup fails, the group automatic cancels the remaining tasks and raises an ExceptionGroup. This Fails Fast behavior helps prevent orphaned background tasks and reduces the risk of resource leaks.
TaskGroup is a good choice all tasks in the same operation and should succeed or fail together. The async with block also helps ensure that task cleanup is handled properly before execution continues.
The first step is defining a new display_response_taskgroup method that supports TaskGroup Fails Fast behavior. Our method is less complicated than the display_response helper function with asyncio.gather(..., return_exceptions=True) approach.
That covers a brief introduction of Asyncio TaskGroup Python code.
Requesting Data with Asyncio TaskGroup, The Basic Form
Now let me turn to the most basic form of grouping multiple calls via Asyncio TaskGroup. I am demonstrating with the historical_pricing.events.Definition for Historical Pricing Events data and historical_pricing.summaries.Definition for Historical Pricing Interday data.
- All requests are created as tasks inside the async with asyncio.TaskGroup() block, which runs them concurrently and waits until every one finishes before moving on.
- Each task carries a closure label (the company name) so you can identify which response belongs to which instrument when displaying results.
After the TaskGroup block finishes, the tasks are complete but their results have not been collected yet.
The cell below does two things:
- Calls task.result() on every task to extract the response data into historical_data, preserving the same order as the original instrument list.
- Displays each response as a DataFrame using display_response_taskgroup.
Please be noticed that when developers send multiple Historical Pricing Definition with a single RIC request, each RIC gets its own data response grouping together sequently in a Python list returns from historical_data = [task.result() for task in tasks] statement.
An application can iterate each result from the returned list (as shown in the display_response_taskgroup method) or use the following statement to get data from its closure.
Understanding asyncio.TaskGroup Code
Before proceeding, let me explain more about the basic of Asyncio TaskGroup Python code above.
The code shows a basic example of using asyncio.TaskGroup to run multiple Historical Pricing module .get_data_async(...) requests concurrently in one managed block.
In the example code, each (ric, company) request is one task. Running them together is usually faster than running them one-by-one.
Why use TaskGroup
TaskGroup provides structured concurrency: tasks are created inside a single managed async with block and are awaited together when the block exits.
This is a strong fit for strict batch workflows. If one task fails, TaskGroup cancels unfinished sibling tasks and raises the failures as one ExceptionGroup.
What this code is doing
- Create one async request per (ric, company) pair using historical_pricing.summaries.Definition(...).get_data_async(...).
- Add each coroutine to the group with tg.create_task(...).
- Let async with asyncio.TaskGroup() wait until all tasks complete (or are cancelled).
- After the block exits, every task is either finished or cancelled due to an error.
After the TaskGroup block exits, use this statement to read the returned data.
Error handling (simple)
- Keep the TaskGroup block inside try/except LDError*.
- Call task.result() only after the TaskGroup block exits.
- The helper display_response_taskgroup(...) methods show each response safely with defensive display pattern.
That’s all I have to say about the basic form of Asyncio TaskGroup code Python code explanation.
Can I use Historical Pricing Events and Summaries Definitions in the same Asyncio TaskGroup?
Yes, you can. The idea is to prepare two separate groups of requests first:
- Event requests - these fetch recent trade and correction events for Boeing (BA.N).
- Intraday summary requests - these fetch 5-minute price bars over the date range for Lockheed Martin (LTM.N).
Both groups are built as lists of coroutines (pending async calls, not yet running). They are then merged into a single list called all_coroutines, keeping their original order.
Separating the setup from the execution makes the code easier to read and lets you confirm what will be requested before anything runs.
Once all_coroutines list is ready, the next cell runs everything at the same time using asyncio.TaskGroup.
- Unlike asyncio.gather, where you can pass mixed Data Library definitions to awaitables directly, TaskGroup works best when we first combine Event and Intraday Summary calls into one all_coroutines list and then create tasks from that list in a single run.
- Keeping them in one ordered list makes result handling easier: the first part of historical_data maps to Event results, and the second part maps to Intraday Summary results.
The code above does the following:
- async with asyncio.TaskGroup() as tg creates a managed task group.
- tg.create_task(coro) schedules each coroutine to run.
- The async with block does not exit until every task in the group has finished (or failed). There is no need to call await manually.
Once the block exits, you can collect the results with task.result() in task-creation order.
If one task raises LDError, TaskGroup cancels the remaining tasks and the except* block reports the error.
The Historical data from the above requests is as follows:
Requesting Data with Request Limits
Moving on to the next topic, how to set up the requests throttle.
Like asyncio.gather(), we can use asyncio.TaskGroup with asyncio.Semaphore to limit the number of in-flight requests (that we are grouping) at any given time (default: 3).
If you are requesting only 2-10 RICs, the backend can usually handle the load without issue. As the number of simultaneous requests grows to 50, 100, or more, a semaphore becomes essential for staying within the platform's rate limits (see the Rate Limit section above). The following example demonstrates this pattern with 20 RICs.
The semaphore pattern is recommended when requesting a large number of instruments from the platform.
Once the semaphore-protected coroutines are ready, the next step is to schedule them as tasks using asyncio.TaskGroup as I have demonstrated previously.
Understanding asyncio.TaskGroup with asyncio.Semaphore
So, now let’s look at how to use asyncio.TaskGroup with asyncio.Semaphore in detail.
An application can uses asyncio.TaskGroup with asyncio.Semaphore to run many requests safely.
Where Semaphore fits
If you start too many requests at once, you may hit HTTP 429 Too Many Requests. A semaphore prevents that by limiting how many requests are in-flight at the same time.
How it works
Only N coroutines can enter the protected section at once. The rest wait.
Key points
- Create the semaphore once, outside the helper function.
- Put await get_data_async(...) inside async with semaphore:.
- The semaphore limits request concurrency per coroutine, while TaskGroup creates and waits for all tasks.
- Start with a small limit (for example 5-10) and lower it if you still see 429 errors.
What fetch_summaries_throttle helper method does
The method uses historical_pricing.summaries.Definition(...) to request summary bars for one instrument. The key important thing is the method runs inside async with semaphore: so request concurrency is limited for each coroutine.
Semaphore controls how many requests run at once; TaskGroup manages the task lifecycle.
Can I use different Definitions in the same Asyncio TaskGroup with a Semaphore?
Yes. The only additional step is to wrap each request in async with semaphore through a helper function; the rest of the TaskGroup pattern remains the same.
What fetch_summaries_throttle helper method does?
The method uses historical_pricing.events.Definition(...) to request event-level data for one instrument. Like the fetch_summaries_throttle method above, it also runs inside async with semaphore: so request concurrency is limited for each coroutine.
Let’s leave the requests throttle there.
How Does TaskGroup Handle Errors?
Now, what about the TaskGroup and the Errors which is a big different between the TaskGroup and asyncio.gather.
The TaskGroup uses a fail-fast approach. If one task raises an error, TaskGroup cancels the remaining tasks and raises an ExceptionGroup. This means the whole batch operation fails as a unit instead of returning partial results to the application.
Note: This error-handling example uses only a small number of RICs, so asyncio.Semaphore is not required in this section.
Invalid and Non-Permission RIC Requests
The example below demonstrates two error cases:
- an invalid RIC: INVALIDRIC.O
- a non-permission RIC: ASML.AS (permission may vary by user account)
This shows how TaskGroup stops the overall operation when one or more requests fail.
As you can see, once the library encounters an error, it raises an exception and immediately marks the entire operation as failed. The error message is not added to the result list because TaskGroup raises the exception as soon as the failure occurs.
Please note that the execution order is not guaranteed, so you might get another error first when you run this code.
Invalid Fields
Now let's see how the library handles invalid fields with the asyncio.TaskGroup.
The library and backend can handle a mix of valid and invalid fields by ignoring the invalid ones and returning data for the valid fields.
With asyncio.TaskGroup, a request that mixes valid and invalid fields can still complete successfully.
You can use the response.data.raw statement to check what error that cause the fields are invalid.
Please note that if a request contains only invalid fields (either one invalid field or a list of all invalid fields), the request fails and raises an exception.
Last Question: Can I make Asyncio TaskGroup return both successful results and errors?
In theory, yes—you can handle this programmatically. However, using asyncio.gather(..., return_exceptions=True) is usually much easier and keeps the code simpler for that requirement.
That’s all I have to say about how Asyncio TaskGroup manages errors.
Close the Session
Now we come to the last section of the code, you can close the session with the following statements.
That brings me to the end of the Data Library Asynchronous methods with Asyncio TaskGroup code walkthrough.
So, Which One Should I Use: Asyncio Gather or TaskGroup for Data Library?
Now let’s get to the main question: which approach should you use?
There isn’t a single right answer. Both Asyncio Gather and TaskGroup are good options. The best choice depends on how you want your application to behave when something goes wrong.
Quick answer
- Use TaskGroup when requests should succeed or fail together, and you want safer, structured error handling.
- Use asyncio.gather(..., return_exceptions=True) when you want more flexible behavior, especially if you need to keep partial successes even when some requests fail.
How they differ in practice
| Area | asyncio.gather | asyncio.TaskGroup |
|---|---|---|
| Main idea | Run many awaitables and collect results | Run many tasks in one managed group |
| Result handling | Returns a result list directly | Keep task references and call .result() |
| Error behavior | Configurable with return_exceptions | Fail-fast by design |
| Partial success support | Strong, especially with return_exceptions=True | Limited, because one failure cancels remaining tasks |
| Safety and structure | Flexible but easier to misuse in complex flows | Strong structured concurrency, easier to reason about |
| Best for | Mixed outcomes, reporting all responses | All-or-nothing operations |
Tradeoffs
asyncio.gather advantages
- Simple for batching and collecting results in one line.
- With return_exceptions=True, you can process successful and failed responses together.
- Useful when your app should continue even if some instruments fail.
asyncio.gather limitations
- Error behavior depends on options and can be confusing in larger workflows.
- Without careful handling, failed tasks can make control flow harder to follow.
TaskGroup advantages
- Clear lifecycle: tasks are created, managed, and completed within one block.
- Fail-fast behavior is safer for operations that must stay consistent.
- Better for production flows where cleanup and predictable control flow matter.
TaskGroup limitations
- More verbose: you must keep task references and extract results manually.
- Not ideal when partial results are the goal, because one failure cancels sibling tasks.
Performance vs Asyncio.Gather
In practice, asyncio.TaskGroup can show a slight performance advantage over asyncio.gather in some Python 3.11+ workloads, partly due to improvements in task management and structured concurrency. However, the difference are micro-level and irrelevant.
That said, performance depends on workload characteristics and runtime conditions, so results may vary. Please check a direct comparison examples using Data Library Historical Pricing historical_pricing.summaries.Definition definition with 30 RICs on 30 RICs with TaskGroup and 30 RICs with Gather notebooks.
Please note that both examples measure retrieval time only, excluding display overhead.
Historical Pricing get_data_async with Asyncio TaskGroup Performance
Historical Pricing get_data_async with Asyncio Gather Performance
Recommended choice for Data Library scenarios
Choose asyncio.gather(..., return_exceptions=True) when:
- You are exploring data from many RICs.
- You want to keep successful responses even if some requests fail.
- You need one combined list of successes and errors for reporting.
Choose TaskGroup when:
- You are running a strict batch job.
- The whole operation should stop if any request fails.
- You want clearer, safer concurrency structure.
Practical rule of thumb
- If you want best-effort results: use asyncio.gather(..., return_exceptions=True).
- If you want all-or-nothing correctness: use asyncio.TaskGroup.
- For both approaches, if you are sending many requests at once: add asyncio.Semaphore to limit in-flight requests and reduce the chance of HTTP 429 errors.
That covers all I wanted to say today.
Reference
You can find more detail regarding the Data Library and Python Asyncio from the following resources:
- LSEG Data Library for Python on the LSEG Developer Community website.
- Data Library for Python - Reference Guide
- Part 2: Beyond REST APIs: Concurrent Data Requests with asyncio.gather() and the LSEG Data Library article.
- Essential Guide to the Data Libraries - Generations of Python library (EDAPI, RDP, RD, LD) article.
- Upgrade from using Eikon Data API to the Data library article.
- Data Library for Python Examples on GitHub repository.
- Comparison of Data Library for Python VS Python/requests direct call for the Delivery Platform (RDP) application article.
- Python Asyncio library page.
- A Conceptual Overview of asyncio article.
- Python's asyncio: A Hands-On Walkthrough
- Asyncio TaskGroup function document page.
For any question related to this example or Data Library, please use the Developers Community Q&A Forum.
Get In Touch
Related Articles
Related APIs
Source Code
Request Free Trial
Call your local sales team
Americas
All countries (toll free): +1 800 427 7570
Brazil: +55 11 47009629
Argentina: +54 11 53546700
Chile: +56 2 24838932
Mexico: +52 55 80005740
Colombia: +57 1 4419404
Europe, Middle East, Africa
Europe: +442045302020
Africa: +27 11 775 3188
Middle East & North Africa: 800035704182
Asia Pacific (Sub-Regional)
Australia & Pacific Islands: +612 8066 2494
China mainland: +86 10 6627 1095
Hong Kong & Macau: +852 3077 5499
India, Bangladesh, Nepal, Maldives & Sri Lanka:
+91 22 6180 7525
Indonesia: +622150960350
Japan: +813 6743 6515
Korea: +822 3478 4303
Malaysia & Brunei: +603 7 724 0502
New Zealand: +64 9913 6203
Philippines: 180 089 094 050 (Globe) or
180 014 410 639 (PLDT)
Singapore and all non-listed ASEAN Countries:
+65 6415 5484
Taiwan: +886 2 7734 4677
Thailand & Laos: +662 844 9576