Skip to content

Python quickstart

Indian stock market data in Python: DalalOS REST quickstart

This guide fetches a quote, quarterly financials, the shareholding pattern and a year of prices for one NSE stock with Python requests, then loads the prices into pandas. It uses the DalalOS REST API at https://mcp.dalalos.in/v1.

There is no official Python package. Everything below is plain HTTP, so it also works with httpx or aiohttp.

1. Create an API key

Sign in and create a key at /dashboard/keys. It starts with isk_live_ and is shown once. Store it in an environment variable and keep it on the server.

shell
export DALALOS_API_KEY="isk_live_…"
pip install requests pandas

REST needs a paid plan

REST access comes with paid plans that include it; see pricing. Without it, every call answers 403 with surface_not_in_plan. The same data is available over MCP on every plan.

2. A small client with error handling

Every response is a JSON envelope. A success has status: "success" and the payload in data. An error has status: "error", a message in error and a reason_code. This helper returns the envelope, waits on 429 and raises on anything else.

dalalos_client.py
import os
import time

import requests

API_BASE = "https://mcp.dalalos.in/v1"

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['DALALOS_API_KEY']}"


class DalalOSError(Exception):
    def __init__(self, http_status, reason_code, message):
        super().__init__(f"{http_status} {reason_code}: {message}")
        self.http_status = http_status
        self.reason_code = reason_code


def get(path, **params):
    """GET a /v1 route and return the whole envelope, or raise DalalOSError."""
    for _ in range(3):
        resp = session.get(f"{API_BASE}{path}", params=params, timeout=30)
        if resp.status_code == 429:
            # rate_limited or concurrency_limited: wait as long as the server asks
            time.sleep(int(resp.headers.get("Retry-After", "1")))
            continue
        try:
            body = resp.json()
        except ValueError:
            resp.raise_for_status()  # a non-JSON error page, e.g. a 502 from a proxy
            raise
        if body.get("status") != "success":
            raise DalalOSError(resp.status_code, body.get("reason_code"), body.get("error"))
        return body
    raise DalalOSError(429, "rate_limited", "still rate limited after 3 tries")

3. Fetch a quote, financials and shareholding

A company is identified by NSE symbol, ISIN or BSE code in the path. Money values are in rupees, ratios such as dividend_yield are fractions, and holdings are percentages.

python
quote = get("/stocks/INFY/quote")
q = quote["data"]
print(quote["as_of"], q["price"], q["pe"], q["market_cap"])

fin = get("/stocks/INFY/financials", period_type="quarterly", limit=4)
for p in fin["data"]["periods"]:
    print(p["fiscal_label"], p["income"]["revenue"], p["income"]["net_income_owners"])

shp = get("/stocks/INFY/shareholding", limit=4)
for p in shp["data"]["periods"]:
    print(p["period_end"], p["promoter_pct"], p["fii_pct"], p["dii_pct"])
GET /v1/stocks/INFY/quote (trimmed)
{
  "status": "success",
  "data": {
    "isin": "INE009A01021",
    "nse_symbol": "INFY",
    "price": 1130.0,
    "change": -15.1,
    "volume": 7145680,
    "market_cap": 4578760000000.0,
    "pe": 14.9293,
    "pb": 4.6214,
    "week52_high": 1728.0,
    "week52_low": 980.4,
    "deliv_pct": 53.56,
    "dividend_yield": 0.0451
  },
  "source": "nse-bhavcopy",
  "cached_at": "2026-11-17T14:45:02+00:00",
  "as_of": "2026-11-17",
  "stale": false,
  "error": null,
  "reason_code": null,
  "freshness": {
    "price": { "basis": "end_of_day", "session": "2026-11-17", "status": "latest_session" },
    "reason_text": "Closing price for Tuesday 17 Nov 2026, the latest trading session on file. This is not a live price."
  }
}

A real response, run on 17 Nov 2026 and trimmed. market_cap is in rupees.

Quarterly financials carry no cash-flow statement, because Indian quarterly filings do not include one. Pass period_type="annual" for cash flow. On 17 Nov 2026 the latest INFY quarter returned was Q2 FY27, filed on 23 Oct 2026, with promoter holding of 13.9% for the quarter ended 30 Sep 2026.

4. Price history into a pandas DataFrame

price-history returns end-of-day bars with open, high, low, close, volume, delivery and 50- and 200-day averages. Prices are as traded unless you pass adjusted="true", which rescales them for splits and bonuses.

python
import pandas as pd

