Handing sessions with a context manager

By default, the Refinitiv 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 Refinitiv Data Library for Python session:

from contextlib import contextmanager

import refinitiv.data as rd


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

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

with rd_session():
    # Do whatever you want to do your `rd` session in the indent ...
    pass
/home/runner/.local/share/virtualenvs/refinitiv-data-python-cookbook-I-HIyNf4/lib/python3.10/site-packages/refinitiv/data/_access_layer/session.py:71:FutureWarning: 
You open a platform session using the default value of the signon_control parameter (signon_control=True).
In future library version v2.0, this default will be changed to False.
If you want to keep the same behavior as today, you will need to set the signon_control parameter to True either in the library configuration file
({'sessions':{'platform':{'your_session_name':{'signon_control':true}}}}) or in your code where you create the Platform Session.
These alternative options are already supported in the current version of the library.

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 rd_session():
    df = rd.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
Date
2024-03-28 155.83 157.6 155.03 136750 156.17 155.69 155.77 21297952 155.7437 1 38347 1451 1 72600
2024-04-01 155.3 155.84 154.07 49537 155.84 155.24 155.25 7684388 155.1242 1 18664 783 1 72600
2024-04-02 152.73 154.26 152.12 74566 153.79 152.67 152.73 11394046 152.8048 1 23812 992 1 72600
2024-04-03 152.44 153.49 151.98 59196 152.08 152.36 152.44 9032983 152.5945 1 22021 839 1 72600
2024-04-04 152.15 153.71 151.31 144144 153.12 152.05 152.15 21929318 152.1348 1 89214 878 1 72600