Börsdata data in Python

Daily stock prices, company reports and ratios such as P/E, EBIT/EV and free cash flow yield for the Nordic stocks listed today, from Börsdata.
Published

November 26, 2026

Updated

November 29, 2026

Börsdata’s API needs a Pro+ membership and an API key from the API tab on MinSida. In a notebook, set the key with import os and os.environ["BORSDATA_API_KEY"] = "your key", and never share a file that contains it. Install the tested client with pip install pandas tenacity https://github.com/alexwox/Modern-Borsdata-Client/archive/df4231e4ad72a803202dfd32dfa459c4d03afa49.zip. The scripts take today’s listings, so delisted companies are missing and backtests have survivorship bias. Börsdata’s API documentation lists other data. 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 prices

One row per stock and trading day from January 2016, with the open, high, low and close prices and the volume. The prices are split-adjusted and exclude dividends. The example covers the 367 common shares listed on Nasdaq Stockholm Large, Mid and Small Cap on 26 November 2026.

Choose these settings in the code:

  • MARKET_IDS, the markets, from the list the script prints.
  • START, the first day.
  • BORSDATA_API_KEY, your API key.
  • FOLDER, the output folder.
import os
from datetime import datetime
from pathlib import Path

import pandas as pd
from borsdata_client import BorsdataClient

MARKET_IDS = [1, 2, 3]               # Börsdata's market ids, here Nasdaq Stockholm Large, Mid and Small Cap
START = "2016-01-01"                 # the first day of the prices (Börsdata gives at most 20 years)
FOLDER = Path.home() / "Downloads"   # change this to the folder for the CSV file

# Step 1. Connect with your API key, read from the environment variable BORSDATA_API_KEY
client = BorsdataClient(api_key=os.environ["BORSDATA_API_KEY"])

# Step 2. Börsdata's markets with their ids (pick yours for MARKET_IDS), and the common shares listed today on
# MARKET_IDS (instrument type 0)
try:
    markets = pd.DataFrame(market.model_dump() for market in client.get_markets())
    instruments = pd.DataFrame(instrument.model_dump() for instrument in client.get_instruments())
except Exception as error:   # an error message would show the request address, which holds the API key
    raise RuntimeError(str(error).replace(client.api_key, "[API key]")) from None
print(markets[["id", "name", "exchange_name"]].to_string(index=False))
stocks = instruments[instruments["market_id"].isin(MARKET_IDS) & instruments["instrument_type"].eq(0)]

# Step 3. Daily prices, one request per stock. The client waits and tries again when Börsdata's limit of
# 100 requests in 10 seconds is reached
rows, failed = [], []
for ins_id in stocks["ins_id"]:
    try:
        bars = client.get_stock_prices(instrument_id=ins_id, from_date=datetime.fromisoformat(START),
                                       to_date=datetime.now(), max_count=20)   # 20 years, the most
    except Exception as error:
        message = str(error).replace(client.api_key, "[API key]")   # the key is part of the request address
        failed.append({"ins_id": ins_id, "error": message[:200]})
        continue
    rows += [bar.model_dump() | {"ins_id": ins_id} for bar in bars]

# Step 4. The failed stocks, if any, in a second CSV file
FOLDER.mkdir(parents=True, exist_ok=True)
failed_file = FOLDER / "borsdata_prices_failed.csv"
if failed:
    pd.DataFrame(failed).to_csv(failed_file, index=False)
else:
    failed_file.unlink(missing_ok=True)   # the list of an earlier run
assert rows, ("No prices came back. Check the API key, MARKET_IDS and the failed stocks file. "
              "No new data file was saved, so an earlier file may still be there.")

# Step 5. Long format, one row per stock and trading day, with the ticker, name, ISIN and currency, saved as one
# CSV file
labels = {"d": "date", "o": "open", "h": "high", "l": "low", "c": "close", "v": "volume"}
prices = (pd.DataFrame(rows).rename(columns=labels)
          .merge(stocks[["ins_id", "ticker", "name", "isin", "stock_price_currency"]], on="ins_id")
          .rename(columns={"stock_price_currency": "currency"}))
prices = prices[["date", "ins_id", "ticker", "name", "isin", "currency", "open", "high", "low", "close", "volume"]]
prices.sort_values(["ticker", "date"]).to_csv(FOLDER / "borsdata_prices.csv", index=False)
print(len(prices), "rows saved,", len(failed), "stocks failed")

Full post: Börsdata API in Python: download prices, reports and ratios

Company reports

One row per stock and report, with variables such as the revenue, the earnings per share and the total equity, and the publication date (report_date). period is 1 to 4 for quarters and 5 for full years. Amounts are in millions of the report currency (currency), shares in millions, and per-share values in that currency.

