PaperTrade-India 0.1.0.dev0__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.
Files changed (101) hide show
  1. papertrade_india/__init__.py +250 -0
  2. papertrade_india/_context.py +144 -0
  3. papertrade_india/broker.py +546 -0
  4. papertrade_india/cli.py +474 -0
  5. papertrade_india/clock.py +29 -0
  6. papertrade_india/corporate_actions/__init__.py +10 -0
  7. papertrade_india/corporate_actions/bonus.py +105 -0
  8. papertrade_india/corporate_actions/dividends.py +99 -0
  9. papertrade_india/corporate_actions/rights.py +189 -0
  10. papertrade_india/corporate_actions/splits.py +111 -0
  11. papertrade_india/corporate_actions/store.py +247 -0
  12. papertrade_india/data/nse_holidays_2026.json +22 -0
  13. papertrade_india/data/nse_holidays_2027.json +9 -0
  14. papertrade_india/data/nse_universe_sample.csv +31 -0
  15. papertrade_india/domain/__init__.py +6 -0
  16. papertrade_india/domain/exceptions.py +183 -0
  17. papertrade_india/domain/models.py +213 -0
  18. papertrade_india/domain/rules/__init__.py +5 -0
  19. papertrade_india/domain/rules/risk.py +165 -0
  20. papertrade_india/domain/rules/tick_lot_band.py +139 -0
  21. papertrade_india/events.py +29 -0
  22. papertrade_india/exceptions.py +29 -0
  23. papertrade_india/execution/__init__.py +5 -0
  24. papertrade_india/execution/book.py +385 -0
  25. papertrade_india/execution/fees.py +213 -0
  26. papertrade_india/execution/settlement.py +360 -0
  27. papertrade_india/execution/simulation.py +176 -0
  28. papertrade_india/execution/slippage.py +120 -0
  29. papertrade_india/fees.py +29 -0
  30. papertrade_india/idempotency.py +29 -0
  31. papertrade_india/infrastructure/__init__.py +6 -0
  32. papertrade_india/infrastructure/clock.py +123 -0
  33. papertrade_india/infrastructure/events.py +137 -0
  34. papertrade_india/infrastructure/holidays.py +138 -0
  35. papertrade_india/infrastructure/idempotency.py +133 -0
  36. papertrade_india/infrastructure/ledger.py +141 -0
  37. papertrade_india/infrastructure/market_hours.py +200 -0
  38. papertrade_india/infrastructure/migrations.py +622 -0
  39. papertrade_india/infrastructure/observability.py +195 -0
  40. papertrade_india/infrastructure/persistence.py +130 -0
  41. papertrade_india/infrastructure/symbols.py +279 -0
  42. papertrade_india/infrastructure/watchlist.py +78 -0
  43. papertrade_india/interface.py +92 -0
  44. papertrade_india/ledger.py +29 -0
  45. papertrade_india/limit_orders.py +29 -0
  46. papertrade_india/market_hours.py +29 -0
  47. papertrade_india/microstructure.py +57 -0
  48. papertrade_india/migrations.py +29 -0
  49. papertrade_india/models.py +29 -0
  50. papertrade_india/observability.py +29 -0
  51. papertrade_india/orders/__init__.py +5 -0
  52. papertrade_india/orders/amo.py +98 -0
  53. papertrade_india/orders/book_helpers.py +111 -0
  54. papertrade_india/orders/bracket.py +115 -0
  55. papertrade_india/orders/limit.py +210 -0
  56. papertrade_india/orders/market.py +264 -0
  57. papertrade_india/orders/partial_fills.py +92 -0
  58. papertrade_india/orders/preopen.py +274 -0
  59. papertrade_india/orders/state.py +640 -0
  60. papertrade_india/orders/stop.py +122 -0
  61. papertrade_india/orders/submit.py +385 -0
  62. papertrade_india/partial_fills.py +29 -0
  63. papertrade_india/persistence.py +29 -0
  64. papertrade_india/preopen.py +29 -0
  65. papertrade_india/presets.py +120 -0
  66. papertrade_india/price_feed.py +316 -0
  67. papertrade_india/providers/__init__.py +123 -0
  68. papertrade_india/providers/alphavantage.py +180 -0
  69. papertrade_india/providers/base.py +256 -0
  70. papertrade_india/providers/cache.py +147 -0
  71. papertrade_india/providers/composite.py +244 -0
  72. papertrade_india/providers/dhan.py +266 -0
  73. papertrade_india/providers/finnhub.py +122 -0
  74. papertrade_india/providers/health.py +233 -0
  75. papertrade_india/providers/jugaad.py +142 -0
  76. papertrade_india/providers/kite.py +222 -0
  77. papertrade_india/providers/nse_bhavcopy.py +210 -0
  78. papertrade_india/providers/nsepython.py +98 -0
  79. papertrade_india/providers/registry.py +226 -0
  80. papertrade_india/providers/stooq.py +173 -0
  81. papertrade_india/providers/twelvedata.py +198 -0
  82. papertrade_india/providers/upstox.py +318 -0
  83. papertrade_india/providers/upstox_instruments.py +171 -0
  84. papertrade_india/providers/yfinance.py +205 -0
  85. papertrade_india/quickstart.py +111 -0
  86. papertrade_india/reads/__init__.py +6 -0
  87. papertrade_india/reads/account.py +140 -0
  88. papertrade_india/reads/orders.py +54 -0
  89. papertrade_india/reads/positions.py +188 -0
  90. papertrade_india/risk.py +29 -0
  91. papertrade_india/settlement.py +29 -0
  92. papertrade_india/simulation.py +29 -0
  93. papertrade_india/slippage.py +29 -0
  94. papertrade_india/symbols.py +29 -0
  95. papertrade_india/workers/__init__.py +6 -0
  96. papertrade_india/workers/limit_orders.py +390 -0
  97. papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
  98. papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
  99. papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
  100. papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  101. papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,210 @@
