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)
/home/runner/.local/share/virtualenvs/refinitiv-data-python-cookbook-I-HIyNf4/lib/python3.10/site-packages/refinitiv/data/_tools/_dataframe.py:177:FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`
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-07-03 168.4 170.29 168.4 55852 168.4 168.4 168.5 9439595 169.0109 <NA> <NA> 955 1 75600
2024-07-05 169.22 169.7 167.58 88376 169.7 169.12 169.13 14913500 168.7506 1 18545 1108 1 72600
2024-07-08 167.87 169.58 166.91 83826 169.58 167.87 167.97 14066352 167.8042 1 16245 1113 1 72600
2024-07-09 167.02 168.78 166.9 82874 168.01 167.07 167.12 13865832 167.3122 1 18381 1033 1 72600
2024-07-10 167.69 167.99 166.94 97018 167.07 167.58 167.69 16262454 167.6231 1 13290 1432 1 72600