download_wrds.get_wrds_connection()

Establish a connection to Wharton Research Data Services (WRDS).

Usage

Source

download_wrds.get_wrds_connection(quiet=False)

Opens a SQLAlchemy connection to the WRDS PostgreSQL database. Credentials are read from the ‘WRDS_USER’ and ‘WRDS_PASSWORD’ environment variables, which can also be supplied through a ‘.env’ file in the working directory (‘load_dotenv’ is called before the lookup). The connection uses the ‘postgresql+psycopg2’ driver, requires SSL, and targets ‘wrds-pgdata.wharton.upenn.edu’ on port 9737. Pool pre-ping is enabled so stale connections are detected and recycled automatically.

Parameters

quiet: bool = False
If True, the messages about the WRDS connection and the download progress are suppressed.

Returns

sqlalchemy.engine.Connection
An open SQLAlchemy connection to the WRDS database. Pass it to any ’download_data_wrds_*’ helper or use it directly with ‘polars.read_database’. Close it via ‘disconnect_connection’ when done.

Raises

ValueError

If ‘WRDS_USER’ or ‘WRDS_PASSWORD’ is not set in the environment or ‘.env’ file. This is checked before the connection is opened.

ConnectionError
If the connection fails, e.g. because the database host is unreachable or the credentials are rejected. The message lists the likely causes. The original error is kept as the cause (‘cause’), with the username and password replaced by placeholders.

Notes

A WRDS username and password alone are not enough to connect. Before the first connection:

  1. Get a WRDS account through an institution that subscribes to the data you need (e.g., CRSP and Compustat).
  2. Enroll in two-factor authentication (Duo) for your WRDS account. WRDS requires it for all connections, including connections from Python.
  3. Log in to the WRDS website (https://wrds-www.wharton.upenn.edu) once and accept the terms of use, if WRDS asks you to.
  4. Store your username and password with ‘set_wrds_credentials’, or set the ‘WRDS_USER’ and ‘WRDS_PASSWORD’ environment variables.
  5. When you connect, approve the Duo push notification on your registered device. The connection waits until you approve it.

If the connection fails, the error message lists these steps. Unless ‘quiet=True’, the function says when it starts connecting and when the connection succeeds, so you know when to approve the Duo request and when the download starts.

See Also

set_wrds_credentials()

Interactively prompts for credentials and writes them to a ‘.env’ file in the project or home directory.

disconnect_connection()

Closes the connection returned by this function.

Examples

import os
os.environ['WRDS_USER'] = 'your_username'
os.environ['WRDS_PASSWORD'] = 'your_password'
from tidyfinance import get_wrds_connection, disconnect_connection
con = get_wrds_connection()
# ... query WRDS via con ...
disconnect_connection(con)