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
2025-09-18 160.56 169.32 160.52 64044 169.32 159.87 160.82 10493940 163.8552 <NA> <NA> 1601 <NA> 71993 64044
2025-09-19 162.52 162.79 160.28 38953 161.855 162.23 163.62 6295321 161.6132 <NA> <NA> 1013 <NA> 71997 38953
2025-09-22 163.03 163.09 161.12 27899 161.51 162.85 163.21 4517233 161.9138 <NA> <NA> 777 <NA> 71998 27899
2025-09-23 160.79 163.02 160.44 15740 162.52 160.68 161.02 2542013 161.5002 <NA> <NA> 474 <NA> 71998 15740
2025-09-24 157.71 160.83 157.6 25138 160.83 157.58 157.92 3997779 159.0333 <NA> <NA> 599 <NA> 71985 25138