From 4e09921459c672f6151d439eb2899e9141066053 Mon Sep 17 00:00:00 2001 From: Alessandro <17289614+0x0f0f0f@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:35:28 +0100 Subject: [PATCH 1/5] fix(alpaca): end SIP requests before the window the free plan refuses update-all asks up to today, which a free plan answers with HTTP 403 for the SIP feed, reported as an invalid API key. A SIP stock request now ends sip_delay_minutes (default 15) before now; 0 disables the cut. 401/403 errors carry Alpaca's own message. --- docs/providers/alpaca.md | 14 +++++- src/ml4t/data/providers/alpaca.py | 49 +++++++++++++++++++-- tests/test_alpaca_provider.py | 71 +++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 5 deletions(-) diff --git a/docs/providers/alpaca.md b/docs/providers/alpaca.md index 006fda2f..ba639fc6 100644 --- a/docs/providers/alpaca.md +++ b/docs/providers/alpaca.md @@ -95,7 +95,10 @@ datetime bounds are the natural shape for sub-day minute/hour windows. exchange (IEX, roughly 2-3% of US volume). - `feed="sip"`: the consolidated tape (100% of US volume, all exchanges). Real-time on paid plans; the free Basic plan can still query SIP bars, only - not the most recent 15 minutes. + not the most recent 15 minutes, and answers such a request with HTTP 403. The + provider therefore ends a SIP stock request `sip_delay_minutes` (default 15) + before now, so `end` may be today, as incremental `update` requests are. Pass + `sip_delay_minutes=0` on a paid plan. - `feed="otc"` (over-the-counter) and `feed="boats"` (Blue Ocean overnight) are also accepted. Any other value raises `DataValidationError` at construction. - `adjustment="raw"` (default, Alpaca's own default): stock bars are **not** @@ -106,6 +109,15 @@ datetime bounds are the natural shape for sub-day minute/hour windows. provider = AlpacaDataProvider(feed="sip", adjustment="all") ``` +In a `ml4t.data.yaml`, the same settings go under `extra` of a named provider: + +```yaml +providers: + - name: alpaca_sip + type: alpaca + extra: {feed: sip, adjustment: all} +``` + --- ## API Key Setup diff --git a/src/ml4t/data/providers/alpaca.py b/src/ml4t/data/providers/alpaca.py index e535438d..80bd388e 100644 --- a/src/ml4t/data/providers/alpaca.py +++ b/src/ml4t/data/providers/alpaca.py @@ -34,7 +34,10 @@ the consolidated tape. - ``feed="sip"`` selects the consolidated tape (100% of US market volume across all exchanges). It is real time on paid plans; the free Basic plan can still - query SIP bars, only not the most recent 15 minutes. + query SIP bars, only not the most recent 15 minutes. A SIP request that would + reach into that window is cut to end ``sip_delay_minutes`` (default 15) before + now, so a request ``end`` of today works on the free plan. Pass + ``sip_delay_minutes=0`` on a paid plan. - ``"otc"`` (over-the-counter) and ``"boats"`` (Blue Ocean overnight) are also accepted; any other value raises ``DataValidationError`` at construction. - Crypto has a single consolidated feed, so ``feed`` does not apply to it. @@ -71,7 +74,7 @@ import asyncio import os import time -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any, ClassVar import polars as pl @@ -192,6 +195,7 @@ def __init__( feed: str = "iex", adjustment: str = "raw", rate_limit: tuple[int, float] | None = None, + sip_delay_minutes: int = 15, **kwargs: Any, ) -> None: """Initialize the Alpaca data provider. @@ -208,6 +212,9 @@ def __init__( Alpaca's own default: no split/dividend adjustment), "split", "dividend", or "all". Ignored for crypto. rate_limit: Optional custom (calls, period_seconds) override. + sip_delay_minutes: With ``feed="sip"``, a stock request ends at least + this many minutes before now, the window the free plan refuses. + ``0`` sends ``end`` unchanged. Ignored for other feeds and crypto. **kwargs: Additional arguments forwarded to BaseProvider. Raises: @@ -238,6 +245,14 @@ def __init__( ) self.feed = normalized_feed self.adjustment = adjustment + if sip_delay_minutes < 0: + raise DataValidationError( + provider="alpaca", + message="sip_delay_minutes cannot be negative", + field="sip_delay_minutes", + value=sip_delay_minutes, + ) + self.sip_delay = timedelta(minutes=sip_delay_minutes) self.base_url = "https://data.alpaca.markets" # Built once, reused for both the sync and async sessions so the two @@ -432,12 +447,36 @@ def _stock_bars_params(self, frequency: str, start: str, end: str) -> dict[str, return { "timeframe": self._map_frequency(frequency), "start": start, - "end": end, + "end": self._stock_end(end), "limit": self.PAGE_LIMIT, "feed": self.feed, "adjustment": self.adjustment, } + def _stock_end(self, end: str) -> str: + """Cut a SIP request's end to before the window the plan refuses. + + Alpaca reads a date-only ``end`` as that whole day, so today's date + reaches into the most recent minutes, which the free plan answers with + HTTP 403. The cut applies only when the bound actually reaches past + ``now - sip_delay``; earlier bounds are sent unchanged. + + Args: + end: Inclusive end date/datetime in ISO-8601 (RFC-3339) form. + + Returns: + ``end`` itself, or ``now - sip_delay`` as an RFC-3339 UTC instant. + """ + if self.feed != "sip" or not self.sip_delay: + return end + bound = self._parse_time_bound(end) + if "T" not in end: + bound += timedelta(days=1) + latest = datetime.now(UTC) - self.sip_delay + if bound <= latest: + return end + return latest.strftime("%Y-%m-%dT%H:%M:%SZ") + def _crypto_bars_params( self, symbol: str, frequency: str, start: str, end: str ) -> dict[str, Any]: @@ -567,8 +606,10 @@ def _check_response_status(self, response: Any, symbol: str) -> None: if status_code == 429: raise RateLimitError(provider="alpaca", retry_after=self._retry_after_seconds(response)) if status_code in (401, 403): + # The body says why, e.g. a 403 for SIP data the plan does not cover. raise AuthenticationError( - provider="alpaca", message="Invalid API key or unauthorized access" + provider="alpaca", + message=f"Invalid API key or unauthorized access: {response.text}", ) if status_code == 404: raise DataNotAvailableError(provider="alpaca", symbol=symbol) diff --git a/tests/test_alpaca_provider.py b/tests/test_alpaca_provider.py index e39dffd8..ca717889 100644 --- a/tests/test_alpaca_provider.py +++ b/tests/test_alpaca_provider.py @@ -1,6 +1,7 @@ """Tests for Alpaca data provider module.""" import time +from datetime import UTC, datetime, timedelta from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -297,6 +298,76 @@ def test_feed_param_sent_for_stock(self): assert mock_get.call_args.kwargs["params"]["feed"] == "sip" + @pytest.mark.parametrize( + ("feed", "delay", "end", "cut"), + [ + ("sip", 15, "today", True), # a date-only end covers the whole day + ("sip", 15, "now", True), + ("sip", 15, "2024-01-05", False), # long past: sent unchanged + ("sip", 0, "today", False), # paid plan: no cut + ("iex", 15, "today", False), # the free feed has no delay rule + ], + ) + def test_sip_end_stops_before_the_recent_window(self, feed, delay, end, cut): + """A SIP request reaching the last minutes ends sip_delay_minutes before now.""" + provider = AlpacaDataProvider( + api_key="k", api_secret="s", feed=feed, sip_delay_minutes=delay + ) + now = datetime.now(UTC) + requested = { + "today": now.strftime("%Y-%m-%d"), + "now": now.strftime("%Y-%m-%dT%H:%M:%SZ"), + }.get(end, end) + + with ( + patch.object(provider.session, "get", return_value=_page_response([])) as mock_get, + patch.object(provider.rate_limiter, "acquire"), + ): + provider._fetch_raw_data("AAPL", "2024-01-01", requested, "daily") + + sent = mock_get.call_args.kwargs["params"]["end"] + if not cut: + assert sent == requested + return + sent_at = datetime.fromisoformat(sent) + assert now - timedelta(minutes=delay, seconds=5) <= sent_at + assert sent_at <= now - timedelta(minutes=delay) + timedelta(seconds=1) + + def test_negative_sip_delay_raises(self): + """A negative delay is a configuration error, not a silent no-op.""" + with pytest.raises(DataValidationError): + AlpacaDataProvider(api_key="k", api_secret="s", sip_delay_minutes=-1) + + def test_free_plan_sip_request_up_to_today_ends_before_the_refused_window(self): + """fetch_ohlcv up to today, as `update` asks, ends 15 minutes before now (#151).""" + provider = AlpacaDataProvider(api_key="k", api_secret="s", feed="sip") + now = datetime.now(UTC) + + with ( + patch.object( + provider.session, "get", return_value=_page_response(STOCK_BARS) + ) as mock_get, + patch.object(provider.rate_limiter, "acquire"), + ): + provider.fetch_ohlcv("AAPL", "2024-01-01", now.strftime("%Y-%m-%d"), "daily") + + sent = mock_get.call_args.kwargs["params"]["end"] + # Alpaca reads a date-only end as the whole day, which reaches into the refused window. + assert "T" in sent, f"date-only end {sent!r} covers the last 15 minutes" + assert datetime.fromisoformat(sent) <= now - timedelta(minutes=15) + timedelta(seconds=1) + + def test_403_reports_alpacas_reason(self, provider): + """A 403 carries Alpaca's own message, which tells a plan limit from a bad key (#151).""" + response = _page_response([], status=403) + response.text = '{"message":"subscription does not permit querying recent SIP data"}' + + with ( + patch.object(provider.session, "get", return_value=response), + patch.object(provider.rate_limiter, "acquire"), + ): + with pytest.raises(AuthenticationError, match="recent SIP data"): + provider.fetch_ohlcv("AAPL", "2024-01-01", "2024-01-05", "daily") + def test_fetch_429_raises_rate_limit(self, provider): """A 429 maps to RateLimitError.""" mock_response = MagicMock() From a8ca0198d252bb568edd3e7c782b75bfc98965eb Mon Sep 17 00:00:00 2001 From: Alessandro <17289614+0x0f0f0f@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:45:58 +0100 Subject: [PATCH 2/5] feat(alpaca): weekly and monthly bars, multi-symbol stock fetch fetch_batch_ohlcv sends up to chunk_size stock tickers per request to /v2/stocks/bars and returns one long frame in the canonical schema, each ticker validated alone. Tickers without bars are absent, which makes monthly bars a probe for which tickers traded, delisted ones included. Pagination moves into _paginate, shared with the single-symbol path. --- docs/providers/alpaca.md | 24 ++++++ src/ml4t/data/providers/alpaca.py | 124 +++++++++++++++++++++++++++++- tests/test_alpaca_provider.py | 79 +++++++++++++++++++ 3 files changed, 224 insertions(+), 3 deletions(-) diff --git a/docs/providers/alpaca.md b/docs/providers/alpaca.md index ba639fc6..5349c9c0 100644 --- a/docs/providers/alpaca.md +++ b/docs/providers/alpaca.md @@ -83,12 +83,36 @@ crypto slash is preserved (e.g. `BTC/USD`). | `5m` / `5minute` | ✅ | | `15m` / `15minute` | ✅ | | `30m` / `30minute` | ✅ | +| `weekly` / `1w` | ✅ | +| `monthly` / `1mo` | ✅ | `start`/`end` accept `YYYY-MM-DD` dates or RFC-3339 datetimes (both inclusive); datetime bounds are the natural shape for sub-day minute/hour windows. --- +## Many Stocks at Once + +`fetch_batch_ohlcv` sends up to `chunk_size` (default 1,000) stock tickers per +request to the multi-symbol endpoint. The symbols of a request share each page +of 10,000 bars, so a bulk load takes about one request per 10,000 bars rather +than one per symbol. A ticker without bars in the range is simply absent, which +makes monthly bars a cheap probe of which tickers traded, delisted ones +included. One invalid ticker string fails its whole request with HTTP 400. + +```python +provider = AlpacaDataProvider(feed="sip", adjustment="raw") +months = provider.fetch_batch_ohlcv( + ["AAPL", "TWTR", "SIVB"], "2016-01-01", "2024-12-31", frequency="monthly" +) +``` + +The result is one long frame in the canonical schema. Store it per symbol with +`DataManager.import_data`, or keep using `fetch_ohlcv` through `update` for +incremental refreshes. + +--- + ## Feeds and Adjustment - `feed="iex"` (default): the free feed, real-time but served from a single diff --git a/src/ml4t/data/providers/alpaca.py b/src/ml4t/data/providers/alpaca.py index 80bd388e..2acb24c3 100644 --- a/src/ml4t/data/providers/alpaca.py +++ b/src/ml4t/data/providers/alpaca.py @@ -2,8 +2,10 @@ Alpaca provides long-history, high-frequency market data across multiple asset classes including US equities and crypto, served over a historical REST API. -Daily, hourly, and minute OHLCV bars (1/5/15/30-minute) are supported for both -asset classes from a single symbol-routed provider. +Monthly, weekly, daily, hourly, and minute OHLCV bars (1/5/15/30-minute) are +supported for both asset classes from a single symbol-routed provider. +``fetch_batch_ohlcv`` loads many stocks per request through the multi-symbol +stock endpoint. API Documentation: https://docs.alpaca.markets/us/docs/about-market-data-api @@ -186,8 +188,21 @@ class AlpacaDataProvider(AsyncSessionMixin, BaseProvider): "15minute": "15Min", "30m": "30Min", "30minute": "30Min", + "weekly": "1Week", + "week": "1Week", + "1w": "1Week", + "1week": "1Week", + "monthly": "1Month", + "month": "1Month", + "1mo": "1Month", + "1month": "1Month", } + # Symbols per multi-symbol stock request in fetch_batch_ohlcv. The page limit + # is shared by all symbols of a request, so a larger chunk costs no extra + # pages; the bound keeps the query string short. + BATCH_CHUNK_SIZE: ClassVar[int] = 1000 + def __init__( self, api_key: str | None = None, @@ -767,7 +782,20 @@ def _fetch_raw_data( """ resolved = self._resolve_asset_class(symbol, asset_class) endpoint, params = self._bars_request(symbol, start, end, frequency, resolved) + return self._paginate(endpoint, params, symbol) + + def _paginate(self, endpoint: str, params: dict[str, Any], label: str) -> dict[str, Any]: + """Request every page of one bars query and merge the pages. + + Args: + endpoint: The bars endpoint URL. + params: The query parameters of the first page. + label: The requested symbol or symbols, for error context. + Returns: + ``{"bars": merged}``: a list for the single-symbol endpoint, a + per-symbol dict for the multi-symbol endpoints. + """ accumulated: Any = None token: str | None = None seen_tokens: set[str] = set() @@ -777,7 +805,7 @@ def _fetch_raw_data( # mutating one shared dict would otherwise rewrite the token on # earlier requests that already went out. page_params = {**params, "page_token": token} if token else params - payload = self._get_page(endpoint, page_params, symbol) + payload = self._get_page(endpoint, page_params, label) page_count += 1 accumulated = self._merge_bars(accumulated, payload.get("bars")) token = self._next_page_token(payload, seen_tokens, page_count) @@ -1078,3 +1106,93 @@ async def _fetch_and_process() -> pl.DataFrame: ) return validated_data + + def fetch_batch_ohlcv( + self, + symbols: list[str], + start: str, + end: str, + frequency: str = "daily", + chunk_size: int | None = None, + ) -> pl.DataFrame: + """Fetch OHLCV bars of many stocks through the multi-symbol endpoint. + + One request carries up to ``chunk_size`` symbols, and they share each + page of up to ``PAGE_LIMIT`` bars, so a bulk load needs about one + request per ``PAGE_LIMIT`` bars instead of one per symbol. A ticker + with no bars in the range is absent from the result, which makes this + also the cheap way to probe which tickers traded. A string that is not + a valid ticker fails its whole chunk with HTTP 400. + + Use ``fetch_ohlcv`` for incremental updates through ``DataManager``. + + Args: + symbols: Stock tickers, case-insensitive. Crypto pairs are refused. + start: Inclusive start, ``YYYY-MM-DD`` or RFC-3339 datetime. + end: Inclusive end, ``YYYY-MM-DD`` or RFC-3339 datetime. + frequency: Canonical frequency key or alias. + chunk_size: Symbols per request; ``BATCH_CHUNK_SIZE`` when ``None``. + + Returns: + One long DataFrame in the canonical OHLCV schema + ``[timestamp, symbol, open, high, low, close, volume]``, sorted by + timestamp and symbol. + + Raises: + ValueError: If a symbol is empty, a date bound is malformed, start + is after end, or ``chunk_size`` is not positive. + DataValidationError: If a symbol is a crypto pair, the frequency is + unsupported, or a response cannot be transformed or validated. + AuthenticationError: If the credentials are rejected (HTTP 401/403). + RateLimitError: If HTTP 429 persists past the per-page retries. + NetworkError: On other HTTP, transport, or JSON-decoding failures. + CircuitBreakerOpenError: If repeated failures have opened the + circuit breaker. + """ + size = self.BATCH_CHUNK_SIZE if chunk_size is None else chunk_size + if size < 1: + raise ValueError("chunk_size must be positive") + tickers = list(dict.fromkeys(symbol.strip().upper() for symbol in symbols)) + for ticker in tickers: + if not ticker: + raise ValueError("Symbol cannot be empty") + if "/" in ticker: + raise DataValidationError( + provider="alpaca", + message="fetch_batch_ohlcv serves stocks; fetch crypto with fetch_ohlcv", + field="symbols", + value=ticker, + ) + if not tickers: + return self._create_empty_dataframe() + self._validate_inputs(tickers[0], start, end, frequency) + endpoint = f"{self.base_url}/v2/stocks/bars" + params = self._stock_bars_params(frequency, start, end) + + def _fetch_and_process() -> pl.DataFrame: + frames = [] + for first in range(0, len(tickers), size): + chunk = tickers[first : first + size] + raw = self._paginate( + endpoint, {**params, "symbols": ",".join(chunk)}, f"{chunk[0]}..{chunk[-1]}" + ) + bars = raw["bars"] if isinstance(raw["bars"], dict) else {} + # The OHLCV contract is per symbol, so each ticker is validated alone. + frames.extend( + self._validate_ohlcv( + self._bars_to_dataframe(rows, ticker, ticker), self.name, ticker + ) + for ticker, rows in bars.items() + if rows + ) + self.logger.info( + "Fetched batch chunk", + done=first + len(chunk), + total=len(tickers), + provider=self.name, + ) + if not frames: + return self._create_empty_dataframe() + return pl.concat(frames).sort(["timestamp", "symbol"]) + + return self._with_circuit_breaker(_fetch_and_process) diff --git a/tests/test_alpaca_provider.py b/tests/test_alpaca_provider.py index ca717889..4cbc70a2 100644 --- a/tests/test_alpaca_provider.py +++ b/tests/test_alpaca_provider.py @@ -212,6 +212,10 @@ class TestFrequencyMapping: ("15minute", "15Min"), ("30m", "30Min"), ("30minute", "30Min"), + ("weekly", "1Week"), + ("1w", "1Week"), + ("monthly", "1Month"), + ("1mo", "1Month"), ], ) def test_frequency_maps_to_timeframe(self, provider, frequency, expected): @@ -1365,3 +1369,78 @@ def test_provider_classes_cached(self): assert first is second assert "alpaca" in first + + +class TestFetchBatchStocks: + """Tests for the multi-symbol stock fetch.""" + + def _call(self, provider, responses, symbols, **kwargs): + with ( + patch.object(provider.session, "get", side_effect=responses) as mock_get, + patch.object(provider.rate_limiter, "acquire"), + ): + df = provider.fetch_batch_ohlcv(symbols, "2024-01-01", "2024-01-31", **kwargs) + return df, mock_get.call_args_list + + def test_chunks_symbols_and_merges_pages(self, provider): + """Symbols go out in chunks; a chunk's pages merge per symbol into one long frame.""" + responses = [ + _page_response({"AAPL": STOCK_BARS[:1], "MSFT": STOCK_BARS[:1]}, token="p2"), + _page_response({"MSFT": STOCK_BARS[1:]}), + _page_response({"TWTR": STOCK_BARS}), + ] + + df, calls = self._call(provider, responses, ["aapl", "MSFT", "AAPL", "TWTR"], chunk_size=2) + + assert [call.args[0] for call in calls] == [ + "https://data.alpaca.markets/v2/stocks/bars" + ] * 3 + sent = [call.kwargs["params"] for call in calls] + assert [params["symbols"] for params in sent] == ["AAPL,MSFT", "AAPL,MSFT", "TWTR"] + assert sent[1]["page_token"] == "p2" + assert sent[0]["feed"] == "iex" + assert df.columns == ["timestamp", "symbol", "open", "high", "low", "close", "volume"] + assert df.group_by("symbol").len().sort("symbol").rows() == [ + ("AAPL", 1), + ("MSFT", 2), + ("TWTR", 2), + ] + assert df.select(pl.col("timestamp").is_sorted()).item() + + def test_tickers_without_bars_are_absent(self, provider): + """A ticker that never traded is missing from the result, not an error.""" + df, _ = self._call(provider, [_page_response({"AAPL": STOCK_BARS})], ["AAPL", "ZZZZQ"]) + + assert df["symbol"].unique().to_list() == ["AAPL"] + + def test_no_bars_returns_canonical_empty_frame(self, provider): + """No bars at all yields the canonical empty schema.""" + df, _ = self._call(provider, [_page_response({})], ["ZZZZQ"]) + + assert df.is_empty() + assert "close" in df.columns + + def test_monthly_frequency_sent(self, provider): + """Monthly bars, the cheap probe for which tickers traded, map to 1Month.""" + _, calls = self._call(provider, [_page_response({})], ["AAPL"], frequency="monthly") + + assert calls[0].kwargs["params"]["timeframe"] == "1Month" + + def test_crypto_pair_refused(self, provider): + """Crypto has its own endpoint; the stock batch refuses a pair before any request.""" + with pytest.raises(DataValidationError): + self._call(provider, [], ["AAPL", "BTC/USD"]) + + def test_nonpositive_chunk_size_refused(self, provider): + """A zero chunk size would never finish; it is refused up front.""" + with pytest.raises(ValueError, match="chunk_size"): + self._call(provider, [], ["AAPL"], chunk_size=0) + + def test_invalid_ticker_fails_the_request(self, provider): + """Alpaca rejects a whole request over one invalid ticker with HTTP 400.""" + response = _page_response({}, status=400) + response.text = '{"message":"invalid symbol: 0029900E0"}' + + # Every non-200 is retried as a NetworkError, so the 400 comes back each attempt. + with pytest.raises(NetworkError, match="invalid symbol"): + self._call(provider, [response] * 3, ["AAPL", "0029900E0"]) From 14ff110ecc37d2a33e7840941638ca25120f0762 Mon Sep 17 00:00:00 2001 From: Alessandro <17289614+0x0f0f0f@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:47:03 +0100 Subject: [PATCH 3/5] feat(alpaca): asof option for stock symbol mapping Alpaca maps a ticker to the company holding it on asof, today by default: a renamed company's history appears under both tickers and the multi-symbol endpoint drops the old one. asof='-' returns the bars traded under each ticker, which keeps a store free of duplicate and missing histories; an InstrumentRegistry then joins renames. --- docs/providers/alpaca.md | 20 ++++++++++++++++++++ src/ml4t/data/providers/alpaca.py | 29 ++++++++++++++++++++++++++++- tests/test_alpaca_provider.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/docs/providers/alpaca.md b/docs/providers/alpaca.md index 5349c9c0..1590dadf 100644 --- a/docs/providers/alpaca.md +++ b/docs/providers/alpaca.md @@ -113,6 +113,26 @@ incremental refreshes. --- +## Renamed and Reused Tickers + +Alpaca maps a stock ticker to the company that holds it on an `asof` date, +today by default, and returns that company's whole history. Measured on daily +and monthly bars since 2016: + +| Request | Default (`asof` today) | `asof="-"` | `asof="2020-01-01"` | +|---|---|---|---| +| `META` | Meta's whole history, FB years included | a fund from 2021-06, then Meta from 2022-06 | as `"-"` | +| `FB` | absent from the multi-symbol endpoint; the single-symbol endpoint returns the `"-"` bars | Meta until 2022-06, then the next holder of FB | Meta's whole history, META years included | +| `BBBY` | as `"-"` | Bed Bath & Beyond to 2023-05, then a later holder from 2025 | Bed Bath & Beyond only | + +With the default, a renamed company's history appears twice, under both its +tickers, and the multi-symbol endpoint drops the old ticker. With `asof="-"` +each bar appears once, under the ticker it traded as, whoever traded it; joining +a company's tickers across a rename, and splitting a reused ticker, is then the +job of an `InstrumentRegistry`. + +--- + ## Feeds and Adjustment - `feed="iex"` (default): the free feed, real-time but served from a single diff --git a/src/ml4t/data/providers/alpaca.py b/src/ml4t/data/providers/alpaca.py index 2acb24c3..46c98fa9 100644 --- a/src/ml4t/data/providers/alpaca.py +++ b/src/ml4t/data/providers/alpaca.py @@ -50,6 +50,15 @@ ``"dividend"``, or ``"all"`` at construction for adjusted bars. Crypto bars have no adjustment concept. +Symbol mapping (stocks): +- Alpaca maps a ticker to the company that holds it on the ``asof`` date, + today by default, and returns that company's whole history. A renamed + company's history then appears under both its tickers (META includes the FB + years), and the multi-symbol endpoint drops the old ticker (FB). ``asof="-"`` + turns the mapping off, so each ticker returns the bars traded under it, + whoever traded them; ``asof="YYYY-MM-DD"`` maps as of that date. Left unset, + Alpaca's default applies. + Rate limiting: - ``DEFAULT_RATE_LIMIT`` is a conservative client-side throttle of 200 calls per minute, reflecting the Basic (free) plan figure documented at @@ -211,6 +220,7 @@ def __init__( adjustment: str = "raw", rate_limit: tuple[int, float] | None = None, sip_delay_minutes: int = 15, + asof: str | None = None, **kwargs: Any, ) -> None: """Initialize the Alpaca data provider. @@ -230,6 +240,9 @@ def __init__( sip_delay_minutes: With ``feed="sip"``, a stock request ends at least this many minutes before now, the window the free plan refuses. ``0`` sends ``end`` unchanged. Ignored for other feeds and crypto. + asof: Stock symbol mapping date, ``"YYYY-MM-DD"``, or ``"-"`` for + none: each ticker then returns the bars traded under it. ``None`` + leaves Alpaca's default, a mapping as of today. Ignored for crypto. **kwargs: Additional arguments forwarded to BaseProvider. Raises: @@ -268,6 +281,17 @@ def __init__( value=sip_delay_minutes, ) self.sip_delay = timedelta(minutes=sip_delay_minutes) + if asof is not None and asof != "-": + try: + datetime.strptime(asof, "%Y-%m-%d") + except ValueError as err: + raise DataValidationError( + provider="alpaca", + message=f"Invalid asof '{asof}': expected YYYY-MM-DD or '-'", + field="asof", + value=asof, + ) from err + self.asof = asof self.base_url = "https://data.alpaca.markets" # Built once, reused for both the sync and async sessions so the two @@ -459,7 +483,7 @@ def _stock_bars_params(self, frequency: str, start: str, end: str) -> dict[str, The query parameter mapping, including the configured data feed and price adjustment. """ - return { + params = { "timeframe": self._map_frequency(frequency), "start": start, "end": self._stock_end(end), @@ -467,6 +491,9 @@ def _stock_bars_params(self, frequency: str, start: str, end: str) -> dict[str, "feed": self.feed, "adjustment": self.adjustment, } + if self.asof is not None: + params["asof"] = self.asof + return params def _stock_end(self, end: str) -> str: """Cut a SIP request's end to before the window the plan refuses. diff --git a/tests/test_alpaca_provider.py b/tests/test_alpaca_provider.py index 4cbc70a2..d095e578 100644 --- a/tests/test_alpaca_provider.py +++ b/tests/test_alpaca_provider.py @@ -302,6 +302,35 @@ def test_feed_param_sent_for_stock(self): assert mock_get.call_args.kwargs["params"]["feed"] == "sip" + @pytest.mark.parametrize("asof", ["-", "2020-01-01"]) + def test_asof_sent_for_stock_and_batch(self, asof): + """The symbol-mapping date reaches both stock endpoints; unset, Alpaca's default applies.""" + provider = AlpacaDataProvider(api_key="k", api_secret="s", asof=asof) + + with ( + patch.object(provider.session, "get", return_value=_page_response({})) as mock_get, + patch.object(provider.rate_limiter, "acquire"), + ): + provider._fetch_raw_data("FB", "2016-01-01", "2024-01-05", "daily") + provider.fetch_batch_ohlcv(["FB", "BBBY"], "2016-01-01", "2024-01-05") + + assert [call.kwargs["params"]["asof"] for call in mock_get.call_args_list] == [asof, asof] + + def test_asof_unset_not_sent(self, provider): + """Without asof the request carries none, so Alpaca maps as of today.""" + with ( + patch.object(provider.session, "get", return_value=_page_response([])) as mock_get, + patch.object(provider.rate_limiter, "acquire"), + ): + provider._fetch_raw_data("FB", "2016-01-01", "2024-01-05", "daily") + + assert "asof" not in mock_get.call_args.kwargs["params"] + + def test_invalid_asof_raises(self): + """A malformed date would be rejected by Alpaca only at request time.""" + with pytest.raises(DataValidationError): + AlpacaDataProvider(api_key="k", api_secret="s", asof="2020/01/01") + @pytest.mark.parametrize( ("feed", "delay", "end", "cut"), [ From 03544bfcdff6abb71fb59455b054fa707c94775e Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Mon, 23 Nov 2026 18:54:06 -0500 Subject: [PATCH 4/5] fix(alpaca): make SIP delay explicit and handle empty windows --- docs/providers/alpaca.md | 12 ++-- src/ml4t/data/providers/alpaca.py | 36 ++++++++---- tests/test_alpaca_provider.py | 2 +- tests/test_alpaca_sip_boundaries.py | 90 +++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 17 deletions(-) create mode 100644 tests/test_alpaca_sip_boundaries.py diff --git a/docs/providers/alpaca.md b/docs/providers/alpaca.md index ba639fc6..0e631274 100644 --- a/docs/providers/alpaca.md +++ b/docs/providers/alpaca.md @@ -96,9 +96,11 @@ datetime bounds are the natural shape for sub-day minute/hour windows. - `feed="sip"`: the consolidated tape (100% of US volume, all exchanges). Real-time on paid plans; the free Basic plan can still query SIP bars, only not the most recent 15 minutes, and answers such a request with HTTP 403. The - provider therefore ends a SIP stock request `sip_delay_minutes` (default 15) - before now, so `end` may be today, as incremental `update` requests are. Pass - `sip_delay_minutes=0` on a paid plan. + free-plan caller must set `sip_delay_minutes=15` to end SIP stock requests + before that window, including incremental `update` requests ending today. + The default `0` preserves real-time access for paid plans. If clipping leaves + no available interval, the provider returns a canonical empty frame without + sending an invalid request. - `feed="otc"` (over-the-counter) and `feed="boats"` (Blue Ocean overnight) are also accepted. Any other value raises `DataValidationError` at construction. - `adjustment="raw"` (default, Alpaca's own default): stock bars are **not** @@ -106,7 +108,7 @@ datetime bounds are the natural shape for sub-day minute/hour windows. `"all"` for adjusted bars. Crypto has no adjustment concept. ```python -provider = AlpacaDataProvider(feed="sip", adjustment="all") +provider = AlpacaDataProvider(feed="sip", adjustment="all", sip_delay_minutes=15) ``` In a `ml4t.data.yaml`, the same settings go under `extra` of a named provider: @@ -115,7 +117,7 @@ In a `ml4t.data.yaml`, the same settings go under `extra` of a named provider: providers: - name: alpaca_sip type: alpaca - extra: {feed: sip, adjustment: all} + extra: {feed: sip, adjustment: all, sip_delay_minutes: 15} ``` --- diff --git a/src/ml4t/data/providers/alpaca.py b/src/ml4t/data/providers/alpaca.py index 80bd388e..cff17123 100644 --- a/src/ml4t/data/providers/alpaca.py +++ b/src/ml4t/data/providers/alpaca.py @@ -34,10 +34,9 @@ the consolidated tape. - ``feed="sip"`` selects the consolidated tape (100% of US market volume across all exchanges). It is real time on paid plans; the free Basic plan can still - query SIP bars, only not the most recent 15 minutes. A SIP request that would - reach into that window is cut to end ``sip_delay_minutes`` (default 15) before - now, so a request ``end`` of today works on the free plan. Pass - ``sip_delay_minutes=0`` on a paid plan. + query SIP bars, only not the most recent 15 minutes. Set + ``sip_delay_minutes=15`` explicitly for the free plan to clip recent requests. + The default ``0`` preserves the requested end for real-time subscriptions. - ``"otc"`` (over-the-counter) and ``"boats"`` (Blue Ocean overnight) are also accepted; any other value raises ``DataValidationError`` at construction. - Crypto has a single consolidated feed, so ``feed`` does not apply to it. @@ -195,7 +194,7 @@ def __init__( feed: str = "iex", adjustment: str = "raw", rate_limit: tuple[int, float] | None = None, - sip_delay_minutes: int = 15, + sip_delay_minutes: int = 0, **kwargs: Any, ) -> None: """Initialize the Alpaca data provider. @@ -214,7 +213,8 @@ def __init__( rate_limit: Optional custom (calls, period_seconds) override. sip_delay_minutes: With ``feed="sip"``, a stock request ends at least this many minutes before now, the window the free plan refuses. - ``0`` sends ``end`` unchanged. Ignored for other feeds and crypto. + Default ``0`` sends ``end`` unchanged. Set ``15`` for the Basic plan. + Ignored for other feeds and crypto. **kwargs: Additional arguments forwarded to BaseProvider. Raises: @@ -245,10 +245,14 @@ def __init__( ) self.feed = normalized_feed self.adjustment = adjustment - if sip_delay_minutes < 0: + if ( + not isinstance(sip_delay_minutes, int) + or isinstance(sip_delay_minutes, bool) + or sip_delay_minutes < 0 + ): raise DataValidationError( provider="alpaca", - message="sip_delay_minutes cannot be negative", + message="sip_delay_minutes must be a non-negative integer", field="sip_delay_minutes", value=sip_delay_minutes, ) @@ -351,6 +355,8 @@ def _validate_inputs( try: start_dt = self._parse_time_bound(start) end_dt = self._parse_time_bound(end) + if len(end) == 10: + end_dt = end_dt.replace(hour=23, minute=59, second=59, microsecond=999999) except ValueError as e: raise ValueError( f"Invalid date format (expected YYYY-MM-DD or RFC-3339 datetime): {e}" @@ -470,7 +476,7 @@ def _stock_end(self, end: str) -> str: if self.feed != "sip" or not self.sip_delay: return end bound = self._parse_time_bound(end) - if "T" not in end: + if len(end) == 10: bound += timedelta(days=1) latest = datetime.now(UTC) - self.sip_delay if bound <= latest: @@ -606,10 +612,10 @@ def _check_response_status(self, response: Any, symbol: str) -> None: if status_code == 429: raise RateLimitError(provider="alpaca", retry_after=self._retry_after_seconds(response)) if status_code in (401, 403): - # The body says why, e.g. a 403 for SIP data the plan does not cover. raise AuthenticationError( provider="alpaca", - message=f"Invalid API key or unauthorized access: {response.text}", + message=f"{'Authentication failed' if status_code == 401 else 'Access denied'}: " + f"{response.text}", ) if status_code == 404: raise DataNotAvailableError(provider="alpaca", symbol=symbol) @@ -767,6 +773,10 @@ def _fetch_raw_data( """ resolved = self._resolve_asset_class(symbol, asset_class) endpoint, params = self._bars_request(symbol, start, end, frequency, resolved) + if params["end"] != end and self._parse_time_bound(start) > self._parse_time_bound( + params["end"] + ): + return {"bars": []} accumulated: Any = None token: str | None = None @@ -819,6 +829,10 @@ async def _fetch_raw_data_async( """ resolved = self._resolve_asset_class(symbol, asset_class) endpoint, params = self._bars_request(symbol, start, end, frequency, resolved) + if params["end"] != end and self._parse_time_bound(start) > self._parse_time_bound( + params["end"] + ): + return {"bars": []} accumulated: Any = None token: str | None = None diff --git a/tests/test_alpaca_provider.py b/tests/test_alpaca_provider.py index ca717889..96d14554 100644 --- a/tests/test_alpaca_provider.py +++ b/tests/test_alpaca_provider.py @@ -340,7 +340,7 @@ def test_negative_sip_delay_raises(self): def test_free_plan_sip_request_up_to_today_ends_before_the_refused_window(self): """fetch_ohlcv up to today, as `update` asks, ends 15 minutes before now (#151).""" - provider = AlpacaDataProvider(api_key="k", api_secret="s", feed="sip") + provider = AlpacaDataProvider(api_key="k", api_secret="s", feed="sip", sip_delay_minutes=15) now = datetime.now(UTC) with ( diff --git a/tests/test_alpaca_sip_boundaries.py b/tests/test_alpaca_sip_boundaries.py new file mode 100644 index 00000000..26e0d574 --- /dev/null +++ b/tests/test_alpaca_sip_boundaries.py @@ -0,0 +1,90 @@ +"""SIP delays are explicit and never create an invalid request window.""" + +from datetime import UTC, datetime +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from ml4t.data.core.exceptions import AuthenticationError, DataValidationError +from ml4t.data.providers.alpaca import AlpacaDataProvider + + +def test_paid_sip_default_preserves_requested_recent_end(): + end = "2026-11-23T15:59:00Z" + with ( + AlpacaDataProvider(api_key="k", api_secret="s", feed="sip") as provider, + patch("ml4t.data.providers.alpaca.datetime", wraps=datetime) as clock, + patch.object(provider.session, "get") as get, + ): + clock.now.return_value = datetime(2026, 11, 23, 16, tzinfo=UTC) + get.return_value = MagicMock(status_code=200) + get.return_value.json.return_value = {"bars": [], "next_page_token": None} + provider.fetch_ohlcv("SPY", "2026-11-23T15:58:00Z", end, "minute") + assert get.call_args.kwargs["params"]["end"] == end + + +def test_datetime_start_with_inclusive_date_end_is_not_an_empty_window(): + with ( + AlpacaDataProvider(api_key="k", api_secret="s", feed="sip") as provider, + patch.object(provider.session, "get") as get, + ): + get.return_value = MagicMock(status_code=200) + get.return_value.json.return_value = {"bars": [], "next_page_token": None} + provider.fetch_ohlcv("SPY", "2026-11-20T16:00:00Z", "2026-11-20", "minute") + assert get.call_args.kwargs["params"]["end"] == "2026-11-20" + + +@pytest.mark.parametrize( + "start,end", + [ + ("2026-11-23T15:50:00Z", "2026-11-23T15:59:00Z"), + ("2026-11-24", "2026-11-24"), + ], +) +def test_clipped_sip_window_without_available_bars_does_not_request(start, end): + with ( + AlpacaDataProvider( + api_key="k", api_secret="s", feed="sip", sip_delay_minutes=15 + ) as provider, + patch("ml4t.data.providers.alpaca.datetime", wraps=datetime) as clock, + patch.object(provider.session, "get") as get, + ): + clock.now.return_value = datetime(2026, 11, 23, 16, tzinfo=UTC) + result = provider.fetch_ohlcv("SPY", start, end, "minute") + assert result.is_empty() + assert result.columns == list(provider.CANONICAL_COLUMNS) + get.assert_not_called() + + +@pytest.mark.asyncio +async def test_async_clipped_sip_window_does_not_request(): + with ( + AlpacaDataProvider( + api_key="k", api_secret="s", feed="sip", sip_delay_minutes=15 + ) as provider, + patch("ml4t.data.providers.alpaca.datetime", wraps=datetime) as clock, + patch.object(provider, "_aget", new_callable=AsyncMock) as get, + ): + clock.now.return_value = datetime(2026, 11, 23, 0, 5, tzinfo=UTC) + result = await provider.fetch_ohlcv_async("SPY", "2026-11-23", "2026-11-23") + assert result.is_empty() + get.assert_not_called() + + +def test_sip_subscription_denial_does_not_claim_invalid_credentials(): + response = MagicMock(status_code=403) + response.text = '{"message":"subscription does not permit querying recent SIP data"}' + with ( + AlpacaDataProvider(api_key="k", api_secret="s", feed="sip") as provider, + patch.object(provider.session, "get", return_value=response) as get, + ): + with pytest.raises(AuthenticationError, match="subscription does not permit") as error: + provider.fetch_ohlcv("SPY", "2026-11-19", "2026-11-20") + assert "Invalid API key" not in str(error.value) + get.assert_called_once() + + +@pytest.mark.parametrize("delay", [-1, True, 1.5, "15", None]) +def test_invalid_sip_delay_is_a_configuration_error(delay): + with pytest.raises(DataValidationError, match="sip_delay_minutes"): + AlpacaDataProvider(api_key="k", api_secret="s", sip_delay_minutes=delay) From 9a2e25e8ab93370a81639e752547ded58efddc70 Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Mon, 23 Nov 2026 18:56:33 -0500 Subject: [PATCH 5/5] fix(alpaca): validate batch responses and clipped query windows --- src/ml4t/data/providers/alpaca.py | 22 ++++- tests/test_alpaca_batch_contract.py | 120 ++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 tests/test_alpaca_batch_contract.py diff --git a/src/ml4t/data/providers/alpaca.py b/src/ml4t/data/providers/alpaca.py index 9e6287bd..75acfa52 100644 --- a/src/ml4t/data/providers/alpaca.py +++ b/src/ml4t/data/providers/alpaca.py @@ -1191,8 +1191,8 @@ def fetch_batch_ohlcv( circuit breaker. """ size = self.BATCH_CHUNK_SIZE if chunk_size is None else chunk_size - if size < 1: - raise ValueError("chunk_size must be positive") + if not isinstance(size, int) or isinstance(size, bool) or size < 1: + raise ValueError("chunk_size must be a positive integer") tickers = list(dict.fromkeys(symbol.strip().upper() for symbol in symbols)) for ticker in tickers: if not ticker: @@ -1209,6 +1209,10 @@ def fetch_batch_ohlcv( self._validate_inputs(tickers[0], start, end, frequency) endpoint = f"{self.base_url}/v2/stocks/bars" params = self._stock_bars_params(frequency, start, end) + if params["end"] != end and self._parse_time_bound(start) > self._parse_time_bound( + params["end"] + ): + return self._create_empty_dataframe() def _fetch_and_process() -> pl.DataFrame: frames = [] @@ -1217,7 +1221,19 @@ def _fetch_and_process() -> pl.DataFrame: raw = self._paginate( endpoint, {**params, "symbols": ",".join(chunk)}, f"{chunk[0]}..{chunk[-1]}" ) - bars = raw["bars"] if isinstance(raw["bars"], dict) else {} + bars = raw["bars"] + if not isinstance(bars, dict): + if bars: + raise DataValidationError( + provider="alpaca", message="Batch response must map symbols to bars" + ) + bars = {} + unexpected = set(bars) - set(chunk) + if unexpected: + raise DataValidationError( + provider="alpaca", + message=f"Batch response contains unrequested symbols: {sorted(unexpected)}", + ) # The OHLCV contract is per symbol, so each ticker is validated alone. frames.extend( self._validate_ohlcv( diff --git a/tests/test_alpaca_batch_contract.py b/tests/test_alpaca_batch_contract.py new file mode 100644 index 00000000..59662f33 --- /dev/null +++ b/tests/test_alpaca_batch_contract.py @@ -0,0 +1,120 @@ +"""Public batch requests preserve pagination and stock identity contracts.""" + +from datetime import UTC, datetime +from unittest.mock import MagicMock, patch + +import pytest + +from ml4t.data.core.exceptions import DataValidationError +from ml4t.data.providers.alpaca import AlpacaDataProvider + + +def response(bars, token=None): + result = MagicMock(status_code=200) + result.json.return_value = {"bars": bars, "next_page_token": token} + return result + + +def bar(timestamp, close): + return {"t": timestamp, "o": 100, "h": 110, "l": 90, "c": close, "v": 1000} + + +@pytest.mark.parametrize("frequency,timeframe", [("weekly", "1Week"), ("monthly", "1Month")]) +def test_batch_pages_preserve_query_bounds_asof_and_missing_symbols(frequency, timeframe): + first = "2026-01-01T05:00:00Z" + last = "2026-02-02T05:00:00Z" + with ( + AlpacaDataProvider(api_key="k", api_secret="s", asof="-") as provider, + patch.object( + provider.session, + "get", + side_effect=[ + response({"SPY": [bar(first, 101)]}, "p2"), + response({"SPY": [bar(last, 102)]}), + response({"QQQ": [bar(first, 103)]}), + ], + ) as get, + ): + result = provider.fetch_batch_ohlcv( + ["spy", "MISSING", "SPY", "qqq"], first, last, frequency, chunk_size=2 + ) + params = [call.kwargs["params"] for call in get.call_args_list] + assert [query["symbols"] for query in params] == ["SPY,MISSING", "SPY,MISSING", "QQQ"] + assert "page_token" not in params[0] + assert params[1]["page_token"] == "p2" + assert "page_token" not in params[2] + for query in params: + assert (query["start"], query["end"], query["asof"], query["timeframe"]) == ( + first, + last, + "-", + timeframe, + ) + assert result.schema == provider.CANONICAL_SCHEMA + assert result.select("symbol", "close").rows() == [ + ("QQQ", 103.0), + ("SPY", 101.0), + ("SPY", 102.0), + ] + assert result["timestamp"].to_list() == [ + datetime(2026, 1, 1, 5, tzinfo=UTC), + datetime(2026, 1, 1, 5, tzinfo=UTC), + datetime(2026, 2, 2, 5, tzinfo=UTC), + ] + + +def test_batch_clipped_empty_sip_interval_does_not_request(): + with ( + AlpacaDataProvider( + api_key="k", api_secret="s", feed="sip", sip_delay_minutes=15 + ) as provider, + patch("ml4t.data.providers.alpaca.datetime", wraps=datetime) as clock, + patch.object(provider.session, "get") as get, + ): + clock.now.return_value = datetime(2026, 11, 23, 16, tzinfo=UTC) + result = provider.fetch_batch_ohlcv( + ["SPY", "QQQ"], "2026-11-23T15:50:00Z", "2026-11-23T15:59:00Z", "minute" + ) + assert result.is_empty() + assert result.schema == provider.CANONICAL_SCHEMA + get.assert_not_called() + + +@pytest.mark.parametrize( + "bars", + [[bar("2026-01-01T05:00:00Z", 100)], {"UNREQUESTED": [bar("2026-01-01T05:00:00Z", 100)]}], +) +def test_batch_rejects_malformed_or_unrequested_symbol_response(bars): + with ( + AlpacaDataProvider(api_key="k", api_secret="s") as provider, + patch.object(provider.session, "get", return_value=response(bars)), + pytest.raises(DataValidationError), + ): + provider.fetch_batch_ohlcv(["SPY"], "2026-01-01", "2026-01-02") + + +def test_batch_repeated_cursor_raises_instead_of_returning_partial_history(): + with ( + AlpacaDataProvider(api_key="k", api_secret="s") as provider, + patch.object( + provider.session, + "get", + side_effect=[ + response({"SPY": [bar("2026-01-01T05:00:00Z", 100)]}, "again"), + response({"SPY": [bar("2026-01-02T05:00:00Z", 101)]}, "again"), + ], + ) as get, + pytest.raises(DataValidationError, match="repeated"), + ): + provider.fetch_batch_ohlcv(["SPY"], "2026-01-01", "2026-01-02") + assert get.call_count == 2 + + +def test_all_missing_batch_returns_typed_empty_frame(): + with ( + AlpacaDataProvider(api_key="k", api_secret="s") as provider, + patch.object(provider.session, "get", return_value=response({})), + ): + result = provider.fetch_batch_ohlcv(["MISSING"], "2026-01-01", "2026-01-02") + assert result.is_empty() + assert result.schema == provider.CANONICAL_SCHEMA