hist = get("/stocks/INFY/price-history", days=365, interval="daily")
df = pd.DataFrame(hist["data"]["bars"])
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")[["open", "high", "low", "close", "volume", "deliv_pct"]]

print(df.tail())
print(df["close"].pct_change().describe())
data.bars (trimmed)
"bars": [
  {"date": "2026-11-16", "open": 1150.0, "high": 1159.9, "low": 1138.2, "close": 1145.1,
   "volume": 4852092, "deliv_qty": 2152110, "deliv_pct": 44.35, "vwap": 1145.2346,
   "sma_50": 1090.379, "sma_200": 1188.72425},
  {"date": "2026-11-17", "open": 1141.0, "high": 1145.0, "low": 1125.3, "close": 1130.0,
   "volume": 7145680, "deliv_qty": 3826909, "deliv_pct": 53.56, "vwap": 1134.0909,
   "sma_50": 1090.373, "sma_200": 1186.02025}
]

Real bars for INFY, run on 17 Nov 2026 and trimmed to two days. sma_50 and sma_200 use split- and bonus-adjusted closes even when adjusted is false.

5. Read cached_at, as_of and stale

  • as_of is the trading day or period end the figures describe.
  • cached_at is when DalalOS stored the data.
  • stale is an envelope flag. On some routes it turns true for reasons other than an old figure.
  • freshness, on quote, financials, shareholding and screen responses, says whether you have the latest session or period and gives a reason_text.

On 17 Nov 2026 the INFY financials response came back with stale: true, while its freshness block said the data was the latest filed quarter and that the exchange results feed showed no newer results. Check the freshness block before you discard a response.

python
def describe_freshness(body):
    fresh = body.get("freshness") or {}
    print("as_of:    ", body.get("as_of"))       # the trading day or period the figures describe
    print("cached_at:", body.get("cached_at"))   # when DalalOS stored this data
    print("stale:    ", body.get("stale"))
    if fresh.get("reason_text"):
        print("why:      ", fresh["reason_text"])


describe_freshness(get("/stocks/INFY/financials", limit=1))

The status page shows when each refresh job last ran.

6. Status codes

REST error status codes and reason codes
HTTPreason_codeWhat to do
400bad_requestA parameter is wrong, for example a percentage passed where the API expects a fraction. The error names the problem.
401unauthorized, invalid_tokenThe key is missing, mistyped or revoked.
402quota_exceededYour plan's quota is used up until it resets. Retrying will not help.
403surface_not_in_planYour plan does not include REST. See pricing.
404not_foundNo company matches the symbol, ISIN or BSE code you sent.
429rate_limited, concurrency_limitedToo many requests or too many at once. Wait for Retry-After seconds.

A valid request with nothing to return answers 200 with status: "success" and reason_code: "no_data", so check data before you index into it.

7. Paging and limits

Most list routes take a limit and return a truncated flag or a note when rows were cut. For a date-range route, ask again from the last date returned.

Per-route limits
RouteLimits
/v1/screenlimit 1 to 100 rows; no offset
/v1/stocks/{q}/price-historydays 1 to 1825; a daily series longer than 750 bars comes back weekly
/v1/stocks/{q}/shareholdinglimit up to 12 quarters
/v1/calendarfrom and to required, at most 180 days apart; limit up to 2000
/v1/results-calendardays 1 to 90; limit up to 200
/v1/iposlimit up to 500
/v1/quotesup to 20 symbols per call

Next steps

Pick a dataset on the data API hub, such as screening, the results calendar or macro data. The REST API reference lists every route. All data is raw disclosed figures and ratios computed by fixed formulas, not investment advice.

FAQ

Common questions

Is there an official DalalOS Python package?
No. Call the REST API with requests or httpx as shown on this page.
Are the prices live?
No. Prices are end-of-day closes from the NSE and BSE bhavcopy. as_of gives the trading day.
Why is stale true when the data is the latest quarter?
The envelope's stale flag can be set for reasons other than an old figure. Read the freshness block: its status and reason_text say whether you have the latest session or period and why the flag is set.
Where do I find every route and its parameters?
The REST API reference lists every /v1 route and the MCP tool it maps to. Each tool page lists the parameters and output fields.
Do I need a paid plan for REST?
Yes, a plan that includes REST. Without it the API answers 403 surface_not_in_plan. MCP works on every plan.

KEEP EXPLORING

Connect your AI to Indian stock market data

Sign in to DalalOS and connect your AI in one line of config. Free to start; paid plans when you need more.

Account holders get product-update emails about every two weeks. Turn them off any time.