Download daily prices for listed and delisted stocks with LSEG Workspace in Python

I wrote this post because it is easy to get stuck trying the LSEG API. The script gets you daily stock data since 2000 as a panel, with one row per stock and trading day, in one CSV file. It covers every company registered in Sweden, or any other country you choose, including delisted stocks, whether it is for a thesis, a paper, or testing something.
You need LSEG Workspace through your university or your job, open and signed in on your computer while the script runs, and Python with pandas and a notebook such as Jupyter on the same computer, for example from Anaconda. Install LSEG’s Python package once by running pip install lseg-data in a terminal, such as the Anaconda Prompt. Then copy each box in order, run it, and change the country, dates, and variables.
Step 1. Importing and opening a session
I import three modules and open a session. The session connects Python to your Workspace, and every request below goes through it. If open_session() fails, check that Workspace is open and that you are signed in, and run the box again.
import time
import pandas as pd
import lseg.data as ld
# Every get_data call below needs an open session.
ld.open_session()Step 2. Screening all stocks
A RIC is LSEG’s code for a stock, like a ticker. Ericsson’s B share on Nasdaq Stockholm, for example, has the RIC ERICb.ST.
The screen asks for every primary-listed Swedish stock, both listed and delisted. You need the delisted companies to avoid survivorship bias. If you backtest the historical market using only companies listed today, you exclude companies that later delisted. Leaving them out can bias your estimated returns.
| Part of the screen | What it asks for |
|---|---|
Equity(active or inactive,public,private,primary) |
stocks that trade today or traded before, on their primary listing |
IN(TR.RegCountryCode,"SE") |
companies registered in Sweden, where "SE" is Sweden’s country code |
"DEL" or "LIS" in TR.InstrumentListingStatusCode |
stocks that are delisted or listed |
screener = ld.get_data(
universe=(
'SCREEN('
'U(IN(Equity(active or inactive,public,private,primary))), '
'IN(TR.RegCountryCode,"SE"), '
'(Contains(TR.InstrumentListingStatusCode,"DEL") '
'OR Contains(TR.InstrumentListingStatusCode,"LIS"))'
')'
),
fields=["TR.RIC", "TR.ISIN"]
)
# get_data returns the columns in the order I asked for them, so I name them by position:
# the matched instrument, then the two fields.
screener.columns = ['Instrument', 'RIC', 'ISIN']
# Keep each non-missing RIC once and turn the column into a list.
rics = screener['RIC'].dropna().unique().tolist()
# Drop blank codes and codes made only of spaces, which would fail the next request.
rics = [ric for ric in rics if ric and str(ric).strip()]
print(f"{len(rics):,} RICs to pull")To use another country, swap "SE" for that country’s two-letter code, such as "US" for the United States, "NO" for Norway or "DK" for Denmark. Then change the currency in Step 3, for example to "USD" to get the values in US dollars.
Step 3. Choosing the variables
I pull 15 variables per stock. It is a set I picked as an example. You can pick many more or fewer, and that is up to you.
How do I find the code of a variable?
Every variable has a field code, such as TR.CompanyMarketCap for the market capitalization. To find the code of the variable you want:
- Open the Screener in Workspace by typing SCREENER in the search bar.
- Add the variable you want as a column.
- Press the question mark next to the variable’s name. It shows the variable’s formula, and the field code is the part that starts with
TR.. - Copy the field code into the list below, and give the column a name next to it.
In the list, each field code has the name its column gets in the CSV file.
fields = {
# Identifiers (keep them and their names Company and ISIN, which Step 5 uses)
'TR.CompanyName': 'Company',
'TR.ISIN': 'ISIN',
# Return and its date
'TR.TotalReturn1D': 'Return1D',
'TR.TotalReturn1D.Date': 'Date',
# Size and liquidity
'TR.CompanyMarketCap': 'MarketCap',
'TR.DailyValueTraded': 'ValueTraded',
'TR.EV': 'EV',
# Volume-weighted average price (VWAP), with the default setting and with Adjusted=1
'TR.TSVWAP': 'VWAP',
'TR.TSVWAP(Adjusted=1)': 'VWAPAdjusted',
# Price range, adjusted and as traded
'TR.LOWPRICE(Adjusted=1)': 'LowAdjusted',
'TR.HIGHPRICE(Adjusted=1)': 'HighAdjusted',
'TR.LOWPRICE(Adjusted=0)': 'Low',
'TR.HIGHPRICE(Adjusted=0)': 'High',
# Bid and ask
'TR.BIDPRICE(Adjusted=1)': 'BidAdjusted',
'TR.ASKPRICE(Adjusted=1)': 'AskAdjusted',
}
params = {
'scale': 6, # money amounts in millions
'SDate': '2000-01-01',
'EDate': '2025-05-31',
'Frq': 'D', # daily
'Curn': 'SEK',
}| Setting | What it does |
|---|---|
'scale': 6 |
gives money amounts, such as the market capitalization, in millions |
'SDate' and 'EDate' |
the first and the last date |
'Frq': 'D' |
one row per trading day. 'W' gives weekly rows and 'M' monthly rows, but TR.TotalReturn1D stays the return of one day |
'Curn': 'SEK' |
values in Swedish kronor. 'USD' gives US dollars and 'EUR' euros |
(Adjusted=1) after a field code |
prices adjusted for corporate actions such as stock splits. (Adjusted=0) gives the unadjusted prices |
.Date after a field code |
the date of that field’s value. TR.TotalReturn1D.Date is the date of the return |
In my test run, the dates of the market capitalization, the VWAP and the high price matched Date on every row. To check another variable, add its date to the list, such as 'TR.EV.Date': 'EVDate', and compare that column with Date. If they differ, the value belongs to its own date.
Step 4. Downloading in batches
When you ask for more at once, you will get a stop. LSEG will stop you because it will be too big a request. That is why you need to split it, and also for the sake of your program, so that it does not have too much memory to keep track of. So I ask for five RICs at a time and try each batch up to three times. A batch that fails all three times goes into errors.
BATCH_SIZE = 5 # RICs per request, since LSEG throttles larger ones
BATCH_DELAY = 1.0 # seconds to pause between batches
MAX_TRIES = 3 # attempts at one batch before giving up on it
def fetch_batch(batch):
"""Ask LSEG for one batch of RICs, retrying a few times.
Returns (frame, None) once a request succeeds, or (None, error text) if every
attempt failed. A single transient failure should not end a run of several hundred
requests, which is the only reason the retry loop exists.
"""
for attempt in range(MAX_TRIES):
try:
return ld.get_data(batch, list(fields), params), None
except Exception as error:
if attempt < MAX_TRIES - 1:
# Wait 2 seconds, then 4. Backing off gives a throttled service time to
# recover.
time.sleep(2 * (2 ** attempt))
else:
return None, str(error)[:200]
results = []
errors = []
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:
results.append(frame) # an empty frame means LSEG returned no data for these RICs
time.sleep(BATCH_DELAY) # pause whether the batch worked or not
print(f"{len(results)} batches downloaded, {len(errors)} batches failed")For about 1,655 RICs, that is 331 requests, and my run took about an hour.
Step 5. Combining the batches and saving
Then I join the batches with pd.concat and save everything in one CSV file, from January 2000 to May 2025. LSEG names the columns after the variables, and the adjusted and unadjusted prices have the same names, so I rename the columns using the names from Step 3. In my test run, LSEG gave the company name and the ISIN only on each stock’s first row, so I fill them down to the stock’s other rows.
df = pd.concat(results, ignore_index=True)
# The columns come in the order of the fields, after the stock's code.
df.columns = ['Instrument'] + list(fields.values())
# The company name and the ISIN on every row of the stock.
names = ['Company', 'ISIN']
df[names] = df[names].replace('', pd.NA).groupby(df['Instrument']).ffill()
df.to_csv('swedish_stocks.csv', index=False)The file goes in the folder where your notebook runs. To save it somewhere else, build the path from Path.home() and your user folder using from pathlib import Path and df.to_csv(Path.home() / 'Documents' / 'swedish_stocks.csv', index=False).
Check that errors is empty before you use the file, because the RICs in errors are missing from the CSV. If some batches failed, the box below tries them again and adds what comes back to results. Then run the CSV box above again.
failed = [item['batch'] for item in errors]
errors = []
for batch in failed:
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:
results.append(frame)
time.sleep(BATCH_DELAY)
print(f"{len(errors)} of {len(failed)} batches failed again")And LSEG has a download limit. If you hit that limit, you need to wait until midnight. And I have hit that, especially when you are dealing with large stock markets like the US.
If something goes wrong
| What you see | What to do |
|---|---|
open_session() fails or waits |
Open Workspace, sign in, and run Step 1 again |
| A column is empty | Check the field code in the Screener. Your license may not cover that variable |
A batch ends up in errors |
Run the last box of Step 5, then the CSV box again |
| Every request fails for the rest of the day | You have reached LSEG’s download limit, so wait until midnight |
The whole script in one box
The same five steps in one box, for when you want to copy everything at once.
import time
import pandas as pd
import lseg.data as ld
ld.open_session()
# Step 2. Every Swedish stock, listed and delisted
screener = ld.get_data(
universe=(
'SCREEN('
'U(IN(Equity(active or inactive,public,private,primary))), '
'IN(TR.RegCountryCode,"SE"), '
'(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 and ISIN for Step 5), and the settings
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'}
# Step 4. Five RICs per request, up to three tries each
BATCH_SIZE, BATCH_DELAY, MAX_TRIES = 5, 1.0, 3
def fetch_batch(batch):
for attempt in range(MAX_TRIES):
try:
return ld.get_data(batch, list(fields), params), None
except Exception as error:
if attempt < MAX_TRIES - 1:
time.sleep(2 * (2 ** attempt))
else:
return None, str(error)[:200]
results, errors = [], []
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:
results.append(frame)
time.sleep(BATCH_DELAY)
print(f"{len(results)} batches downloaded, {len(errors)} batches failed")
# Step 5. One table with named columns, saved as one CSV file
df = pd.concat(results, ignore_index=True)
df.columns = ['Instrument'] + list(fields.values())
names = ['Company', 'ISIN']
df[names] = df[names].replace('', pd.NA).groupby(df['Instrument']).ffill()
df.to_csv('swedish_stocks.csv', index=False)Conclusion
So the conclusion is that this is a script for anyone interested in getting stock data, both listed and delisted companies, through LSEG Workspace, when they have a license and Workspace running on their computer. The Screener’s question mark lets you see the formula for any other variable you want.
References
London Stock Exchange Group. (n.d.). LSEG Data Library for Python. LSEG Developer Community. https://developers.lseg.com/en/api-catalog/lseg-data-platform/lseg-data-library-for-python
Read next
- LSEG data in Python Stock prices, tick data, insider trades, IPOs and company identifiers from LSEG.
- Interactive Brokers API in Python: download historical prices with ib_async The broker route to daily price bars, read-only through a paper IBKR account and into pandas with
ib_async. - LSEG Tick History REST API in Python: download trades and quotes A download script for Tick History, which returns trades and quotes to the microsecond through a separate API and its own login.
- Download US insider trading data from LSEG Workspace in Python A download script for US insider trades from the same LSEG session.