Hide code cell content

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

Handing sessions with a context manager

By default, the LSEG Data Library for Python expects you to open and close a session manually, typically done with the open_session and close_session functions.

This can lead to problems if you forget to close your session, and it can require you to write more code than you might like.

That can be avoided by using a context manager. Context managers allow you to create a block of code that is executed when you enter and exit a with statement. A common example from Python’s standard library is opening and closing a file like so:

with open("my_file.txt", "w") as f:
    f.write("Hello, world!")

Here’s how to create a custom context manager that will open and close a LSEG Data Library for Python session:

from contextlib import contextmanager

import lseg.data as ld


@contextmanager
def ld_session():
    """Context manager for handling a LSEG Data Library for Python session."""
    try:
        # Create a session and return it
        ld.open_session()
        yield
    finally:
        # Close the session
        ld.close_session()

Once that’s been introduced to your code, you can open a session by running the following code:

with ld_session():
    # Do whatever you want to do your `ld` session in the indent ...
    pass

Once the indent is removed, the session will be closed automatically. Here’s how you could use it to get the current price of Thomson Reuters stock:

with ld_session():
    df = ld.get_history('TRI.N')

df.head(5)
TRI.N TRDPRC_1 HIGH_1 LOW_1 ACVOL_UNS OPEN_PRC BID ASK TRNOVR_UNS VWAP BLKCOUNT BLKVOLUM NUM_MOVES TRD_STATUS SALTIM VWAP_VOL
Date
2026-06-18 78.7 79.32 77.43 29867 78.53 78.42 79.2 2345512 78.5319 <NA> <NA> 652 1 71997 29867
2026-06-22 76.48 79.04 76.43 31985 77.65 76.43 76.66 2466724 77.1213 <NA> <NA> 649 1 71992 31985
2026-06-23 80.77 80.86 78.56 28367 78.82 80.59 80.8 2257979 79.5988 <NA> <NA> 623 1 71961 28367
2026-06-24 80.98 82.14 79.47 15275 79.85 80.9 81.11 1243674 81.4189 <NA> <NA> 418 1 71985 15275
2026-06-25 80.91 82.79 79.59 21718 79.98 80.8 81.52 1753233 80.7272 <NA> <NA> 591 1 71996 21718