LSEG data in Python
LSEG data needs a license, for example through a university or an employer. The stock, insider, IPO and LEI scripts need lseg.data (pip install lseg-data) and LSEG Workspace open and signed in on the same computer. Tick History needs its own username and password, plus pandas and requests. Each script saves one long-format CSV in FOLDER (default Downloads), overwriting any file of the same name.
If a script does not work as it should, email me.
Daily stock data
One row per stock and trading day, with 15 variables including the daily total return (%) and the market capitalization (millions). The example covers all primary listings of companies registered in Sweden, delisted ones included, from January 2000 to May 2025. Before use, check each variable’s date field, such as TR.EV.Date, against the return date, because LSEG does not always align them. Batches failing three times go to a second CSV.
Choose these settings in the code:
COUNTRY, the two-letter country code from the Workspace Screener, SE for Sweden.fields, the variables. The question mark next to a variable in the Workspace Screener shows its code, such as TR.CompanyMarketCap. Keep Company, ISIN and Date, which identify the stock and day.params, the period and the currency, SEK for Swedish stocks.FOLDER, the output folder.
import time
from pathlib import Path
import pandas as pd
import lseg.data as ld
COUNTRY = "SE" # the two-letter country code, SE for Sweden. Change it to get another country.
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
# Step 1. Open the session (LSEG Workspace open and signed in on this computer)
ld.open_session()
# Step 2. Every stock of the country, listed and delisted
screener = ld.get_data(
universe=(
'SCREEN('
'U(IN(Equity(active or inactive,public,private,primary))), '
f'IN(TR.RegCountryCode,"{COUNTRY}"), '
'(Contains(TR.InstrumentListingStatusCode,"DEL") '
'OR Contains(TR.InstrumentListingStatusCode,"LIS"))'
')'
),
fields=["TR.RIC", "TR.ISIN"]
)
screener.columns = ['Instrument', 'RIC', 'ISIN']
rics = screener['RIC'].dropna().unique().tolist()
rics = [ric for ric in rics if ric and str(ric).strip()]
# Step 3. The variables, each with its column name (keep Company, ISIN and Date), and the settings.
# To add a variable, open the Screener in Workspace and press the question mark next to it to see its code.
fields = {
'TR.CompanyName': 'Company',
'TR.ISIN': 'ISIN',
'TR.TotalReturn1D': 'Return1D',
'TR.TotalReturn1D.Date': 'Date',
'TR.CompanyMarketCap': 'MarketCap',
'TR.DailyValueTraded': 'ValueTraded',
'TR.EV': 'EV',
'TR.TSVWAP': 'VWAP',
'TR.TSVWAP(Adjusted=1)': 'VWAPAdjusted',
'TR.LOWPRICE(Adjusted=1)': 'LowAdjusted',
'TR.HIGHPRICE(Adjusted=1)': 'HighAdjusted',
'TR.LOWPRICE(Adjusted=0)': 'Low',
'TR.HIGHPRICE(Adjusted=0)': 'High',
'TR.BIDPRICE(Adjusted=1)': 'BidAdjusted',
'TR.ASKPRICE(Adjusted=1)': 'AskAdjusted',
}
params = {'scale': 6, 'SDate': '2000-01-01', 'EDate': '2025-05-31', 'Frq': 'D',
'Curn': 'SEK'} # millions, the period, daily data and the currency (change SEK with the country)
# Step 4. Five RICs per request, up to three tries each. Each batch gets named columns and goes into the CSV file
# as it arrives, so the code never keeps the whole dataset in memory.
BATCH_SIZE, BATCH_DELAY, MAX_TRIES = 5, 1.0, 3
FOLDER.mkdir(parents=True, exist_ok=True)
output = FOLDER / f'lseg_stocks_{COUNTRY}.csv'
output.unlink(missing_ok=True) # the file of an earlier run
def fetch_batch(batch):
for attempt in range(MAX_TRIES):
try:
frame = ld.get_data(batch, list(fields), params)
frame.columns = ['Instrument'] + list(fields.values())
return frame, None
except Exception as error:
if attempt < MAX_TRIES - 1:
time.sleep(2 * (2 ** attempt))
else:
return None, str(error)[:200]
rows, errors = 0, []
for start in range(0, len(rics), BATCH_SIZE):
batch = rics[start:start + BATCH_SIZE]
frame, error = fetch_batch(batch)
if error is not None:
errors.append({'batch': batch, 'error': error})
elif frame is not None and not frame.empty:
# One row per stock and trading day. LSEG can give the name and ISIN on a stock's first row only,
# so they are filled down to its other rows
names = ['Company', 'ISIN']
frame[names] = frame[names].replace('', pd.NA).groupby(frame['Instrument']).ffill()
frame.to_csv(output, mode='a', header=not output.exists(), index=False)
rows = rows + len(frame)
time.sleep(BATCH_DELAY)
ld.close_session()
# Step 5. The failed batches, if any, in a second CSV file
failed_file = FOLDER / f'lseg_stocks_{COUNTRY}_failed_batches.csv'
if errors:
pd.DataFrame(errors).to_csv(failed_file, index=False)
else:
failed_file.unlink(missing_ok=True) # the list of an earlier run
assert rows, 'No data came back. Check the session, the license, the fields and the failed batches file.'
print(rows, 'rows saved in', output, '|', len(errors), 'batches failed')Full post: Download daily prices for listed and delisted stocks with LSEG Workspace in Python
Tick data
tick_data.csv holds one row per trade, quote, auction or correction, with UTC time stamps. The example covers Vodafone and AstraZeneca in London in May 2025. The script saves one file per stock and 30-day window, then joins them. Reruns skip saved windows, so delete those files after changing the variables or the period.
Choose these settings in the code:
RICS, the stocks’ RICs, such as VOD.L for Vodafone in London. The full post shows how to turn ISINs into RICs.STARTandEND, the period in UTC.fieldsinpayload_tas, the trade, quote, auction and correction variables.CHUNK_DAYS, the days per request and file. Use fewer for the most traded stocks so each file fits in memory.RTH_USERandRTH_PASS, your Tick History username and password.FOLDER, the output folder.
import csv
import gzip
import io
import json
import os
import time
import zipfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta
from pathlib import Path
import pandas as pd
import requests
from pandas.errors import EmptyDataError
RICS = ["VOD.L", "AZN.L"] # the stocks' RICs (.L is the London Stock Exchange)
START = "2025-05-01T07:00:00.000Z" # UTC, inclusive
END = "2025-05-31T23:59:59.000Z" # the end of the period, UTC
FOLDER = Path.home() / "Downloads" / "tick_data" # change this to the folder for the CSV files
CHUNK_DAYS = 30 # days per request and file (fewer for the most traded stocks)
MAX_WORKERS = 3 # parallel downloads
MAX_RETRIES = 10 # per-chunk retries
os.environ["RTH_USER"] = "YOUR_USERNAME" # your DataScope user id
os.environ["RTH_PASS"] = "YOUR_PASSWORD" # your DataScope password (never share a file that contains it)
BASE = "https://selectapi.datascope.lseg.com/RestApi/v1"
AUTH_URL = f"{BASE}/Authentication/RequestToken"
EXTRACT_URL = f"{BASE}/Extractions/ExtractRaw"
class RTHError(RuntimeError):
pass
def auth_token():
u, p = os.environ.get("RTH_USER"), os.environ.get("RTH_PASS")
if not u or not p:
raise RTHError("Set RTH_USER and RTH_PASS first.")
r = requests.post(AUTH_URL, json={"Credentials": {"Username": u, "Password": p}}, timeout=60)
if r.status_code != 200:
raise RTHError(f"AUTH {r.status_code}: {r.text[:500]}")
token = r.json().get("value")
if not token:
raise RTHError("Authenticated, but no token came back.")
return token
def payload_tas(ric, start, end, fields=None):
fields = fields or [ # change this list to choose other fields
# Trade
"Trade - Price", "Trade - Volume", "Trade - Exchange Time",
"Trade - Qualifiers", "Trade - Exchange/Contributor ID",
"Trade - Buyer ID", "Trade - Seller ID",
"Trade - Trade Price Currency", "Trade - ISIN",
# Auction
"Auction - Price", "Auction - Volume", "Auction - Exchange Time",
"Auction - Bid Price", "Auction - Bid Size",
"Auction - Ask Price", "Auction - Ask Size", "Auction - Qualifiers",
# Quote
"Quote - Bid Price", "Quote - Bid Size",
"Quote - Ask Price", "Quote - Ask Size", "Quote - Volume",
"Quote - Exchange Time", "Quote - Qualifiers",
"Quote - Exchange/Contributor ID",
"Quote - Buyer ID", "Quote - Seller ID", "Quote - ISIN",
# Correction
"Correction - Bid Price", "Correction - Ask Price",
"Correction - Exchange Time", "Correction - Exchange/Contributor ID",
"Correction - Original Exchange Time", "Correction - ISIN",
]
return {
"ExtractionRequest": {
"@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.TickHistoryTimeAndSalesExtractionRequest",
"ContentFieldNames": fields,
"IdentifierList": {
"@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.InstrumentIdentifierList",
"InstrumentIdentifiers": [{"Identifier": ric, "IdentifierType": "Ric"}],
"ValidationOptions": {
"AllowHistoricalInstruments": True, # keep delisted names
"AllowInactiveInstruments": True,
"AllowOpenAccessInstruments": True,
},
"UseUserPreferencesForValidationOptions": False,
},
"Condition": {
"MessageTimeStampIn": "GmtUtc",
"ApplyCorrectionsAndCancellations": True,
"ReportDateRangeType": "Range",
"QueryStartDate": start,
"QueryEndDate": end,
"DisplaySourceRIC": True,
},
}
}
def _read_zip_or_csv_bytes(b: bytes) -> pd.DataFrame:
if b[:2] == b"\x1f\x8b": # a gzip file starts with these two bytes
b = gzip.decompress(b)
if len(b) > 4 and b[:4] == b"PK\x03\x04": # a ZIP file starts with these four bytes
with zipfile.ZipFile(io.BytesIO(b)) as z:
names = [n for n in z.namelist() if n.lower().endswith(".csv")] or z.namelist()
if not names:
raise RTHError("ZIP had no files.")
with z.open(names[0]) as f:
return pd.read_csv(f, dtype=str, keep_default_na=False) # text, so IDs keep leading zeros
return pd.read_csv(io.BytesIO(b), dtype=str, keep_default_na=False) # otherwise a plain CSV
def _collect_links(j):
urls = []
for key in ("Notes", "notes"):
for n in (j.get(key) or []):
if isinstance(n, dict) and "URL" in n:
urls.append(n["URL"])
for c in (j.get("Contents") or []):
if isinstance(c, dict) and "Location" in c:
urls.append(c["Location"])
return urls
def download_stream_by_jobid(token, job_id) -> pd.DataFrame:
headers = {"Authorization": f"Token {token}"}
url = f"{BASE}/Extractions/RawExtractionResults('{job_id}')/$value"
r = requests.get(url, headers=headers, stream=True, timeout=600)
if r.status_code >= 400:
raise RTHError(f"DOWNLOAD {r.status_code}: {r.text[:800]}")
return _read_zip_or_csv_bytes(r.content)
def extract_tas_df(ric, start, end, token) -> pd.DataFrame:
headers = {"Authorization": f"Token {token}", "Content-Type": "application/json",
"Prefer": "respond-async"}
resp = requests.post(EXTRACT_URL, headers=headers, data=json.dumps(payload_tas(ric, start, end)),
timeout=60)
location = resp.headers.get("Location") # the address to ask while the extraction runs
while resp.status_code == 202: # the extraction still runs, so ask again in 30 seconds
time.sleep(30)
resp = requests.get(location, headers=headers, timeout=60)
if resp.status_code >= 400:
raise RTHError(f"EXTRACT {resp.status_code}: {resp.text[:1200]}")
j = resp.json()
notes = [note for note in (j.get("Notes") or []) if isinstance(note, str)]
if notes: # LSEG's extraction notes, such as warnings and quotas
print(ric, start[:10], "|", " ".join(notes)[:1000])
links = _collect_links(j)
if links: # case 1: URLs to fetch
frames = []
for u in links:
r = requests.get(u, headers=headers, stream=True, timeout=600)
if r.status_code >= 400:
raise RTHError(f"DOWNLOAD {r.status_code}: {r.text[:800]}")
frames.append(_read_zip_or_csv_bytes(r.content))
return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
job_id = j.get("JobId") or j.get("jobId")
if job_id: # case 2: a JobId to stream
return download_stream_by_jobid(token, job_id)
rows = j.get("Data") or j.get("Rows") # case 3: rows inline
if rows is None:
raise RTHError(f"No links, no JobId, no rows. Body: {str(j)[:1000]}")
return pd.DataFrame(rows)
def daterange_chunks(start_date, end_date, chunk_days):
"""Split a date range into windows of chunk_days, the last one possibly shorter.
A whole date range in one request can be more than the service will return in one go,
so each window is asked for separately. CHUNK_DAYS sets the width.
"""
current = start_date
while current < end_date:
window_end = current + timedelta(days=chunk_days)
yield current, min(window_end, end_date) # min: never run past the end asked for
current = window_end
def process_chunk(ric, chunk_start, chunk_end, token):
"""Download one stock over one window, unless its file is already on disk."""
start_text = chunk_start.strftime("%Y-%m-%dT%H:%M:%S.000Z")
end_text = chunk_end.strftime("%Y-%m-%dT%H:%M:%S.000Z")
label = f"{chunk_start.date()}_{chunk_end.date()}"
out_csv = FOLDER / f"{ric}_{label}.csv"
if out_csv.exists():
return {
"ok": True,
"status": "skipped",
}
for attempt in range(1, MAX_RETRIES + 1):
try:
df = extract_tas_df(ric, start_text, end_text, token)
# Write to a .part file and rename it once the write finished. A run killed
# mid-write then leaves no half-file that the resume check would trust.
tmp_csv = out_csv.with_suffix(".csv.part")
df.to_csv(tmp_csv, index=False)
tmp_csv.replace(out_csv)
return {
"ok": True,
"status": "saved",
"rows": len(df),
}
except EmptyDataError:
return {
"ok": True,
"status": "empty",
}
except Exception as ex:
err = f"{type(ex).__name__}: {ex}"
if attempt < MAX_RETRIES:
time.sleep(2 * attempt)
continue
return {
"ok": False,
"status": "failed",
"ric": ric,
"chunk": label,
"error": err,
}
def main():
FOLDER.mkdir(parents=True, exist_ok=True)
(FOLDER / "failed_rics.csv").unlink(missing_ok=True) # the list of an earlier run
(FOLDER / "tick_data.csv").unlink(missing_ok=True) # the joined file of an earlier run
token = auth_token()
start_dt = datetime.strptime(START, "%Y-%m-%dT%H:%M:%S.000Z")
end_dt = datetime.strptime(END, "%Y-%m-%dT%H:%M:%S.000Z")
tasks = [(ric, cs, ce, token)
for ric in RICS
for cs, ce in daterange_chunks(start_dt, end_dt, CHUNK_DAYS)]
results = []
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as ex:
for fut in as_completed(ex.submit(process_chunk, *t) for t in tasks):
results.append(fut.result())
failed = [res for res in results if not res["ok"]]
if failed:
path = FOLDER / "failed_rics.csv"
with path.open("w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["RIC", "Chunk", "Error"])
for row in failed:
w.writerow([row["ric"], row["chunk"], row["error"]])
# Windows saved, skipped (file already there), empty (no data) and failed, and the rows saved
summary = pd.Series([res["status"] for res in results]).value_counts().to_dict()
print("windows:", summary, "| rows saved:", sum(res.get("rows", 0) for res in results))
# One CSV file with every window of this run, one row per trade, quote or auction.
# The window files stay, so a rerun skips the windows already downloaded.
files = [FOLDER / f"{ric}_{cs.date()}_{ce.date()}.csv" for ric, cs, ce, _ in tasks]
# The files are joined one at a time, so the computer holds one window in memory at once.
files = [path for path in files if path.exists()]
assert files, "No window file came back, so the code wrote no tick_data.csv. See failed_rics.csv."
columns = [] # every column of every window, in order
for path in files:
columns += [column for column in pd.read_csv(path, dtype=str, nrows=0).columns if column not in columns]
rows = 0
for number, path in enumerate(files):
frame = pd.read_csv(path, dtype=str, keep_default_na=False).reindex(columns=columns)
frame.to_csv(FOLDER / "tick_data.csv", mode="w" if number == 0 else "a", header=number == 0, index=False)
rows = rows + len(frame)
print(rows, "rows in", FOLDER / "tick_data.csv")
if __name__ == "__main__":
main()Full post: LSEG Tick History REST API in Python: download trades and quotes
Insider trades
One row per insider trade, with the insider’s name and role, the trade date and type, the shares as reported and the price. The script covers all primary listings of companies registered in COUNTRY, delisted ones included, from 2000 to 2025. Allow hours for countries with many companies. Check for trades repeated across two share classes and for variables left empty by successful requests. Batches failing three times go to a second CSV.
Choose these settings in the code:
COUNTRY, the two-letter country code from the Workspace Screener, such as SE for Sweden.STARTandEND, the trade dates.fields, the variable codes from the Data Item Browser in Workspace.FOLDER, the output folder.
import time
from pathlib import Path
import pandas as pd
import lseg.data as ld
COUNTRY = "US" # the two-letter country code. Change it to get another country, such as SE for Sweden.
START, END = "2000-01-01", "2025-12-31" # the period of the trades
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
# Step 1. Open the session (LSEG Workspace open and signed in on this computer)
ld.open_session()
# Step 2. Every stock of the country, listed and delisted, by its primary quote
screener = ld.get_data(
universe=(
'SCREEN('
'U(IN(Equity(active or inactive,public,private,primary))), '
f'IN(TR.RegCountryCode,"{COUNTRY}"), '
'(Contains(TR.InstrumentListingStatusCode,"DEL") '
'OR Contains(TR.InstrumentListingStatusCode,"LIS"))'
')'
),
fields=["TR.RIC"]
)
screener.columns = ['Instrument', 'RIC']
rics = screener['RIC'].dropna().unique().tolist()
rics = [ric for ric in rics if ric and str(ric).strip()]
# Step 3. The insider variables, each with its column name.
# To add a variable, look up its code in the Data Item Browser in Workspace.
fields = {
'TR.InsiderFullName': 'Insider',
'TR.InsiderRole': 'Role',
'TR.TransactionDate': 'Date',
'TR.ShortTransactionType': 'Type',
'TR.AsRepSharesTraded': 'Shares',
'TR.TransactionPrice': 'Price',
}
params = {'SDate': START, 'EDate': END}
# Step 4. 50 RICs per request, up to three tries each. Each batch gets named columns and goes into the CSV file
# as it arrives, so the code never keeps the whole dataset in memory.
BATCH_SIZE, BATCH_DELAY, MAX_TRIES = 50, 0.5, 3
FOLDER.mkdir(parents=True, exist_ok=True)
output = FOLDER / f'lseg_insider_trades_{COUNTRY}.csv'
output.unlink(missing_ok=True) # the file of an earlier run
def fetch_batch(batch):
for attempt in range(MAX_TRIES):
try:
frame = ld.get_data(batch, list(fields), params)
frame.columns = ['Instrument'] + list(fields.values())
return frame, None
except Exception as error:
if attempt < MAX_TRIES - 1:
time.sleep(2 * (2 ** attempt))
else:
return None, str(error)[:200]
rows, errors = 0, []
for first in range(0, len(rics), BATCH_SIZE):
batch = rics[first:first + BATCH_SIZE]
frame, error = fetch_batch(batch)
if error is not None:
errors.append({'batch': batch, 'error': error})
elif frame is not None and not frame.empty:
# One row per insider trade. Rows with no returned insider information are left out
empty = frame[list(fields.values())].replace('', pd.NA).isna().all(axis=1)
frame = frame[~empty]
if not frame.empty:
frame.to_csv(output, mode='a', header=not output.exists(), index=False)
rows = rows + len(frame)
time.sleep(BATCH_DELAY)
ld.close_session()
# Step 5. The failed batches, if any, in a second CSV file
failed_file = FOLDER / f'lseg_insider_trades_{COUNTRY}_failed_batches.csv'
if errors:
pd.DataFrame(errors).to_csv(failed_file, index=False)
else:
failed_file.unlink(missing_ok=True) # the list of an earlier run
assert rows, 'No data came back. Check the session, the license, the fields and the failed batches file.'
print(rows, 'rows saved in', output, '|', len(errors), 'batches failed')Full post: Download US insider trading data from LSEG Workspace in Python
IPOs
One row per IPO before the full post’s cleaning step, with the offer price, the proceeds and flags for special purpose acquisition companies (SPACs). The script covers the 1988 to 2026 IPOs of issuers from ISSUER_NATION, delisted and merged companies included. LSEG’s deals database, DEALSEQ, needs a separate permission.
Choose these settings in the code:
ISSUER_NATION, the issuer’s country code. Check it in Workspace, because the deals database and the stock screen can use different codes.YEARS, the years of issue.CURRENCY, the currency of the amounts, such as USD or SEK.DEAL_FIELDS, the variable codes from the Data Item Browser in Workspace, with their names inCOLSin the same order.FOLDER, the output folder.
import warnings
# This runs before the other imports on purpose. lseg.data and pandas can raise a warning
# while they are themselves importing, and a filter set afterwards would come too late.
warnings.filterwarnings("ignore") # suppress the lseg and pandas warnings
from pathlib import Path
import pandas as pd
import lseg.data as ld
ISSUER_NATION = "US" # the issuer's country code. Change it to get another country's IPOs.
YEARS = range(1988, 2027) # the years of issue, 1988 to 2026
CURRENCY = "USD" # the currency of the amounts
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
ld.get_config().set_param("http.request-timeout", 300) # must precede open_session
ld.open_session()
# The SDC deals screen: every IPO by an issuer from ISSUER_NATION in [a, b], with dates as YYYYMMDD.
# Universe is IN(DEALS) with the DEALSEQ package hint. TR.NIIssueDate gates the window.
def deals_screen(a, b):
return ("SCREEN(U(IN(DEALS)/*UNV:DEALSEQ*/),"
f'IN(TR.NIIssuerNation,"{ISSUER_NATION}"),'
"TR.NIIsECM=true,TR.NIIsIPO=true,"
f"BETWEEN(TR.NIIssueDate,{a},{b}))")
# Enrichment fields, in the order get_data returns them, and their column names in the same order.
DEAL_FIELDS = [
"TR.NIIssueDate", # the deal date
"TR.NIIssuer",
"TR.NISdcPackageNumber", # SDC's permanent key for the deal
"TR.NIIssueType",
"TR.NIIssueDesc", # the security type
"TR.NIListingNation",
"TR.NIProceedsAmtAllMkts",
"TR.NIOfferPrice",
"TR.NIIsBlankCheckCompany", # the SPAC flag
"TR.NIIsBusinessDevelopmentCompany",
"TR.NIIssuerPrimarySic",
]
COLS = ["instrument","issue_date","issuer","pkg","issue_type","issue_desc","listing",
"proceeds","offer_price","is_spac","is_bdc","sic"]
# get_data returns the instrument and then the fields in the order asked for, so each year's columns are named by
# position. If a field does not come back, the column count differs and the code stops instead of naming wrongly.
frames = []
for yr in YEARS: # one request per year of issue
df = ld.get_data(deals_screen(f"{yr}0101", f"{yr}1231"),
DEAL_FIELDS, parameters={"Curn": CURRENCY})
if df is not None and len(df):
assert df.shape[1] == len(COLS), f"{yr}: expected {len(COLS)} columns, got {list(df.columns)}"
df.columns = COLS
frames.append(df)
ld.close_session()
assert frames, f"No IPOs came back for {ISSUER_NATION}. Check the DEALSEQ permission and the country code."
deals = pd.concat(frames, ignore_index=True)
deals["issue_date"] = pd.to_datetime(deals["issue_date"], errors="coerce")
deals = deals.dropna(subset=["issue_date"])
# The package number is SDC's permanent key for a deal, so one row per package is one row
# per IPO even when the same deal was filed as several tranches. Deals without a package number stay.
no_package = deals["pkg"].isna() | deals["pkg"].eq("")
deals = deals[no_package | ~deals.duplicated("pkg")]
# One row per IPO, saved as one CSV file
FOLDER.mkdir(parents=True, exist_ok=True)
deals.to_csv(FOLDER / f"lseg_ipos_{ISSUER_NATION}.csv", index=False)
print(len(deals), "IPOs saved")Full post: Download US IPO data from LSEG Workspace in Python
LEI to PermID
One row per valid Legal Entity Identifier (LEI) in leis.csv, with the entity’s name and PermID, LSEG’s number for an organization. If leis.csv is missing from FOLDER, the script uses 25 example LEIs and says so.
Choose these settings in the code:
FOLDER, the input and output folder.leis.csv, your LEIs in a column named lei.
import re
from pathlib import Path
import httpx
import lseg.data as ld
import pandas as pd
# Path.home() is your user folder, and / joins a folder and a file name
FOLDER = Path.home() / "Downloads" # change this to the folder with leis.csv and for the CSV file
LEI_FILE = FOLDER / "leis.csv" # your LEIs, in a column named lei
PERMID_FILE = FOLDER / "lei_permids.csv" # the result, written below
BATCH_SIZE = 100 # LEIs per request
# Used when leis.csv is missing: 25 entries from GLEIF's public LEI register, read on 25 October 2026.
# The last three are written wrongly on purpose, to show what the code does with such entries
EXAMPLE_LEIS = [
"HWUPKR0MPOU8FGXBT394", # Apple Inc., United States
"INR2EJN1ERAN0W5ZP974", # Microsoft Corporation, United States
"549300W9JLPW15XIFM52", # Telefonaktiebolaget LM Ericsson, Sweden
"549300HGV012CNC8JD22", # Aktiebolaget Volvo, Sweden
"549300VEBQPHRZBKUX38", # Investor Aktiebolag, Sweden
"529900O5RR7R39FRDM42", # H & M Hennes & Mauritz AB, Sweden
"213800TB53ELEUKM7Q61", # Vodafone Group Public Limited Company, United Kingdom
"MLU0ZO3ML4LN2LL2TL39", # HSBC Holdings plc, United Kingdom
"21380068P1DRHMJ8KU70", # Shell plc, United Kingdom
"W38RGI023J3WT1HWRP32", # Siemens Aktiengesellschaft, Germany
"7LTWFZYICNSX8D621K86", # Deutsche Bank Aktiengesellschaft, Germany
"529900S21EQ1BO4ESM68", # TotalEnergies SE, France
"KY37LUS27QQX7BB93L28", # Nestlé S.A., Switzerland
"549300SZJ9VS8SGXAN81", # UBS Group AG, Switzerland
"724500Y6DUVHQD6OXN27", # ASML Holding N.V., Netherlands
"549300DAQ1CVT6CXN342", # Novo Nordisk A/S, Denmark
"5493006W3QUS5LMH6R84", # Toyota Motor Corporation, Japan
"ES7IP3U3RHIGC71XBU11", # Royal Bank of Canada, Canada
"549300G81RQKP7XW2N18", # Apple Operations International Limited, Ireland, not listed
"549300506SI9CRFV9Z86", # Credit Suisse Group AG, Switzerland, retired when UBS took it over
"549300RTWP0GIJZL7V79", # Microsoft Corporation Savings Plus 401(k) Plan, a pension plan
"254900KZR24L5GN8TE52", # Apple Ford, Inc., a car dealer whose LEI has lapsed
"HWUPKR0MPOU8FGXBT395", # Apple's LEI with its last digit changed
"HWUPKR0MPOU8FGXBT39", # Apple's LEI with its last digit missing
" 549300w9jlpw15xifm52 ", # Ericsson's LEI in lower case, with spaces
]
def check_digits_hold(lei):
"""The last two characters of an LEI are check digits (ISO 17442). With each letter written as a
number, A as 10 up to Z as 35, the LEI read as one long number leaves a remainder of 1 when
divided by 97. int(character, 36) gives that number for a digit or a letter."""
return int("".join(str(int(character, 36)) for character in lei)) % 97 == 1
def open_lseg():
"""Open the LSEG session. lseg-data 2.1.1 passes proxy={} to httpx, which httpx 0.28 and later
reject with "'dict' object has no attribute 'url'". On that error the empty dictionary is
turned into no proxy, and the session is opened again."""
ld.get_config().set_param("http.request-timeout", 300) # seconds, read when the session opens
try:
ld.open_session()
except AttributeError:
for client in (httpx.Client, httpx.AsyncClient):
original = client.__init__
def patched(self, *args, _original=original, **kwargs):
if isinstance(kwargs.get("proxy"), dict):
kwargs["proxy"] = next((value for value in kwargs["proxy"].values()
if value), None)
return _original(self, *args, **kwargs)
client.__init__ = patched
ld.open_session()
# Your LEIs, or the example when leis.csv is missing
if LEI_FILE.exists():
entries = pd.read_csv(LEI_FILE, dtype=str)["lei"]
else:
entries = pd.Series(EXAMPLE_LEIS)
print("leis.csv is not in FOLDER, so the code takes the example LEIs")
# str.strip removes spaces at either end, str.upper writes the letters as capitals, and unique()
# keeps each LEI once
leis = entries.dropna().str.strip().str.upper().unique()
# An LEI has 18 letters or digits and then two check digits (ISO 17442)
valid = [lei for lei in leis if re.fullmatch(r"[A-Z0-9]{18}[0-9]{2}", lei) and check_digits_hold(lei)]
assert valid, "No valid LEIs. Check the column lei in leis.csv."
open_lseg()
tables = []
# range(0, n, BATCH_SIZE) gives 0, 100, 200, ..., and valid[first:first + BATCH_SIZE] is one batch
for first in range(0, len(valid), BATCH_SIZE):
batch = valid[first:first + BATCH_SIZE]
# "<LEI>@LEI" asks for the organization with that LEI. TR.OrganizationID is the organization's
# PermID, and TR.CommonName its name, to check the match
table = ld.get_data(universe=[f"{lei}@LEI" for lei in batch],
fields=["TR.OrganizationID", "TR.CommonName"])
tables.append(table)
ld.close_session()
# concat stacks the batches. The columns are named by position, because LSEG names them for display
result = pd.concat(tables, ignore_index=True)
assert result.shape[1] == 3, f"expected three columns, got {list(result.columns)}"
result.columns = ["instrument", "organization_permid", "name"]
result["lei"] = result["instrument"].str.replace("@LEI", "", regex=False)
# One row per LEI, saved as one CSV file
FOLDER.mkdir(parents=True, exist_ok=True)
result[["lei", "organization_permid", "name"]].to_csv(PERMID_FILE, index=False)
print(len(result), "LEIs saved")Full post: Map an LEI to a PermID with LSEG in Python