diff --git a/docs/providers/alpaca.md b/docs/providers/alpaca.md index 0e63127..fb95aed 100644 --- a/docs/providers/alpaca.md +++ b/docs/providers/alpaca.md @@ -83,12 +83,56 @@ 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. + +--- + +## 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 cff1712..75acfa5 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 @@ -47,6 +49,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 @@ -185,8 +196,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, @@ -195,6 +219,7 @@ def __init__( adjustment: str = "raw", rate_limit: tuple[int, float] | None = None, sip_delay_minutes: int = 0, + asof: str | None = None, **kwargs: Any, ) -> None: """Initialize the Alpaca data provider. @@ -215,6 +240,9 @@ def __init__( this many minutes before now, the window the free plan refuses. Default ``0`` sends ``end`` unchanged. Set ``15`` for the Basic plan. 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: @@ -257,6 +285,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 @@ -450,7 +489,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), @@ -458,6 +497,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. @@ -777,7 +819,20 @@ def _fetch_raw_data( params["end"] ): return {"bars": []} + 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() @@ -787,7 +842,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) @@ -1092,3 +1147,109 @@ 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 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: + 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) + 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 = [] + 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 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( + 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_batch_contract.py b/tests/test_alpaca_batch_contract.py new file mode 100644 index 0000000..59662f3 --- /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 diff --git a/tests/test_alpaca_provider.py b/tests/test_alpaca_provider.py index 96d1455..a27b48b 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): @@ -298,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"), [ @@ -1365,3 +1398,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"])