dalalos 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dalalos/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """Python client for DalalOS: NSE/BSE company financials, shareholding, filings,
2
+ corporate actions, insider trades, FII/DII flows and end-of-day prices.
3
+
4
+ from dalalos import Client
5
+ c = Client() # reads DALALOS_API_KEY
6
+ c.quote("RELIANCE")
7
+ """
8
+
9
+ from ._version import __version__
10
+ from .client import DEFAULT_BASE_URL, Client
11
+ from .errors import (
12
+ AuthenticationError,
13
+ BadRequestError,
14
+ ConflictError,
15
+ DalalOSError,
16
+ NotFoundError,
17
+ PermissionDeniedError,
18
+ QuotaExceededError,
19
+ RateLimitError,
20
+ ServerError,
21
+ )
22
+ from .response import Response, to_frame
23
+
24
+ __all__ = [
25
+ "__version__",
26
+ "Client",
27
+ "DEFAULT_BASE_URL",
28
+ "Response",
29
+ "to_frame",
30
+ "DalalOSError",
31
+ "BadRequestError",
32
+ "AuthenticationError",
33
+ "QuotaExceededError",
34
+ "PermissionDeniedError",
35
+ "NotFoundError",
36
+ "ConflictError",
37
+ "RateLimitError",
38
+ "ServerError",
39
+ ]
dalalos/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
dalalos/client.py ADDED
@@ -0,0 +1,496 @@
1
+ """HTTP client for the DalalOS REST API (https://mcp.dalalos.in/v1).
2
+
3
+ Each method maps to one REST route and takes that route's own parameter
4
+ names. Python reserves ``from``, so date ranges take ``from_`` and send it as
5
+ ``from``. Every method returns a :class:`~dalalos.response.Response`: the
6
+ JSON body as the API sent it.
7
+ """
8
+
9
+ import os
10
+ import time
11
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Union
12
+
13
+ import requests
14
+
15
+ from ._version import __version__
16
+ from .errors import DalalOSError, RateLimitError, error_for_status, parse_retry_after
17
+ from .response import Response, extract_rows
18
+
19
+ DEFAULT_BASE_URL = "https://mcp.dalalos.in/v1"
20
+ KEYS_URL = "https://dalalos.in/dashboard/keys"
21
+
22
+ Symbols = Union[str, Sequence[str]]
23
+
24
+
25
+ class Client:
26
+ """DalalOS REST client.
27
+
28
+ >>> from dalalos import Client
29
+ >>> c = Client() # reads DALALOS_API_KEY
30
+ >>> c.quote("RELIANCE")["data"]["price"]
31
+
32
+ ``q`` arguments accept an NSE symbol, an ISIN or a BSE code. Use the ISIN
33
+ or BSE code for BSE-only companies, whose ``nse_symbol`` is empty.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ api_key: Optional[str] = None,
39
+ *,
40
+ base_url: Optional[str] = None,
41
+ timeout: float = 30.0,
42
+ max_retries: int = 2,
43
+ max_retry_wait: float = 60.0,
44
+ session: Optional[requests.Session] = None,
45
+ ) -> None:
46
+ key = api_key if api_key is not None else os.environ.get("DALALOS_API_KEY")
47
+ if not key:
48
+ raise DalalOSError(
49
+ f"No API key. Pass api_key= or set DALALOS_API_KEY. Create a free key at {KEYS_URL}"
50
+ )
51
+ self.base_url = (base_url or os.environ.get("DALALOS_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
52
+ self.timeout = timeout
53
+ self.max_retries = max(0, int(max_retries))
54
+ self.max_retry_wait = max_retry_wait
55
+ self.session = session if session is not None else requests.Session()
56
+ self.session.headers["Authorization"] = f"Bearer {key}"
57
+ self.session.headers.setdefault("Accept", "application/json")
58
+ self.session.headers["User-Agent"] = f"dalalos-python/{__version__}"
59
+
60
+ def __repr__(self) -> str:
61
+ return f"Client(base_url={self.base_url!r})"
62
+
63
+ def close(self) -> None:
64
+ self.session.close()
65
+
66
+ def __enter__(self) -> "Client":
67
+ return self
68
+
69
+ def __exit__(self, *exc: Any) -> None:
70
+ self.close()
71
+
72
+ # ------------------------------------------------------------------ core
73
+
74
+ def get(self, path: str, **params: Any) -> Response:
75
+ """GET any /v1 route. Use for routes without a named method."""
76
+ return self._request("GET", path, params=params)
77
+
78
+ def post(self, path: str, body: Optional[Mapping[str, Any]] = None) -> Response:
79
+ """POST JSON to any /v1 route."""
80
+ return self._request("POST", path, json_body=dict(body or {}))
81
+
82
+ def _request(
83
+ self,
84
+ method: str,
85
+ path: str,
86
+ params: Optional[Mapping[str, Any]] = None,
87
+ json_body: Optional[Mapping[str, Any]] = None,
88
+ ) -> Response:
89
+ url = self.base_url + "/" + path.lstrip("/")
90
+ query = _clean_params(params or {})
91
+ attempt = 0
92
+ while True:
93
+ resp = self.session.request(method, url, params=query, json=json_body, timeout=self.timeout)
94
+ if resp.status_code == 429 and attempt < self.max_retries:
95
+ wait = parse_retry_after(resp.headers.get("Retry-After"))
96
+ wait = 1.0 if wait is None else wait
97
+ if wait <= self.max_retry_wait:
98
+ attempt += 1
99
+ time.sleep(wait)
100
+ continue
101
+ return self._handle(resp)
102
+
103
+ @staticmethod
104
+ def _handle(resp: requests.Response) -> Response:
105
+ try:
106
+ body = resp.json()
107
+ except ValueError:
108
+ body = None
109
+ headers = dict(resp.headers)
110
+ if resp.status_code >= 400:
111
+ message = None
112
+ reason = None
113
+ if isinstance(body, dict):
114
+ message = body.get("error") or body.get("message") or body.get("detail")
115
+ reason = body.get("reason_code")
116
+ if not isinstance(message, str):
117
+ message = (resp.text or resp.reason or "request failed").strip()[:500]
118
+ cls = error_for_status(resp.status_code)
119
+ raise cls(message, status=resp.status_code, reason_code=reason,
120
+ body=body if isinstance(body, dict) else None, headers=headers)
121
+ if not isinstance(body, dict):
122
+ raise DalalOSError("Response was not a JSON object", status=resp.status_code, headers=headers)
123
+ return Response(body, headers=headers, status_code=resp.status_code)
124
+
125
+ def _paginate(self, path: str, params: Dict[str, Any], row_key: str) -> Iterator[Dict[str, Any]]:
126
+ params = dict(params)
127
+ seen = set()
128
+ while True:
129
+ page = self.get(path, **params)
130
+ data = page.get("data")
131
+ rows = data.get(row_key) if isinstance(data, dict) else None
132
+ for row in rows or []:
133
+ yield row
134
+ cursor = _lookup(page, "next_cursor")
135
+ has_more = _lookup(page, "has_more")
136
+ if not cursor or has_more is False or cursor in seen:
137
+ return
138
+ seen.add(cursor)
139
+ params["cursor"] = cursor
140
+
141
+ # ------------------------------------------------------------ discovery
142
+
143
+ def search(self, q: str, limit: Optional[int] = None) -> Response:
144
+ """``GET /search``: securities by name, NSE symbol, BSE code or ISIN."""
145
+ return self.get("/search", q=q, limit=limit)
146
+
147
+ def resolve(self, q: str) -> Optional[Dict[str, Any]]:
148
+ """First match from ``/search`` as one dict (isin, nse_symbol, bse_code, name, ...), or None."""
149
+ rows = extract_rows(self.search(q, limit=1).get("data"))
150
+ return rows[0] if rows else None
151
+
152
+ def profile(self, q: str) -> Response:
153
+ """``GET /stocks/{q}/profile``: company profile."""
154
+ return self.get(f"/stocks/{_seg(q)}/profile")
155
+
156
+ # --------------------------------------------------------------- prices
157
+
158
+ def quote(self, q: str) -> Response:
159
+ """``GET /stocks/{q}/quote``: latest end-of-day quote."""
160
+ return self.get(f"/stocks/{_seg(q)}/quote")
161
+
162
+ def quotes(self, symbols: Symbols) -> Response:
163
+ """``GET /quotes``: end-of-day quotes for up to 20 symbols."""
164
+ return self.get("/quotes", symbols=_join(symbols))
165
+
166
+ def price_history(
167
+ self,
168
+ q: str,
169
+ days: Optional[int] = None,
170
+ adjusted: Optional[bool] = None,
171
+ interval: Optional[str] = None,
172
+ ) -> Response:
173
+ """``GET /stocks/{q}/price-history``: OHLCV bars.
174
+
175
+ ``days`` 1..1825, ``interval`` daily | weekly | monthly. At most 750
176
+ bars come back; a longer daily window is returned as weekly bars.
177
+ """
178
+ return self.get(f"/stocks/{_seg(q)}/price-history", days=days, adjusted=adjusted, interval=interval)
179
+
180
+ # ----------------------------------------------------------- financials
181
+
182
+ def financials(
183
+ self,
184
+ q: str,
185
+ period_type: Optional[str] = None,
186
+ limit: Optional[int] = None,
187
+ from_fy: Optional[int] = None,
188
+ to_fy: Optional[int] = None,
189
+ from_: Optional[str] = None,
190
+ to: Optional[str] = None,
191
+ statement_type: Optional[str] = None,
192
+ **params: Any,
193
+ ) -> Response:
194
+ """``GET /stocks/{q}/financials``: P&L, balance sheet, TTM and margins.
195
+
196
+ ``period_type`` quarterly (default) | annual | half_yearly.
197
+ ``from_fy``/``to_fy`` are Indian fiscal years ending March (2024 is
198
+ FY2023-24), at most a 10-year span. How far back data goes depends on
199
+ the company. ``statement_type`` auto | consolidated | standalone.
200
+ """
201
+ return self.get(
202
+ f"/stocks/{_seg(q)}/financials",
203
+ period_type=period_type, limit=limit, from_fy=from_fy, to_fy=to_fy,
204
+ **{"from": from_, "to": to}, statement_type=statement_type, **params,
205
+ )
206
+
207
+ def annual_financials(self, q: str, **kwargs: Any) -> Response:
208
+ """``financials`` with ``period_type="annual"``."""
209
+ return self.financials(q, period_type="annual", **kwargs)
210
+
211
+ def quarterly_financials(self, q: str, **kwargs: Any) -> Response:
212
+ """``financials`` with ``period_type="quarterly"``."""
213
+ return self.financials(q, period_type="quarterly", **kwargs)
214
+
215
+ def financial_versions(
216
+ self,
217
+ q: str,
218
+ period_type: Optional[str] = None,
219
+ limit: Optional[int] = None,
220
+ statement_type: Optional[str] = None,
221
+ period_end: Optional[str] = None,
222
+ ) -> Response:
223
+ """``GET /stocks/{q}/financials/versions``: every stored version of a filing."""
224
+ return self.get(
225
+ f"/stocks/{_seg(q)}/financials/versions",
226
+ period_type=period_type, limit=limit, statement_type=statement_type, period_end=period_end,
227
+ )
228
+
229
+ def financial_changes(
230
+ self,
231
+ since: Optional[str] = None,
232
+ limit: Optional[int] = None,
233
+ revision_kind: Optional[str] = None,
234
+ after_id: Optional[int] = None,
235
+ ) -> Response:
236
+ """``GET /changes/financials``: filings stored since ``since`` (UTC ISO, at most 30 days back)."""
237
+ return self.get("/changes/financials", since=since, limit=limit,
238
+ revision_kind=revision_kind, after_id=after_id)
239
+
240
+ def iter_financial_changes(
241
+ self,
242
+ since: Optional[str] = None,
243
+ limit: Optional[int] = None,
244
+ revision_kind: Optional[str] = None,
245
+ ) -> Iterator[Dict[str, Any]]:
246
+ """Yield every change, following ``next_since``/``next_after_id`` while ``has_more``."""
247
+ after_id: Optional[int] = None
248
+ seen = set()
249
+ while True:
250
+ page = self.financial_changes(since=since, limit=limit, revision_kind=revision_kind, after_id=after_id)
251
+ data = page.get("data") or {}
252
+ for row in data.get("changes") or []:
253
+ yield row
254
+ if not data.get("has_more"):
255
+ return
256
+ marker = (data.get("next_since"), data.get("next_after_id"))
257
+ if marker in seen or marker == (None, None):
258
+ return
259
+ seen.add(marker)
260
+ since, after_id = marker
261
+
262
+ # -------------------------------------------------------------- screens
263
+
264
+ def ratios(self) -> Response:
265
+ """``GET /ratios``: the metric registry (ids, labels, units, filterable, sortable)."""
266
+ return self.get("/ratios")
267
+
268
+ def screen(
269
+ self,
270
+ sort_by: Optional[str] = None,
271
+ order: Optional[str] = None,
272
+ limit: Optional[int] = None,
273
+ **filters: Any,
274
+ ) -> Response:
275
+ """``GET /screen``: filter the universe.
276
+
277
+ Any other keyword is a filter, for example ``pe_max=20``,
278
+ ``roe_min=0.15`` (fractions, not percentages) or
279
+ ``sector="Information Technology"``. An unknown key returns a 400
280
+ listing every accepted key. ``limit`` 1..100.
281
+ """
282
+ return self.get("/screen", sort_by=sort_by, order=order, limit=limit, **filters)
283
+
284
+ def screen_query(
285
+ self,
286
+ query: str,
287
+ dialect: Optional[str] = None,
288
+ sort_by: Optional[str] = None,
289
+ order: Optional[str] = None,
290
+ limit: Optional[int] = None,
291
+ snapshot_id: Optional[str] = None,
292
+ **body: Any,
293
+ ) -> Response:
294
+ """``POST /screen/query``: a Screener.in-style expression.
295
+
296
+ Example: ``"Return on capital employed > 22% AND Market Capitalization > 500"``.
297
+ ``dialect`` screener (default) | dalalos. Pass the returned
298
+ ``snapshot_id`` to read the next page of the same generation.
299
+ """
300
+ payload = _clean_params({
301
+ "query": query, "dialect": dialect, "sort_by": sort_by, "order": order,
302
+ "limit": limit, "snapshot_id": snapshot_id, **body,
303
+ }, stringify=False)
304
+ return self.post("/screen/query", payload)
305
+
306
+ # ------------------------------------------------------------ ownership
307
+
308
+ def shareholding(
309
+ self,
310
+ q: str,
311
+ limit: Optional[int] = None,
312
+ from_: Optional[str] = None,
313
+ to: Optional[str] = None,
314
+ from_fy: Optional[int] = None,
315
+ to_fy: Optional[int] = None,
316
+ ) -> Response:
317
+ """``GET /stocks/{q}/shareholding``: promoter / FII / DII / public by quarter."""
318
+ return self.get(f"/stocks/{_seg(q)}/shareholding", limit=limit,
319
+ **{"from": from_, "to": to}, from_fy=from_fy, to_fy=to_fy)
320
+
321
+ def pledge_trend(self, q: str, limit: Optional[int] = None) -> Response:
322
+ """``GET /stocks/{q}/pledge-trend``: promoter pledge by quarter."""
323
+ return self.get(f"/stocks/{_seg(q)}/pledge-trend", limit=limit)
324
+
325
+ def insider_trades(
326
+ self,
327
+ symbol: Optional[str] = None,
328
+ days: Optional[int] = None,
329
+ from_: Optional[str] = None,
330
+ to: Optional[str] = None,
331
+ category: Optional[str] = None,
332
+ side: Optional[str] = None,
333
+ min_value_inr: Optional[float] = None,
334
+ include_derivatives: Optional[bool] = None,
335
+ group_by: Optional[str] = None,
336
+ limit: Optional[int] = None,
337
+ ) -> Response:
338
+ """``GET /insider-trades``: SEBI PIT disclosures, market-wide or for one company.
339
+
340
+ ``category`` promoters (default) | directors_kmp | designated | relatives | all.
341
+ ``side`` trades (default) | buy | sell | pledge | all.
342
+ """
343
+ return self.get(
344
+ "/insider-trades", symbol=symbol, days=days, **{"from": from_, "to": to},
345
+ category=category, side=side, min_value_inr=min_value_inr,
346
+ include_derivatives=include_derivatives, group_by=group_by, limit=limit,
347
+ )
348
+
349
+ def bulk_block_deals(
350
+ self,
351
+ q: str,
352
+ deal_type: Optional[str] = None,
353
+ exchange: Optional[str] = None,
354
+ days: Optional[int] = None,
355
+ from_date: Optional[str] = None,
356
+ to_date: Optional[str] = None,
357
+ cursor: Optional[str] = None,
358
+ limit: Optional[int] = None,
359
+ ) -> Response:
360
+ """``GET /stocks/{q}/bulk-block-deals``. ``exchange`` nse (default) | bse | all."""
361
+ return self.get(
362
+ f"/stocks/{_seg(q)}/bulk-block-deals", deal_type=deal_type, exchange=exchange, days=days,
363
+ from_date=from_date, to_date=to_date, cursor=cursor, limit=limit,
364
+ )
365
+
366
+ def iter_bulk_block_deals(self, q: str, **kwargs: Any) -> Iterator[Dict[str, Any]]:
367
+ """Yield every deal in the window, following ``next_cursor``."""
368
+ return self._paginate(f"/stocks/{_seg(q)}/bulk-block-deals", _range_params(kwargs), "deals")
369
+
370
+ def fii_dii(self, from_: Optional[str] = None, to: Optional[str] = None,
371
+ segment: Optional[str] = None) -> Response:
372
+ """``GET /market-fii-dii-flow``: daily FII/DII net cash flow (Rs crore).
373
+
374
+ A window spans at most 366 days; data starts 2006-04-04.
375
+ """
376
+ return self.get("/market-fii-dii-flow", **{"from": from_, "to": to}, segment=segment)
377
+
378
+ # ------------------------------------------------------ filings, events
379
+
380
+ def events(
381
+ self,
382
+ q: str,
383
+ days: Optional[int] = None,
384
+ from_: Optional[str] = None,
385
+ to: Optional[str] = None,
386
+ category: Optional[str] = None,
387
+ limit: Optional[int] = None,
388
+ cursor: Optional[str] = None,
389
+ ) -> Response:
390
+ """``GET /stocks/{q}/events``: BSE corporate announcements (Reg-30 filings).
391
+
392
+ Without a range: trailing ``days`` (1..365). A ``from_``/``to`` range
393
+ (up to 10 years) pages with ``cursor``; see :meth:`iter_events`.
394
+ """
395
+ return self.get(f"/stocks/{_seg(q)}/events", days=days, **{"from": from_, "to": to},
396
+ category=category, limit=limit, cursor=cursor)
397
+
398
+ announcements = events
399
+
400
+ def iter_events(self, q: str, **kwargs: Any) -> Iterator[Dict[str, Any]]:
401
+ """Yield every announcement in the window, following ``meta.next_cursor``."""
402
+ return self._paginate(f"/stocks/{_seg(q)}/events", _range_params(kwargs), "events")
403
+
404
+ iter_announcements = iter_events
405
+
406
+ def documents(
407
+ self,
408
+ q: str,
409
+ days: Optional[int] = None,
410
+ from_: Optional[str] = None,
411
+ to: Optional[str] = None,
412
+ document_type: Optional[str] = None,
413
+ limit: Optional[int] = None,
414
+ cursor: Optional[str] = None,
415
+ ) -> Response:
416
+ """``GET /stocks/{q}/documents``: filings with a document (results, annual reports,
417
+ presentations, call transcripts, ...) and their original ``source_url``."""
418
+ return self.get(f"/stocks/{_seg(q)}/documents", days=days, **{"from": from_, "to": to},
419
+ document_type=document_type, limit=limit, cursor=cursor)
420
+
421
+ def iter_documents(self, q: str, **kwargs: Any) -> Iterator[Dict[str, Any]]:
422
+ """Yield every document in the window, following ``meta.next_cursor``."""
423
+ return self._paginate(f"/stocks/{_seg(q)}/documents", _range_params(kwargs), "documents")
424
+
425
+ def corporate_actions(
426
+ self,
427
+ q: str,
428
+ years: Optional[int] = None,
429
+ from_: Optional[str] = None,
430
+ to: Optional[str] = None,
431
+ types: Optional[Symbols] = None,
432
+ ) -> Response:
433
+ """``GET /stocks/{q}/corporate-actions``: splits, bonuses, dividends, buybacks, ..."""
434
+ return self.get(f"/stocks/{_seg(q)}/corporate-actions", years=years,
435
+ **{"from": from_, "to": to}, types=_join(types) if types else None)
436
+
437
+ def dividends(self, q: str, years: Optional[int] = None,
438
+ from_: Optional[str] = None, to: Optional[str] = None) -> Response:
439
+ """``GET /stocks/{q}/dividends``: dividend history."""
440
+ return self.get(f"/stocks/{_seg(q)}/dividends", years=years, **{"from": from_, "to": to})
441
+
442
+ # ---------------------------------------------------------------- misc
443
+
444
+ def freshness(self) -> Response:
445
+ """``GET /freshness``: when each dataset was last refreshed."""
446
+ return self.get("/freshness")
447
+
448
+
449
+ # ---------------------------------------------------------------- helpers
450
+
451
+ def _seg(value: str) -> str:
452
+ from urllib.parse import quote
453
+
454
+ value = str(value).strip()
455
+ if not value:
456
+ raise ValueError("A symbol, ISIN or BSE code is required")
457
+ return quote(value, safe="")
458
+
459
+
460
+ def _join(symbols: Optional[Symbols]) -> Optional[str]:
461
+ if symbols is None:
462
+ return None
463
+ if isinstance(symbols, str):
464
+ return symbols
465
+ return ",".join(str(s).strip() for s in symbols)
466
+
467
+
468
+ def _clean_params(params: Mapping[str, Any], stringify: bool = True) -> Dict[str, Any]:
469
+ out: Dict[str, Any] = {}
470
+ for key, value in params.items():
471
+ if value is None:
472
+ continue
473
+ if key.endswith("_") and key[:-1] in ("from", "type"):
474
+ key = key[:-1]
475
+ if stringify and isinstance(value, bool):
476
+ value = "true" if value else "false"
477
+ elif stringify and isinstance(value, (list, tuple)):
478
+ value = ",".join(str(v) for v in value)
479
+ out[key] = value
480
+ return out
481
+
482
+
483
+ def _range_params(kwargs: Dict[str, Any]) -> Dict[str, Any]:
484
+ kwargs = dict(kwargs)
485
+ kwargs.pop("cursor", None)
486
+ return _clean_params(kwargs, stringify=False)
487
+
488
+
489
+ def _lookup(body: Mapping[str, Any], key: str) -> Any:
490
+ for container in (body.get("data"), body.get("meta"), body):
491
+ if isinstance(container, dict) and key in container:
492
+ return container[key]
493
+ return None
494
+
495
+
496
+ __all__: List[str] = ["Client", "DEFAULT_BASE_URL"]
dalalos/errors.py ADDED
@@ -0,0 +1,127 @@
1
+ """Exceptions raised by the DalalOS client.
2
+
3
+ Every exception carries the HTTP status, the API's ``reason_code`` and its
4
+ ``error`` message, plus the parsed response body when there is one.
5
+ """
6
+
7
+ from typing import Any, Dict, Optional
8
+
9
+
10
+ class DalalOSError(Exception):
11
+ """Base class for every error the client raises."""
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ status: Optional[int] = None,
17
+ reason_code: Optional[str] = None,
18
+ body: Optional[Dict[str, Any]] = None,
19
+ headers: Optional[Dict[str, str]] = None,
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.message = message
23
+ self.status = status
24
+ self.reason_code = reason_code
25
+ self.body = body or {}
26
+ self.headers = dict(headers or {})
27
+
28
+ def __str__(self) -> str:
29
+ parts = []
30
+ if self.status is not None:
31
+ parts.append(str(self.status))
32
+ if self.reason_code:
33
+ parts.append(self.reason_code)
34
+ prefix = " ".join(parts)
35
+ return f"{prefix}: {self.message}" if prefix else self.message
36
+
37
+
38
+ class BadRequestError(DalalOSError):
39
+ """400: a parameter is wrong. The message names the problem."""
40
+
41
+
42
+ class AuthenticationError(DalalOSError):
43
+ """401: the API key is missing, mistyped or revoked."""
44
+
45
+
46
+ class QuotaExceededError(DalalOSError):
47
+ """402: the plan's credits are used up, or too low for this call.
48
+
49
+ ``credits_needed`` and ``credits_remaining`` come from the response body
50
+ when the API sends them. Retrying will not help until the quota resets.
51
+ """
52
+
53
+ @property
54
+ def credits_needed(self) -> Optional[int]:
55
+ return _find(self.body, "credits_needed")
56
+
57
+ @property
58
+ def credits_remaining(self) -> Optional[int]:
59
+ return _find(self.body, "credits_remaining")
60
+
61
+
62
+ class PermissionDeniedError(DalalOSError):
63
+ """403: the plan does not include this surface or route."""
64
+
65
+
66
+ class NotFoundError(DalalOSError):
67
+ """404: no company or resource matches what was sent."""
68
+
69
+
70
+ class ConflictError(DalalOSError):
71
+ """409: for example ``snapshot_expired`` while paging a screen."""
72
+
73
+
74
+ class RateLimitError(DalalOSError):
75
+ """429: too many requests, or too many at once.
76
+
77
+ ``retry_after`` is the ``Retry-After`` header in seconds, when sent.
78
+ """
79
+
80
+ @property
81
+ def retry_after(self) -> Optional[float]:
82
+ return parse_retry_after(self.headers.get("Retry-After") or self.headers.get("retry-after"))
83
+
84
+
85
+ class ServerError(DalalOSError):
86
+ """5xx: the service could not answer. Safe to retry later."""
87
+
88
+
89
+ STATUS_ERRORS = {
90
+ 400: BadRequestError,
91
+ 401: AuthenticationError,
92
+ 402: QuotaExceededError,
93
+ 403: PermissionDeniedError,
94
+ 404: NotFoundError,
95
+ 409: ConflictError,
96
+ 429: RateLimitError,
97
+ }
98
+
99
+
100
+ def error_for_status(status: int):
101
+ if status in STATUS_ERRORS:
102
+ return STATUS_ERRORS[status]
103
+ if status >= 500:
104
+ return ServerError
105
+ return DalalOSError
106
+
107
+
108
+ def parse_retry_after(value: Optional[str]) -> Optional[float]:
109
+ if value is None:
110
+ return None
111
+ try:
112
+ seconds = float(value)
113
+ except (TypeError, ValueError):
114
+ return None
115
+ return max(seconds, 0.0)
116
+
117
+
118
+ def _find(body: Dict[str, Any], key: str) -> Any:
119
+ if not isinstance(body, dict):
120
+ return None
121
+ if key in body:
122
+ return body[key]
123
+ for nested in ("data", "meta"):
124
+ inner = body.get(nested)
125
+ if isinstance(inner, dict) and key in inner:
126
+ return inner[key]
127
+ return None
dalalos/py.typed ADDED
File without changes
dalalos/response.py ADDED
@@ -0,0 +1,106 @@
1
+ """The parsed API response.
2
+
3
+ ``Response`` is a plain ``dict`` holding the JSON body exactly as the API sent
4
+ it (``status``, ``data``, ``source``, ``cached_at``, ``stale``, ``as_of``,
5
+ ``meta`` and so on), so source links and as-of dates are never dropped. It adds
6
+ a few read-only conveniences and ``to_frame()`` for pandas users.
7
+ """
8
+
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ # Keys under ``data`` that hold the row list, in the order they are tried.
12
+ ROW_KEYS = (
13
+ "results",
14
+ "bars",
15
+ "periods",
16
+ "quarters",
17
+ "events",
18
+ "documents",
19
+ "deals",
20
+ "changes",
21
+ "versions",
22
+ "actions",
23
+ "corporate_actions",
24
+ "trades",
25
+ "dividends",
26
+ "metrics",
27
+ "rows",
28
+ "items",
29
+ )
30
+
31
+
32
+ class Response(dict):
33
+ """The JSON body of one API call, unchanged, plus a few helpers."""
34
+
35
+ def __init__(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None, status_code: int = 200):
36
+ super().__init__(body)
37
+ self.headers: Dict[str, str] = dict(headers or {})
38
+ self.status_code = status_code
39
+
40
+ @property
41
+ def data(self) -> Any:
42
+ return self.get("data")
43
+
44
+ @property
45
+ def meta(self) -> Dict[str, Any]:
46
+ meta = self.get("meta")
47
+ return meta if isinstance(meta, dict) else {}
48
+
49
+ @property
50
+ def credits_charged(self) -> Optional[int]:
51
+ """Credits this call used, from ``X-DalalOS-Credits-Charged`` or ``meta``."""
52
+ for name, value in self.headers.items():
53
+ if name.lower() == "x-dalalos-credits-charged":
54
+ try:
55
+ return int(value)
56
+ except (TypeError, ValueError):
57
+ return None
58
+ value = self.meta.get("credits_charged")
59
+ return value if isinstance(value, int) else None
60
+
61
+ def rows(self, key: Optional[str] = None) -> List[Any]:
62
+ """The row list inside ``data`` (for example ``bars`` or ``events``)."""
63
+ return extract_rows(self.get("data"), key)
64
+
65
+ def to_frame(self, key: Optional[str] = None):
66
+ """Return the rows as a pandas DataFrame (needs ``pip install dalalos[pandas]``).
67
+
68
+ Nested objects are flattened with ``pandas.json_normalize``, so a
69
+ financials period gives columns such as ``income.revenue``.
70
+ """
71
+ return to_frame(self, key)
72
+
73
+
74
+ def extract_rows(data: Any, key: Optional[str] = None) -> List[Any]:
75
+ if data is None:
76
+ return []
77
+ if isinstance(data, list):
78
+ return data
79
+ if not isinstance(data, dict):
80
+ return [data]
81
+ if key is not None:
82
+ value = data.get(key)
83
+ if value is None:
84
+ raise KeyError(f"'{key}' is not in data; keys are: {', '.join(sorted(data))}")
85
+ return value if isinstance(value, list) else [value]
86
+ for candidate in ROW_KEYS:
87
+ value = data.get(candidate)
88
+ if isinstance(value, list):
89
+ return value
90
+ for value in data.values():
91
+ if isinstance(value, list) and value and all(isinstance(item, dict) for item in value):
92
+ return value
93
+ return [data]
94
+
95
+
96
+ def to_frame(body: Any, key: Optional[str] = None):
97
+ """Turn a response (or its ``data``) into a pandas DataFrame."""
98
+ try:
99
+ import pandas as pd
100
+ except ImportError as exc: # pragma: no cover - exercised only without pandas
101
+ raise ImportError("to_frame() needs pandas: pip install 'dalalos[pandas]'") from exc
102
+ data = body.get("data") if isinstance(body, dict) and "data" in body else body
103
+ rows = extract_rows(data, key)
104
+ if rows and all(isinstance(row, dict) for row in rows):
105
+ return pd.json_normalize(rows)
106
+ return pd.DataFrame(rows)
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.5
2
+ Name: dalalos
3
+ Version: 0.1.0
4
+ Summary: Python client for DalalOS: NSE/BSE company financials, shareholding, filings, corporate actions, insider trades, FII/DII flows and end-of-day prices
5
+ Project-URL: Homepage, https://dalalos.in
6
+ Project-URL: Documentation, https://dalalos.in/docs/python-quickstart
7
+ Project-URL: Repository, https://github.com/BeyondNoww/DalalOS-Indian-Stock-Research
8
+ Project-URL: Pricing, https://dalalos.in/pricing
9
+ Author: DalalOS
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,bse,financial statements,fundamentals,indian stock market,nse,shareholding
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Topic :: Office/Business :: Financial
26
+ Classifier: Topic :: Office/Business :: Financial :: Investment
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.9
29
+ Requires-Dist: requests>=2.25
30
+ Provides-Extra: pandas
31
+ Requires-Dist: pandas>=1.3; extra == 'pandas'
32
+ Provides-Extra: test
33
+ Requires-Dist: pytest>=7; extra == 'test'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # dalalos
37
+
38
+ Python client for DalalOS: NSE/BSE company financials, shareholding, filings, corporate actions, insider trades, FII/DII flows and end-of-day prices.
39
+
40
+ It wraps the DalalOS REST API (`https://mcp.dalalos.in/v1`). Every method returns the API's JSON unchanged, including `source`, `as_of`, `cached_at`, `stale` and the source links on each row, so you can cite where a figure came from and when.
41
+
42
+ - Get an API key (free tier, no card): https://dalalos.in/dashboard/keys
43
+ - REST reference: https://dalalos.in/docs/rest-api
44
+ - Python quickstart: https://dalalos.in/docs/python-quickstart
45
+ - Source and issues: https://github.com/BeyondNoww/DalalOS-Indian-Stock-Research/tree/main/python
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install dalalos # needs only requests
51
+ pip install "dalalos[pandas]" # adds .to_frame()
52
+ ```
53
+
54
+ Python 3.9 or newer.
55
+
56
+ ## Example
57
+
58
+ ```python
59
+ from dalalos import Client
60
+
61
+ c = Client() # reads DALALOS_API_KEY; or Client(api_key="...")
62
+ r = c.financials("TCS", period_type="annual", from_fy=2024, to_fy=2026)
63
+ for p in r["data"]["periods"]:
64
+ print(p["fiscal_label"], p["income"]["revenue"], p["income"]["net_income"])
65
+ ```
66
+
67
+ Output (run on 6 Dec 2026; figures in rupees, from the company's BSE XBRL filings):
68
+
69
+ ```text
70
+ FY26 2670210000000.0 494540000000.0
71
+ FY25 2553240000000.0 487970000000.0
72
+ FY24 2408930000000.0 460990000000.0
73
+ ```
74
+
75
+ Each period also carries `source_document_url`, the filing the figures were read from, and the response carries `meta.history` (how far back this company's data goes) and `meta.credits_charged`.
76
+
77
+ `q` arguments take an NSE symbol, an ISIN or a BSE code. Some BSE-only companies have an empty `nse_symbol`; use their `isin` or `bse_code`.
78
+
79
+ ## Methods
80
+
81
+ | Method | REST route | Returns |
82
+ | --- | --- | --- |
83
+ | `search(q, limit)` | `GET /search` | Securities matching a name, NSE symbol, BSE code or ISIN |
84
+ | `resolve(q)` | `GET /search` | The first match as one dict (`isin`, `nse_symbol`, `bse_code`, `name`, `sector`) |
85
+ | `profile(q)` | `GET /stocks/{q}/profile` | Company identity, market data, business and management |
86
+ | `quote(q)` | `GET /stocks/{q}/quote` | Latest end-of-day price, volume, market cap, P/E, P/B, 52-week range |
87
+ | `quotes(symbols)` | `GET /quotes` | End-of-day quotes for up to 20 symbols |
88
+ | `price_history(q, days, adjusted, interval)` | `GET /stocks/{q}/price-history` | OHLCV bars with delivery %, VWAP, 50/200-day averages |
89
+ | `financials(q, period_type, limit, from_fy, to_fy, from_, to, statement_type)` | `GET /stocks/{q}/financials` | P&L, balance sheet, cash flow, TTM, margins, growth, segments |
90
+ | `annual_financials(q, ...)`, `quarterly_financials(q, ...)` | `GET /stocks/{q}/financials` | Same, with `period_type` set |
91
+ | `financial_versions(q, period_type, limit, statement_type, period_end)` | `GET /stocks/{q}/financials/versions` | Every stored version of a filing (original, revised, re-parsed) |
92
+ | `financial_changes(since, limit, revision_kind, after_id)` | `GET /changes/financials` | Filings stored since a time, across all companies |
93
+ | `ratios()` | `GET /ratios` | The metric registry used by the screener |
94
+ | `screen(sort_by, order, limit, **filters)` | `GET /screen` | Companies passing filters such as `pe_max=20`, `roe_min=0.15`, `sector="Information Technology"` |
95
+ | `screen_query(query, dialect, sort_by, order, limit, snapshot_id)` | `POST /screen/query` | Companies matching an expression such as `Return on capital employed > 22%` |
96
+ | `shareholding(q, limit, from_, to, from_fy, to_fy)` | `GET /stocks/{q}/shareholding` | Promoter, FII, DII and public holding by quarter, with BSE source links |
97
+ | `pledge_trend(q, limit)` | `GET /stocks/{q}/pledge-trend` | Promoter pledge by quarter |
98
+ | `events(q, days, from_, to, category, limit, cursor)` (alias `announcements`) | `GET /stocks/{q}/events` | BSE corporate announcements with the filing PDF link |
99
+ | `documents(q, days, from_, to, document_type, limit, cursor)` | `GET /stocks/{q}/documents` | Results, annual reports, presentations, call transcripts, by type |
100
+ | `corporate_actions(q, years, from_, to, types)` | `GET /stocks/{q}/corporate-actions` | Splits, bonuses, dividends, buybacks with ex-dates and source links |
101
+ | `dividends(q, years, from_, to)` | `GET /stocks/{q}/dividends` | Dividend history, trailing yield and payout |
102
+ | `insider_trades(symbol, days, from_, to, category, side, min_value_inr, include_derivatives, group_by, limit)` | `GET /insider-trades` | SEBI PIT insider buys, sells and pledges, market-wide or for one company |
103
+ | `bulk_block_deals(q, deal_type, exchange, days, from_date, to_date, cursor, limit)` | `GET /stocks/{q}/bulk-block-deals` | NSE and BSE bulk and block deals |
104
+ | `fii_dii(from_, to, segment)` | `GET /market-fii-dii-flow` | Daily FII and DII cash-market buy, sell and net (Rs crore) |
105
+ | `freshness()` | `GET /freshness` | When each dataset was last refreshed |
106
+ | `get(path, **params)`, `post(path, body)` | any `/v1` route | For routes without a named method, for example `c.get("/indices")` |
107
+
108
+ Python reserves `from`, so date ranges take `from_` and send it as `from`.
109
+
110
+ ### Paging
111
+
112
+ These iterators follow the API's cursor and yield one row at a time:
113
+
114
+ ```python
115
+ for e in c.iter_events("RELIANCE", from_="2024-01-01", to="2026-11-30"):
116
+ print(e["filed_at"], e["subject"])
117
+ ```
118
+
119
+ | Iterator | Follows |
120
+ | --- | --- |
121
+ | `iter_events(q, ...)` (alias `iter_announcements`) | `meta.next_cursor` |
122
+ | `iter_documents(q, ...)` | `meta.next_cursor` |
123
+ | `iter_bulk_block_deals(q, ...)` | `next_cursor` while `has_more` |
124
+ | `iter_financial_changes(since, ...)` | `next_since` and `next_after_id` while `has_more` |
125
+
126
+ On ranged events and documents, pages after the first cost no credit.
127
+
128
+ ### pandas
129
+
130
+ ```python
131
+ df = c.price_history("TCS", days=10).to_frame()
132
+ print(df[["date", "close", "volume"]].tail(3).to_string(index=False))
133
+ ```
134
+
135
+ ```text
136
+ date close volume
137
+ 2026-12-02 2522.3 3530115
138
+ 2026-12-03 2500.0 2581082
139
+ 2026-12-04 2546.0 3788761
140
+ ```
141
+
142
+ `to_frame()` picks the row list inside `data` (`bars`, `periods`, `results`, `events`, ...) and flattens nested fields, so financials give columns such as `income.revenue`. Pass `key=` to choose another list. `dalalos.to_frame(response)` does the same as a function.
143
+
144
+ ## More output (run on 6 Dec 2026)
145
+
146
+ ```python
147
+ r = c.quote("TCS")
148
+ print(r["data"]["price"], r["as_of"], r["source"])
149
+ # 2546.0 2026-12-04 nse-bhavcopy
150
+
151
+ for q in c.shareholding("TCS", limit=2)["data"]["periods"]:
152
+ print(q["period_end"], q["promoter_pct"], q["fii_pct"], q["dii_pct"], q["source_url"])
153
+ # 2026-09-30 71.77 9.01 13.57 https://www.bseindia.com/corporates/shpSecurities?scripcd=532540&qtrid=131.00
154
+ # 2026-06-30 71.77 9.06 13.47 https://www.bseindia.com/corporates/shpSecurities?scripcd=532540&qtrid=130.00
155
+
156
+ for d in c.fii_dii(from_="2026-12-03", to="2026-12-05")["data"]["results"]:
157
+ print(d["trade_date"], d["fii_net"], d["dii_net"])
158
+ # 2026-12-03 -1096.08 18.03
159
+ # 2026-12-04 -456.31 743.19
160
+
161
+ for a in c.corporate_actions("TCS", years=2)["data"]["actions"][:2]:
162
+ print(a["ex_date"], a["event_type"], a["sub_type"], a["amount"])
163
+ # 2026-10-14 dividend interim 12.0
164
+ # 2026-07-15 dividend interim 12.0
165
+ ```
166
+
167
+ ## Errors
168
+
169
+ Errors raise a typed exception carrying `status`, `reason_code`, the API's `message` and the parsed `body`:
170
+
171
+ | Status | Exception | Meaning |
172
+ | --- | --- | --- |
173
+ | 400 | `BadRequestError` | A parameter is wrong; the message names it |
174
+ | 401 | `AuthenticationError` | Key missing, mistyped or revoked |
175
+ | 402 | `QuotaExceededError` | Credits used up or too low; has `credits_needed`, `credits_remaining` |
176
+ | 403 | `PermissionDeniedError` | The plan does not include this route |
177
+ | 404 | `NotFoundError` | No company matches the symbol, ISIN or BSE code |
178
+ | 409 | `ConflictError` | For example `snapshot_expired` while paging a screen |
179
+ | 429 | `RateLimitError` | Too many requests; has `retry_after` from the `Retry-After` header |
180
+ | 5xx | `ServerError` | The service could not answer |
181
+
182
+ All inherit from `DalalOSError`. On 429 the client waits for `Retry-After` and retries up to `max_retries` times (default 2) before raising.
183
+
184
+ ```python
185
+ from dalalos import Client, NotFoundError
186
+
187
+ try:
188
+ Client().quote("ZZZNOTACOMPANY")
189
+ except NotFoundError as e:
190
+ print(e.status, e.reason_code) # 404 not_found
191
+ ```
192
+
193
+ ## Limits
194
+
195
+ - End-of-day prices and exchange filings. No live ticks, no intraday data, no order placement.
196
+ - Price history: `days` up to 1825 and at most 750 bars per call; a longer daily window comes back as weekly bars.
197
+ - Financials and shareholding ranges (`from_fy`/`to_fy` or `from_`/`to`) span at most 10 years. How far back data goes depends on the company: TCS annual figures start at FY22, for example. `meta.history` reports it.
198
+ - FII/DII: at most 366 days per call; data starts 2006-04-04.
199
+ - `screen` returns at most 100 rows; `quotes` takes at most 20 symbols.
200
+ - Each call uses credits; a ranged call can use more than one. The response reports `meta.credits_charged` where it applies. Credits per plan: https://dalalos.in/pricing
201
+
202
+ Showing data publicly needs Business+ and covers filings data only. See [display rights](https://dalalos.in/docs/display-rights).
203
+
204
+ Not investment advice. DalalOS returns reported facts and mechanically computed ratios; it does not issue buy or sell calls.
205
+
206
+ ## Licence
207
+
208
+ MIT. The client code is MIT licensed; the hosted service and the data it returns are governed by the DalalOS terms (https://dalalos.in/terms).
@@ -0,0 +1,10 @@
1
+ dalalos/__init__.py,sha256=Mh7Im5OromILU7l9o-j1BvDTtz5XjcxH1cQMHLkLVQY,912
2
+ dalalos/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ dalalos/client.py,sha256=BizJKEkVvBji30AEDPRtnKRc3FJwGlChJm_bUbZt0ZY,19758
4
+ dalalos/errors.py,sha256=oN5C58CC3fAKnci5CNLTFz1Bx7gKPWXbiwlk7C1-DjY,3489
5
+ dalalos/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ dalalos/response.py,sha256=QHDjv2h6pl22Eczis5j42dmuBkGkALbvNk4kkJuw3_w,3625
7
+ dalalos-0.1.0.dist-info/METADATA,sha256=8Qe83A5p22tS2FoSJGvsFs-5laUMZ5h2hbVoKg1iuu0,10988
8
+ dalalos-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ dalalos-0.1.0.dist-info/licenses/LICENSE,sha256=BuR2cvUZd9c5ZnfCCye_fN72qLnXkdnLH_eZLDqRvu8,1085
10
+ dalalos-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DalalOS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.