1
+ """NSE Bhavcopy provider — official EOD daily-bar source.
2
+
3
+ The bhavcopy is NSE's official end-of-day CSV with every traded symbol's
4
+ OHLCV. We fetch it once per trading date and cache the parse so repeat
5
+ quotes for that date are O(1).
6
+
7
+ URL pattern (current NSE archive layout, 2024+):
8
+ https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_<DDMMYYYY>.csv
9
+
10
+ NSE rate-limits and occasionally requires a cookie; this provider keeps
11
+ its surface narrow (single-day fetch, in-memory cache) and lets the
12
+ circuit breaker handle hostile responses.
13
+
14
+ Real-time? No — the bhavcopy is published after the session closes.
15
+ ``MarketQuote.is_real_time`` is ``False`` and ``is_stale`` semantics in
16
+ the broker treat it as cache-grade.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import io
23
+ import logging
24
+ import urllib.request
25
+ from datetime import date, datetime, timedelta
26
+ from threading import RLock
27
+ from urllib.error import HTTPError, URLError
28
+
29
+ from .base import (
30
+ OHLCV,
31
+ MarketDataProvider,
32
+ MarketQuote,
33
+ ProviderCapability,
34
+ ProviderError,
35
+ ProviderInfo,
36
+ )
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ _BHAVCOPY_URL = (
41
+ "https://nsearchives.nseindia.com/products/content/"
42
+ "sec_bhavdata_full_{ddmmyyyy}.csv"
43
+ )
44
+
45
+ # NSE's archive blocks default urllib UA; mimic a browser to get past
46
+ # the gate without dragging in ``requests`` as a hard dep.
47
+ _HEADERS = {
48
+ "User-Agent": (
49
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
50
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
51
+ "Chrome/124.0 Safari/537.36"
52
+ ),
53
+ "Accept": "text/csv,application/csv,*/*",
54
+ "Accept-Language": "en-US,en;q=0.9",
55
+ "Referer": "https://www.nseindia.com/",
56
+ }
57
+
58
+
59
+ class NSEBhavcopyProvider(MarketDataProvider):
60
+ """Read EOD prices from the official NSE bhavcopy.
61
+
62
+ Parameters
63
+ ----------
64
+ timeout:
65
+ HTTP timeout in seconds. Default 10.
66
+ max_lookback_days:
67
+ How many trading days back to walk when today's bhavcopy isn't
68
+ published yet (weekend, holiday, before EOD). Default 7.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ timeout: float = 10.0,
74
+ max_lookback_days: int = 7,
75
+ ) -> None:
76
+ self._timeout = float(timeout)
77
+ self._max_lookback = int(max_lookback_days)
78
+ self._cache: dict[date, dict[str, dict[str, float | int]]] = {}
79
+ self._lock = RLock()
80
+
81
+ @property
82
+ def info(self) -> ProviderInfo:
83
+ return ProviderInfo(
84
+ name="nse-bhavcopy",
85
+ description="Official NSE EOD bhavcopy CSV.",
86
+ capabilities=(
87
+ ProviderCapability.LAST_PRICE
88
+ | ProviderCapability.OHLCV_DAILY
89
+ | ProviderCapability.SUPPORTS_NSE
90
+ | ProviderCapability.DELAYED
91
+ ),
92
+ requires_api_key=False,
93
+ homepage="https://www.nseindia.com/all-reports",
94
+ notes="Published after market close. Authoritative EOD data.",
95
+ )
96
+
97
+ # ── Quote/history ─────────────────────────────────────────────────
98
+
99
+ def get_quote(self, symbol: str) -> MarketQuote | None:
100
+ for days_back in range(self._max_lookback):
101
+ d = date.today() - timedelta(days=days_back)
102
+ try:
103
+ table = self._load(d)
104
+ except ProviderError:
105
+ # The dated copy may not exist (weekend/holiday) — try earlier.
106
+ continue
107
+ row = table.get(symbol.upper())
108
+ if row is None:
109
+ continue
110
+ return MarketQuote(
111
+ last=float(row["close"]),
112
+ timestamp=datetime.combine(d, datetime.min.time()),
113
+ open=float(row["open"]),
114
+ high=float(row["high"]),
115
+ low=float(row["low"]),
116
+ prev_close=float(row.get("prev_close") or 0) or None,
117
+ volume=int(row.get("volume") or 0) or None,
118
+ source="nse-bhavcopy",
119
+ is_real_time=False,
120
+ )
121
+ return None
122
+
123
+ def get_history(
124
+ self,
125
+ symbol: str,
126
+ start: date,
127
+ end: date,
128
+ interval: str = "1d",
129
+ ) -> list[OHLCV]:
130
+ if interval != "1d":
131
+ return []
132
+ out: list[OHLCV] = []
133
+ d = start
134
+ while d <= end:
135
+ try:
136
+ table = self._load(d)
137
+ except ProviderError:
138
+ d += timedelta(days=1)
139
+ continue
140
+ row = table.get(symbol.upper())
141
+ if row is not None:
142
+ out.append(
143
+ OHLCV(
144
+ timestamp=datetime.combine(d, datetime.min.time()),
145
+ open=float(row["open"]),
146
+ high=float(row["high"]),
147
+ low=float(row["low"]),
148
+ close=float(row["close"]),
149
+ volume=int(row.get("volume") or 0),
150
+ )
151
+ )
152
+ d += timedelta(days=1)
153
+ return out
154
+
155
+ # ── Internals ─────────────────────────────────────────────────────
156
+
157
+ def _load(self, d: date) -> dict[str, dict[str, float | int]]:
158
+ with self._lock:
159
+ cached = self._cache.get(d)
160
+ if cached is not None:
161
+ return cached
162
+ url = _BHAVCOPY_URL.format(ddmmyyyy=d.strftime("%d%m%Y"))
163
+ body = self._fetch(url)
164
+ table = self._parse(body)
165
+ with self._lock:
166
+ self._cache[d] = table
167
+ return table
168
+
169
+ def _fetch(self, url: str) -> str:
170
+ req = urllib.request.Request(url, headers=_HEADERS) # noqa: S310 — fixed host
171
+ try:
172
+ with urllib.request.urlopen(req, timeout=self._timeout) as resp: # noqa: S310
173
+ return resp.read().decode("utf-8", errors="replace")
174
+ except HTTPError as e:
175
+ raise ProviderError(f"NSE bhavcopy HTTP {e.code}: {url}") from e
176
+ except (URLError, TimeoutError) as e:
177
+ raise ProviderError(f"NSE bhavcopy fetch failed: {e}") from e
178
+
179
+ @staticmethod
180
+ def _parse(body: str) -> dict[str, dict[str, float | int]]:
181
+ """Parse the NSE bhavcopy CSV into a ``{symbol: row}`` map.
182
+
183
+ The columns are space-padded (``" SYMBOL"``) and named in upper
184
+ case in the canonical layout. We only keep the EQ series rows.
185
+ """
186
+ out: dict[str, dict[str, float | int]] = {}
187
+ reader = csv.DictReader(io.StringIO(body))
188
+ for raw in reader:
189
+ row = {k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in raw.items()}
190
+ series = (row.get("SERIES") or "").upper()
191
+ if series and series != "EQ":
192
+ continue
193
+ symbol = (row.get("SYMBOL") or "").upper()
194
+ if not symbol:
195
+ continue
196
+ try:
197
+ close = float(row.get("CLOSE_PRICE") or row.get("CLOSE") or 0.0)
198
+ if close <= 0:
199
+ continue
200
+ out[symbol] = {
201
+ "open": float(row.get("OPEN_PRICE") or row.get("OPEN") or 0.0),
202
+ "high": float(row.get("HIGH_PRICE") or row.get("HIGH") or 0.0),
203
+ "low": float(row.get("LOW_PRICE") or row.get("LOW") or 0.0),
204
+ "close": close,
205
+ "prev_close": float(row.get("PREV_CLOSE") or 0.0),
206
+ "volume": int(float(row.get("TTL_TRD_QNTY") or row.get("VOLUME") or 0)),
207
+ }
208
+ except (TypeError, ValueError):
209
+ continue
210
+ return out
@@ -0,0 +1,98 @@
1
+ """nsepython provider — another NSE-direct fallback.
2
+
3
+ ``nsepython`` is the actively-maintained spiritual successor to a few
4
+ older NSE scrapers. Like ``jugaad-data`` it scrapes the public NSE site
5
+ directly, but its API stays a bit closer to the live JSON shape and it
6
+ generally exposes bid/ask/volume for liquid names.
7
+
8
+ Optional dep: install with ``pip install nsepython``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ from datetime import datetime
15
+
16
+ from .base import (
17
+ MarketDataProvider,
18
+ MarketQuote,
19
+ ProviderCapability,
20
+ ProviderError,
21
+ ProviderInfo,
22
+ )
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class NSEPythonProvider(MarketDataProvider):
28
+ """NSE direct via the ``nsepython`` package."""
29
+
30
+ @property
31
+ def info(self) -> ProviderInfo:
32
+ return ProviderInfo(
33
+ name="nsepython",
34
+ description="Direct NSE quotes via the nsepython package.",
35
+ capabilities=(
36
+ ProviderCapability.LAST_PRICE
37
+ | ProviderCapability.QUOTE
38
+ | ProviderCapability.SUPPORTS_NSE
39
+ | ProviderCapability.DELAYED
40
+ ),
41
+ requires_api_key=False,
42
+ homepage="https://github.com/aeron7/nsepython",
43
+ notes="Scraper. Treat failures as expected.",
44
+ )
45
+
46
+ def get_quote(self, symbol: str) -> MarketQuote | None:
47
+ try:
48
+ from nsepython import nsefetch # type: ignore
49
+ except ImportError as e:
50
+ raise ProviderError("nsepython is not installed") from e
51
+
52
+ url = (
53
+ "https://www.nseindia.com/api/quote-equity?symbol="
54
+ f"{symbol.upper()}"
55
+ )
56
+ try:
57
+ data = nsefetch(url)
58
+ except Exception as e: # noqa: BLE001
59
+ logger.warning("nsepython failed for %s: %s", symbol, e)
60
+ raise ProviderError(f"nsepython failed for {symbol}: {e}") from e
61
+
62
+ if not isinstance(data, dict):
63
+ return None
64
+ price_info = data.get("priceInfo") or {}
65
+ if not price_info:
66
+ return None
67
+ try:
68
+ last = float(price_info.get("lastPrice"))
69
+ except (TypeError, ValueError):
70
+ return None
71
+
72
+ ohl = price_info.get("intraDayHighLow") or {}
73
+ return MarketQuote(
74
+ last=last,
75
+ timestamp=datetime.now(),
76
+ open=_f(price_info.get("open")),
77
+ high=_f(ohl.get("max")),
78
+ low=_f(ohl.get("min")),
79
+ prev_close=_f(price_info.get("previousClose")),
80
+ volume=_i((data.get("preOpenMarket") or {}).get("totalTradedVolume")),
81
+ source="nsepython",
82
+ is_real_time=False,
83
+ )
84
+
85
+
86
+ def _f(x: object) -> float | None:
87
+ try:
88
+ if x is None:
89
+ return None
90
+ v = float(x)
91
+ return v if v > 0 else None
92
+ except (TypeError, ValueError):
93
+ return None
94
+
95
+
96
+ def _i(x: object) -> int | None:
97
+ f = _f(x)
98
+ return int(f) if f is not None else None
@@ -0,0 +1,226 @@
1
+ """Provider registry — lookup by stable name.
2
+
3
+ The registry is a thin map from a stable, lowercased name (``"yfinance"``,
4
+ ``"jugaad-data"``, ``"stooq"``, …) to a factory that builds the provider.
5
+ Used by:
6
+
7
+ - The CLI (``papertrade-india providers list``) to enumerate what's
8
+ available and what's installed.
9
+ - Config-driven setup so users can declare provider chains in env / TOML
10
+ without hard-coding imports in their app.
11
+ - Tests to discover what to monkeypatch.
12
+
13
+ Why factories instead of instances? Most providers are cheap to build,
14
+ but a few (Finnhub, Twelve Data) read API keys at construction time —
15
+ deferring instantiation to "the caller asked for it" keeps the import
16
+ side-effect free.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ from collections.abc import Callable
23
+ from dataclasses import dataclass
24
+
25
+ from .base import MarketDataProvider, ProviderInfo
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ ProviderFactory = Callable[..., MarketDataProvider]
31
+
32
+
33
+ @dataclass
34
+ class _RegistryEntry:
35
+ info: ProviderInfo
36
+ factory: ProviderFactory
37
+ available: bool
38
+
39
+
40
+ class ProviderRegistry:
41
+ """Name → factory map for every known provider.
42
+
43
+ Unknown providers raise :class:`KeyError`. Use :meth:`available` to
44
+ list only those whose third-party deps are installed.
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ self._entries: dict[str, _RegistryEntry] = {}
49
+
50
+ def register(
51
+ self,
52
+ name: str,
53
+ info: ProviderInfo,
54
+ factory: ProviderFactory,
55
+ available: bool = True,
56
+ ) -> None:
57
+ self._entries[name.lower()] = _RegistryEntry(
58
+ info=info, factory=factory, available=available,
59
+ )
60
+
61
+ def get(self, name: str, **kwargs: object) -> MarketDataProvider:
62
+ entry = self._entries.get(name.lower())
63
+ if entry is None:
64
+ raise KeyError(f"Unknown provider: {name!r}")
65
+ if not entry.available:
66
+ raise RuntimeError(
67
+ f"Provider {name!r} is registered but its dependencies "
68
+ f"are not installed. Notes: {entry.info.notes}",
69
+ )
70
+ return entry.factory(**kwargs)
71
+
72
+ def info(self, name: str) -> ProviderInfo:
73
+ entry = self._entries.get(name.lower())
74
+ if entry is None:
75
+ raise KeyError(f"Unknown provider: {name!r}")
76
+ return entry.info
77
+
78
+ def names(self, *, only_available: bool = False) -> list[str]:
79
+ return sorted(
80
+ n for n, e in self._entries.items()
81
+ if (not only_available) or e.available
82
+ )
83
+
84
+ def all(self) -> dict[str, ProviderInfo]:
85
+ return {n: e.info for n, e in self._entries.items()}
86
+
87
+ def available(self) -> dict[str, ProviderInfo]:
88
+ return {n: e.info for n, e in self._entries.items() if e.available}
89
+
90
+
91
+ def _build_default_registry() -> ProviderRegistry:
92
+ """Populate the registry with every known provider.
93
+
94
+ Optional providers are registered as ``available=False`` when their
95
+ third-party imports fail, so the CLI can show "yes installed / not
96
+ installed" without crashing.
97
+ """
98
+ reg = ProviderRegistry()
99
+
100
+ # Always available — pure-Python or already in the install dep set.
101
+ from .jugaad import JugaadDataProvider
102
+ from .nse_bhavcopy import NSEBhavcopyProvider
103
+ from .stooq import StooqProvider
104
+ from .yfinance import YFinanceProvider
105
+
106
+ reg.register(
107
+ "yfinance",
108
+ YFinanceProvider().info,
109
+ lambda **kw: YFinanceProvider(**kw),
110
+ available=_check_import("yfinance"),
111
+ )
112
+ reg.register(
113
+ "jugaad-data",
114
+ JugaadDataProvider().info,
115
+ lambda **kw: JugaadDataProvider(**kw),
116
+ available=_check_import("jugaad_data"),
117
+ )
118
+ reg.register(
119
+ "stooq",
120
+ StooqProvider().info,
121
+ lambda **kw: StooqProvider(**kw),
122
+ available=True, # stdlib only
123
+ )
124
+ reg.register(
125
+ "nse-bhavcopy",
126
+ NSEBhavcopyProvider().info,
127
+ lambda **kw: NSEBhavcopyProvider(**kw),
128
+ available=True, # stdlib only
129
+ )
130
+
131
+ # Optional providers — register even when deps are missing, so
132
+ # ``providers list`` shows them as "(install <pkg>)".
133
+ try:
134
+ from .nsepython import NSEPythonProvider # noqa: F401
135
+ reg.register(
136
+ "nsepython",
137
+ NSEPythonProvider().info,
138
+ lambda **kw: NSEPythonProvider(**kw),
139
+ available=_check_import("nsepython"),
140
+ )
141
+ except Exception as e: # noqa: BLE001
142
+ logger.debug("nsepython provider unavailable: %s", e)
143
+
144
+ try:
145
+ from .alphavantage import AlphaVantageProvider
146
+ reg.register(
147
+ "alphavantage",
148
+ AlphaVantageProvider().info,
149
+ lambda **kw: AlphaVantageProvider(**kw),
150
+ available=True, # stdlib only — auth checked at call time
151
+ )
152
+ except Exception as e: # noqa: BLE001
153
+ logger.debug("alphavantage unavailable: %s", e)
154
+
155
+ try:
156
+ from .twelvedata import TwelveDataProvider
157
+ reg.register(
158
+ "twelvedata",
159
+ TwelveDataProvider().info,
160
+ lambda **kw: TwelveDataProvider(**kw),
161
+ available=True,
162
+ )
163
+ except Exception as e: # noqa: BLE001
164
+ logger.debug("twelvedata unavailable: %s", e)
165
+
166
+ try:
167
+ from .finnhub import FinnhubProvider
168
+ reg.register(
169
+ "finnhub",
170
+ FinnhubProvider().info,
171
+ lambda **kw: FinnhubProvider(**kw),
172
+ available=True,
173
+ )
174
+ except Exception as e: # noqa: BLE001
175
+ logger.debug("finnhub unavailable: %s", e)
176
+
177
+ # Broker-feed providers — real bid/ask + depth. Kite and Dhan need a
178
+ # third-party SDK; Upstox is REST (stdlib) but still needs an account
179
+ # token, so all three are gated on credentials at call time.
180
+ try:
181
+ from .kite import KiteProvider
182
+ reg.register(
183
+ "kite",
184
+ KiteProvider().info,
185
+ lambda **kw: KiteProvider(**kw),
186
+ available=_check_import("kiteconnect"),
187
+ )
188
+ except Exception as e: # noqa: BLE001
189
+ logger.debug("kite unavailable: %s", e)
190
+
191
+ try:
192
+ from .dhan import DhanProvider
193
+ reg.register(
194
+ "dhan",
195
+ DhanProvider().info,
196
+ lambda **kw: DhanProvider(**kw),
197
+ available=_check_import("dhanhq"),
198
+ )
199
+ except Exception as e: # noqa: BLE001
200
+ logger.debug("dhan unavailable: %s", e)
201
+
202
+ try:
203
+ from .upstox import UpstoxProvider
204
+ reg.register(
205
+ "upstox",
206
+ UpstoxProvider().info,
207
+ lambda **kw: UpstoxProvider(**kw),
208
+ available=True, # stdlib REST — token checked at call time
209
+ )
210
+ except Exception as e: # noqa: BLE001
211
+ logger.debug("upstox unavailable: %s", e)
212
+
213
+ return reg
214
+
215
+
216
+ def _check_import(module_name: str) -> bool:
217
+ """Light import probe so we can flag unavailable deps."""
218
+ try:
219
+ __import__(module_name)
220
+ except Exception: # noqa: BLE001
221
+ return False
222
+ return True
223
+
224
+
225
+ # Module-level default registry. Built once on import.
226
+ default_registry = _build_default_registry()
@@ -0,0 +1,173 @@
1
+ """Stooq.com EOD provider.
2
+
3
+ Stooq publishes free end-of-day CSVs over plain HTTP — no API key.
4
+ Useful as a reference / backtest source and as another fallback in the
5
+ chain. End-of-day only, so :attr:`MarketQuote.is_real_time` is always
6
+ ``False``.
7
+
8
+ Symbol convention: NSE → ``<symbol>.in`` (lowercase). E.g. ``RELIANCE``
9
+ → ``reliance.in``. BSE coverage is partial; we attempt the same suffix.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import csv
15
+ import io
16
+ import logging
17
+ import urllib.parse
18
+ import urllib.request
19
+ from datetime import date, datetime
20
+ from urllib.error import URLError
21
+
22
+ from .base import (
23
+ OHLCV,
24
+ MarketDataProvider,
25
+ MarketQuote,
26
+ ProviderCapability,
27
+ ProviderError,
28
+ ProviderInfo,
29
+ )
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ _QUOTE_URL = "https://stooq.com/q/l/"
34
+
35
+
36
+ class StooqProvider(MarketDataProvider):
37
+ """End-of-day quotes from stooq.com.
38
+
39
+ Parameters
40
+ ----------
41
+ suffix:
42
+ Symbol suffix appended to the query. Default ``".in"`` for NSE.
43
+ timeout:
44
+ HTTP timeout in seconds.
45
+ """
46
+
47
+ def __init__(self, suffix: str = ".in", timeout: float = 5.0) -> None:
48
+ self._suffix = suffix
49
+ self._timeout = float(timeout)
50
+
51
+ @property
52
+ def info(self) -> ProviderInfo:
53
+ return ProviderInfo(
54
+ name="stooq",
55
+ description="End-of-day OHLCV CSVs from stooq.com (no API key).",
56
+ capabilities=(
57
+ ProviderCapability.LAST_PRICE
58
+ | ProviderCapability.OHLCV_DAILY
59
+ | ProviderCapability.SUPPORTS_NSE
60
+ | ProviderCapability.DELAYED
61
+ ),
62
+ requires_api_key=False,
63
+ homepage="https://stooq.com",
64
+ notes="Free EOD data — no real-time prices.",
65
+ )
66
+
67
+ def _ticker(self, symbol: str) -> str:
68
+ return f"{symbol.lower()}{self._suffix}"
69
+
70
+ def get_quote(self, symbol: str) -> MarketQuote | None:
71
+ params = urllib.parse.urlencode({"s": self._ticker(symbol), "f": "sd2t2ohlcv", "h": "", "e": "csv"})
72
+ url = f"{_QUOTE_URL}?{params}"
73
+ try:
74
+ with urllib.request.urlopen(url, timeout=self._timeout) as resp: # noqa: S310 — fixed host
75
+ body = resp.read().decode("utf-8", errors="replace")
76
+ except (URLError, TimeoutError) as e:
77
+ raise ProviderError(f"stooq fetch failed: {e}") from e
78
+ except Exception as e: # noqa: BLE001 — defensive
79
+ raise ProviderError(f"stooq fetch failed: {e}") from e
80
+
81
+ reader = csv.DictReader(io.StringIO(body))
82
+ rows = list(reader)
83
+ if not rows:
84
+ return None
85
+ row = rows[0]
86
+ # Stooq returns "N/D" when the symbol is unknown.
87
+ last_raw = row.get("Close") or row.get("close")
88
+ if not last_raw or last_raw.upper() == "N/D":
89
+ return None
90
+ try:
91
+ last = float(last_raw)
92
+ day_open = _maybe_float(row.get("Open") or row.get("open"))
93
+ day_high = _maybe_float(row.get("High") or row.get("high"))
94
+ day_low = _maybe_float(row.get("Low") or row.get("low"))
95
+ volume_raw = row.get("Volume") or row.get("volume")
96
+ volume = int(float(volume_raw)) if volume_raw and volume_raw.upper() != "N/D" else None
97
+ except ValueError as e:
98
+ raise ProviderError(f"stooq malformed row: {row}") from e
99
+
100
+ ts = _parse_date_time(row.get("Date"), row.get("Time"))
101
+ return MarketQuote(
102
+ last=last,
103
+ timestamp=ts,
104
+ open=day_open,
105
+ high=day_high,
106
+ low=day_low,
107
+ volume=volume,
108
+ source="stooq",
109
+ is_real_time=False,
110
+ )
111
+
112
+ def get_history(
113
+ self,
114
+ symbol: str,
115
+ start: date,
116
+ end: date,
117
+ interval: str = "1d",
118
+ ) -> list[OHLCV]:
119
+ if interval != "1d":
120
+ return []
121
+ params = urllib.parse.urlencode(
122
+ {
123
+ "s": self._ticker(symbol),
124
+ "i": "d",
125
+ "d1": start.strftime("%Y%m%d"),
126
+ "d2": end.strftime("%Y%m%d"),
127
+ },
128
+ )
129
+ url = f"https://stooq.com/q/d/l/?{params}"
130
+ try:
131
+ with urllib.request.urlopen(url, timeout=self._timeout) as resp: # noqa: S310
132
+ body = resp.read().decode("utf-8", errors="replace")
133
+ except (URLError, TimeoutError) as e:
134
+ raise ProviderError(f"stooq history fetch failed: {e}") from e
135
+
136
+ reader = csv.DictReader(io.StringIO(body))
137
+ out: list[OHLCV] = []
138
+ for row in reader:
139
+ try:
140
+ out.append(
141
+ OHLCV(
142
+ timestamp=datetime.strptime(row["Date"], "%Y-%m-%d"),
143
+ open=float(row["Open"]),
144
+ high=float(row["High"]),
145
+ low=float(row["Low"]),
146
+ close=float(row["Close"]),
147
+ volume=int(float(row.get("Volume") or 0)),
148
+ )
149
+ )
150
+ except (KeyError, ValueError):
151
+ continue
152
+ return out
153
+
154
+
155
+ def _maybe_float(s: str | None) -> float | None:
156
+ if not s or s.upper() == "N/D":
157
+ return None
158
+ try:
159
+ return float(s)
160
+ except ValueError:
161
+ return None
162
+
163
+
164
+ def _parse_date_time(d: str | None, t: str | None) -> datetime:
165
+ """Parse stooq's ``Date`` + ``Time`` columns, falling back to now."""
166
+ if d:
167
+ try:
168
+ if t:
169
+ return datetime.strptime(f"{d} {t}", "%Y-%m-%d %H:%M:%S")
170
+ return datetime.strptime(d, "%Y-%m-%d")
171
+ except ValueError:
172
+ pass
173
+ return datetime.now()