Choose these settings in the code:

  • MARKET_IDS, the markets, as in the price script.
  • YEARS and QUARTERS, the most annual and quarterly reports per stock, at most 20 and 40.
  • BORSDATA_API_KEY, your API key.
  • FOLDER, the output folder.
import os
from pathlib import Path

import pandas as pd
from borsdata_client import BorsdataClient
from borsdata_client.models import ReportsArrayResp

MARKET_IDS = [1, 2, 3]               # Börsdata's market ids, here Nasdaq Stockholm Large, Mid and Small Cap
YEARS, QUARTERS = 20, 40             # the most annual and quarterly reports per stock (at most 20 and 40)
FOLDER = Path.home() / "Downloads"   # change this to the folder for the CSV file

# Step 1. Connect with your API key, read from the environment variable BORSDATA_API_KEY
client = BorsdataClient(api_key=os.environ["BORSDATA_API_KEY"])

# Step 2. The common shares listed today on MARKET_IDS (instrument type 0)
try:
    instruments = pd.DataFrame(instrument.model_dump() for instrument in client.get_instruments())
except Exception as error:   # an error message would show the request address, which holds the API key
    raise RuntimeError(str(error).replace(client.api_key, "[API key]")) from None
stocks = instruments[instruments["market_id"].isin(MARKET_IDS) & instruments["instrument_type"].eq(0)]

# Step 3. The annual and quarterly reports, 50 stocks per request. The client's get_reports_batch() sends the
# number of quarters under a name the API ignores, so the code calls Börsdata's reports endpoint directly.
# original 1 keeps each company's report currency, which the column currency names
rows, failed = [], []
ids = stocks["ins_id"].tolist()
for first in range(0, len(ids), 50):
    try:
        response = client._get("/instruments/reports", {"instList": ",".join(map(str, ids[first:first + 50])),
                                                        "maxYearCount": str(YEARS), "maxR12QCount": str(QUARTERS),
                                                        "original": "1"})
        items = ReportsArrayResp(**response).report_list or []
    except Exception as error:
        message = str(error).replace(client.api_key, "[API key]")   # the key is part of the request address
        failed.append({"first_ins_id": ids[first], "error": message[:200]})
        continue
    for item in items:
        if item.error:                       # Börsdata can refuse one stock and still answer for the others
            failed.append({"ins_id": item.instrument, "error": item.error})
            continue
        for report_type, reports in [("annual", item.reports_year or []), ("quarterly", item.reports_quarter or [])]:
            rows += [{"ins_id": item.instrument, "report_type": report_type} | report.model_dump() for report in reports]

# Step 4. The failures, if any, in a second CSV file
FOLDER.mkdir(parents=True, exist_ok=True)
failed_file = FOLDER / "borsdata_reports_failed.csv"
if failed:
    pd.DataFrame(failed).to_csv(failed_file, index=False)
else:
    failed_file.unlink(missing_ok=True)   # the list of an earlier run
assert rows, ("No reports came back. Check the API key, MARKET_IDS and the failures file. "
              "No new data file was saved, so an earlier file may still be there.")

# Step 5. Long format, one row per stock and report, with the ticker and name, saved as one CSV file
reports = pd.DataFrame(rows).merge(stocks[["ins_id", "ticker", "name"]], on="ins_id")
reports = reports[["ins_id", "ticker", "name"] + [column for column in reports if column not in ("ins_id", "ticker", "name")]]
reports.sort_values(["ticker", "report_type", "year", "period"]).to_csv(FOLDER / "borsdata_reports.csv", index=False)
print(len(reports), "reports saved for", reports["ins_id"].nunique(), "stocks |", len(failed), "failures")

Full post: Börsdata API in Python: download prices, reports and ratios

Ratios (KPIs)

One row per stock and period. The example takes P/E, P/B, EBIT/EV, P/FCF, return on capital (ROC) and return on equity (ROE) for each fiscal year and adds free cash flow yield, 100 divided by P/FCF. EBIT/EV, the yield, ROC and ROE are in percent, and the rest are multiples. Finished years have period 5, and the latest row can cover the 12 months through the last reported quarter, as for 2026 with period 3 on 26 November 2026. A price ratio of 0 means no price that year, usually before the listing. Börsdata’s KPI table lists the other ratios (KPIs) and each one’s report and price types.

