Skip to content
Merged
44 changes: 44 additions & 0 deletions docs/providers/alpaca.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
169 changes: 165 additions & 4 deletions src/ml4t/data/providers/alpaca.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -450,14 +489,17 @@ 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),
"limit": self.PAGE_LIMIT,
"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.
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Loading
Loading