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-07-31 98.26 98.69 96.5 28715 96.57 98.04 98.33 2806630 97.7409 <NA> <NA> 873 1 71949 28715
2026-08-03 101.56 102.93 100.305 28993 101.215 101.36 101.76 2948966 101.713 <NA> <NA> 645 1 71995 28993
2026-08-04 109.0 109.36 101.255 88028 101.255 108.23 109.29 9389641 106.6665 <NA> <NA> 1603 1 71999 88028
2026-08-05 98.6 112.91 97.89 99849 110.51 98.46 98.95 10109799 101.2509 <NA> <NA> 1790 1 71996 99849
2026-08-06 100.14 101.48 96.405 70698 101.42 100.07 100.16 6979123 98.7174 <NA> <NA> 1380 1 71987 70698