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/2] 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 03544bfcdff6abb71fb59455b054fa707c94775e Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Mon, 23 Nov 2026 18:54:06 -0500 Subject: [PATCH 2/2] 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)