Choose these settings in the code:

  • KPIS, the KPI ids from the printed list, with your variable names.
  • REPORT_TYPE, “year” for fiscal years or “r12” for the 12 months through each quarter.
  • PRICE_TYPE, the price in ratios such as P/E. Here “mean” averages the prices over the period, and some ratios take “high” or “low”.
  • COUNT, the most periods per stock, at most 20 for “year” and 40 for “r12”.
  • MARKET_IDS, the markets, as in the price script.
  • BORSDATA_API_KEY, your API key.
  • FOLDER, the output folder.
import os
from pathlib import Path

import pandas as pd
from borsdata_client import BorsdataClient

MARKET_IDS = [1, 2, 3]               # Börsdata's market ids, here Nasdaq Stockholm Large, Mid and Small Cap
KPIS = {2: "PE", 4: "PB", 17: "EBIT_EV", 76: "P_FCF", 36: "ROC", 33: "ROE"}   # Börsdata's KPI ids and your column names
REPORT_TYPE = "year"                 # "year" for fiscal years, or "r12" for the 12 months up to each quarter
PRICE_TYPE = "mean"                  # the price in price ratios, "mean" (some ratios also take "high" or "low")
COUNT = 20                           # the most periods per stock, at most 20 for "year" and 40 for "r12"
FOLDER = Path.home() / "Downloads"   # change this to the folder for the CSV file

# Step 1. Connect with your API key, read from the environment variable BORSDATA_API_KEY
client = BorsdataClient(api_key=os.environ["BORSDATA_API_KEY"])

# Step 2. Börsdata's ratios (KPIs) with their ids (pick yours for KPIS), and the common shares listed today on
# MARKET_IDS (instrument type 0)
try:
    kpi_list = pd.DataFrame(kpi.model_dump() for kpi in client.get_kpi_metadata())
    instruments = pd.DataFrame(instrument.model_dump() for instrument in client.get_instruments())
except Exception as error:   # an error message would show the request address, which holds the API key
    raise RuntimeError(str(error).replace(client.api_key, "[API key]")) from None
print(kpi_list[["kpi_id", "name_en", "format"]].to_string(index=False))   # format "%" means percent
stocks = instruments[instruments["market_id"].isin(MARKET_IDS) & instruments["instrument_type"].eq(0)]

# Step 3. Each ratio's history, 50 stocks per request. A refused request or stock goes to a list of failures,
# with the API key removed from the message
rows, failed = [], []
ids = stocks["ins_id"].tolist()
for kpi_id, name in KPIS.items():
    for first in range(0, len(ids), 50):
        try:
            answer = client.get_kpi_history_batch(ids[first:first + 50], kpi_id, REPORT_TYPE, PRICE_TYPE,
                                                  max_count=COUNT)
        except Exception as error:
            message = str(error).replace(client.api_key, "[API key]")   # the key is part of the request address
            failed.append({"kpi": name, "first_ins_id": ids[first], "error": message[:200]})
            continue
        for item in answer.kpis_list or []:
            if item.error:                   # Börsdata can refuse one stock and still answer for the others
                failed.append({"kpi": name, "ins_id": item.instrument, "error": item.error})
                continue
            rows += [{"ins_id": item.instrument, "year": value.y, "period": value.p, "kpi": name, "value": value.v}
                     for value in item.values or []]

# Step 4. The failures, if any, in a second CSV file
FOLDER.mkdir(parents=True, exist_ok=True)
failed_file = FOLDER / "borsdata_ratios_failed.csv"
if failed:
    pd.DataFrame(failed).to_csv(failed_file, index=False)
else:
    failed_file.unlink(missing_ok=True)   # the list of an earlier run
assert rows, ("No ratios came back. Check the API key, MARKET_IDS, KPIS and the failures file. "
              "No new data file was saved, so an earlier file may still be there.")

# Step 5. One row per stock and period, one column per ratio, with the ticker and name, plus free cash flow yield,
# saved as one CSV file
ratios = (pd.DataFrame(rows).pivot(index=["ins_id", "year", "period"], columns="kpi", values="value").reset_index()
          .merge(stocks[["ins_id", "ticker", "name"]], on="ins_id"))
ratios = ratios.reindex(columns=["ins_id", "ticker", "name", "year", "period"] + list(KPIS.values()))
if "P_FCF" in ratios:   # free cash flow yield in percent, 100 divided by P/FCF, empty where P/FCF is 0 (no price)
    ratios["FCF_YIELD"] = (100 / ratios["P_FCF"]).where(ratios["P_FCF"] != 0)
ratios.sort_values(["ticker", "year", "period"]).to_csv(FOLDER / f"borsdata_ratios_{REPORT_TYPE}.csv", index=False)
print(len(ratios), "rows saved,", len(failed), "failures")

Full post: Börsdata API in Python: download prices, reports and ratios