Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/providers/yahoo.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ History windows are imposed upstream, not guaranteed by Data. See the
[SDK download contract](https://ranaroussi.github.io/yfinance/reference/api/yfinance.download.html)
for interval and request semantics; unavailable ranges can fail.

A window with no trading session for a known symbol, such as a weekend or an exchange holiday,
returns an empty frame with the OHLCV schema. `SymbolNotFoundError` means Yahoo does not know the
symbol or has no recent sessions for it. Telling the two apart costs one extra request, made only
after a download has come back empty.

---

## Symbol Format
Expand Down
71 changes: 63 additions & 8 deletions src/ml4t/data/providers/yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,21 @@ def fetch() -> pl.DataFrame:
from ml4t.data.utils.conversion import pandas_to_polars

frame = self._download_prices(symbol, start, end, "daily", keepna=True)
if frame.empty:
# A known symbol with no session in the window; see _resolve_empty_download.
self.last_fetch_metadata = {
"source_index_name": None,
"source_index_unit": None,
"price_basis": "yahoo_auto_adjusted",
"source_package_version": str(getattr(yf, "__version__", "unknown")),
}
return pl.DataFrame(
schema={
"timestamp": pl.Datetime("us", "UTC"),
"symbol": pl.String,
"close": pl.Float64,
}
)
if isinstance(frame.columns, pd.MultiIndex):
if symbol.upper() not in frame.columns.get_level_values(1):
raise DataValidationError(self.name, "Response lacks the requested symbol")
Expand Down Expand Up @@ -249,6 +264,9 @@ def _fetch_and_transform_data(
Returns:
Polars DataFrame with standardized schema

Returns the canonical empty frame when the symbol is known but the window holds no
session, such as a weekend or an exchange holiday.

Raises:
DataNotAvailableError: If no data available for the period
DataValidationError: If data format is invalid
Expand All @@ -272,17 +290,18 @@ def _fetch_and_transform_data(

try:
df_pandas = self._download_prices(symbol, start, end_str, frequency)
if df_pandas.empty:
logger.info("No Yahoo session in the requested window", symbol=symbol)
return self._create_empty_dataframe()

# Convert to Polars with symbol column
df = self._convert_to_polars(df_pandas, symbol)

if df.is_empty():
# Every row was the current session's placeholder; the window holds no bar.
raise SymbolNotFoundError(
"yahoo",
symbol,
details={"start": start, "end": end_str, "frequency": frequency},
)
# Every row was the current session's placeholder: Yahoo answered for the
# symbol, so it is known, and the window holds no bar.
logger.info("No Yahoo session in the requested window", symbol=symbol)
return self._create_empty_dataframe()

logger.info("Successfully fetched data", symbol=symbol, rows=len(df))
return df
Expand Down Expand Up @@ -340,6 +359,13 @@ def _resolve_empty_download(
:meth:`BaseProvider.fetch_ohlcv` retries a :class:`NetworkError` whose ``retryable`` is
set and honours its ``retry_after``, so no separate backoff is needed here.

A window without a session (a weekend, an exchange holiday) is not an unknown symbol.
yfinance raises ``YFTzMissingError`` when Yahoo has no exchange timezone for the symbol
and ``YFPricesMissingError`` when it has one but no bar in the window. A timezone can
come from yfinance's local cache, so the second case is confirmed by asking for the
symbol's recent sessions, one request on a path that has already failed. When Yahoo
has them, the window is empty and an empty frame is returned, as other adapters do.

Args:
symbol: The symbol whose download came back empty
start: Start date in YYYY-MM-DD format
Expand All @@ -348,14 +374,15 @@ def _resolve_empty_download(
frequency: The caller's frequency name, carried into the error details

Returns:
The pandas DataFrame the second ask returned, when it returned one
The pandas DataFrame the second ask returned, when it returned one, or an empty
pandas DataFrame when the symbol has recent sessions but none in the window

Raises:
RateLimitError: Yahoo throttled the request. Retryable.
SymbolNotFoundError: The symbol really is unknown, or Yahoo refused it for a
reason it named. The reason is carried in ``details``.
"""
from yfinance.exceptions import YFException, YFRateLimitError
from yfinance.exceptions import YFException, YFPricesMissingError, YFRateLimitError

details = {"start": start, "end": end, "frequency": frequency}
try:
Expand All @@ -371,15 +398,43 @@ def _resolve_empty_download(
except YFRateLimitError as e:
logger.warning("Yahoo rate limited the request", symbol=symbol, error=str(e))
raise RateLimitError("yahoo") from e
except YFPricesMissingError as e:
if self._has_recent_sessions(symbol):
logger.info(
"Yahoo has no session in the requested window", symbol=symbol, **details
)
return pd.DataFrame()
raise SymbolNotFoundError("yahoo", symbol, details={**details, "reason": str(e)}) from e
except YFException as e:
raise SymbolNotFoundError("yahoo", symbol, details={**details, "reason": str(e)}) from e

if recovered.empty:
if self._has_recent_sessions(symbol):
return recovered
raise SymbolNotFoundError("yahoo", symbol, details=details)

logger.info("Empty download recovered on a second ask", symbol=symbol, rows=len(recovered))
return recovered

def _has_recent_sessions(self, symbol: str) -> bool:
"""Return whether Yahoo serves daily bars for the symbol over the last month."""
from yfinance.exceptions import YFException, YFRateLimitError

try:
recent = yf.Ticker(symbol).history(
period="1mo",
interval="1d",
auto_adjust=True,
actions=False,
raise_errors=True,
)
except YFRateLimitError as e:
logger.warning("Yahoo rate limited the request", symbol=symbol, error=str(e))
raise RateLimitError("yahoo") from e
except YFException:
return False
return not recent.empty

def _convert_to_polars(self, df_pandas: pd.DataFrame, symbol: str) -> pl.DataFrame:
"""
Convert pandas DataFrame from yfinance to Polars DataFrame.
Expand Down
11 changes: 11 additions & 0 deletions tests/integration/test_yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,17 @@ def test_invalid_symbol(self, provider):
assert "INVALID_SYMBOL_12345" in str(exc_info.value)
print("✅ Invalid symbol raises SymbolNotFoundError as expected")

def test_window_without_sessions_is_empty_not_unknown(self, provider):
"""A valid symbol over a weekend is an empty frame, not SymbolNotFoundError (#164)."""
from ml4t.data.core.exceptions import SymbolNotFoundError

df = provider.fetch_ohlcv("SPY", "2025-06-07", "2025-06-08", "daily")
assert df.is_empty()
assert df.columns == ["timestamp", "symbol", "open", "high", "low", "close", "volume"]

with pytest.raises(SymbolNotFoundError):
provider.fetch_ohlcv("INVALID_SYMBOL_12345", "2025-06-07", "2025-06-08", "daily")

def test_historical_data_range(self, provider):
"""Test fetching historical data over longer period."""
# Fetch 1 year of data
Expand Down
131 changes: 130 additions & 1 deletion tests/test_yahoo_empty_download_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
from unittest.mock import MagicMock, patch

import pandas as pd
import polars as pl
import pytest
from yfinance.exceptions import YFPricesMissingError, YFRateLimitError
from yfinance.exceptions import YFPricesMissingError, YFRateLimitError, YFTzMissingError

from ml4t.data.core.exceptions import (
DataValidationError,
Expand Down Expand Up @@ -176,3 +177,131 @@ def test_shared_errors_is_not_a_channel(self):
import yfinance.shared as shared

assert shared._ERRORS == {}


WEEKEND = ("SPY", "2025-06-07", "2025-06-08", "daily")


def _known_symbol_without_bars_in_window() -> MagicMock:
"""What yfinance 1.5.2 does for SPY over Saturday and Sunday, measured live.

The ranged ask resolves SPY's exchange timezone and then finds no bar, so it raises
``YFPricesMissingError``; asking for the recent sessions of the same symbol succeeds.
"""

def history(**kwargs):
if "period" in kwargs:
return _bars()
raise YFPricesMissingError("SPY", "(1d 2025-06-07 -> 2025-06-09)")

ticker = MagicMock()
ticker.history = MagicMock(side_effect=history)
return MagicMock(return_value=ticker)


class TestAWindowWithoutSessionsIsNotAnUnknownSymbol:
"""ml4t/data#164: a valid symbol over a weekend or holiday was reported as not found.

A caller acting on ``SymbolNotFoundError`` drops the symbol from its universe; one asking
for yesterday on a Monday has nothing to do. Like the other adapters, Yahoo now answers an
empty window for a known symbol with the canonical empty frame.
"""

def test_a_weekend_returns_the_canonical_empty_frame(self, provider):
"""Prevents: SymbolNotFoundError for SPY over 2025-06-07..2025-06-08."""
with (
patch("ml4t.data.providers.yahoo.yf.download", return_value=pd.DataFrame()),
patch("ml4t.data.providers.yahoo.yf.Ticker", _known_symbol_without_bars_in_window()),
):
df = provider.fetch_ohlcv(*WEEKEND)

assert df.is_empty()
assert df.schema == provider._create_empty_dataframe().schema

def test_empty_ranged_history_still_recognizes_a_symbol_with_recent_bars(self, provider):
ticker = _probing(side_effect=[pd.DataFrame(), _bars()])
with (
patch("yfinance.download", return_value=pd.DataFrame()),
patch("yfinance.Ticker", ticker),
):
bars = provider.fetch_ohlcv(*WEEKEND)
assert bars.is_empty()
assert bars.schema == provider._create_empty_dataframe().schema
assert ticker.return_value.history.call_args.kwargs["period"] == "1mo"

def test_a_window_holding_only_the_current_session_placeholder_is_empty(self, provider):
"""Prevents: SymbolNotFoundError when Yahoo's only row is the null-price placeholder.

Yahoo answered with a row for the symbol, so the symbol is known; the window has no bar.
"""
placeholder = pd.DataFrame(
{
"Open": [float("nan")],
"High": [float("nan")],
"Low": [float("nan")],
"Close": [float("nan")],
"Volume": [1_000],
},
index=pd.DatetimeIndex(["2025-06-09"], name="Date"),
)
with patch("ml4t.data.providers.yahoo.yf.download", return_value=placeholder):
df = provider.fetch_ohlcv("SPY", "2025-06-09", "2025-06-09", "daily")

assert df.is_empty()
assert df.schema == provider._create_empty_dataframe().schema

def test_adjusted_close_over_a_weekend_returns_an_empty_typed_frame(self, provider):
"""Prevents: SymbolNotFoundError from ``fetch_adjusted_close`` over a weekend."""
with (
patch("ml4t.data.providers.yahoo.yf.download", return_value=pd.DataFrame()),
patch("ml4t.data.providers.yahoo.yf.Ticker", _known_symbol_without_bars_in_window()),
):
df = provider.fetch_adjusted_close("SPY", "2025-06-07", "2025-06-09")

assert df.is_empty()
assert df.columns == ["timestamp", "symbol", "close"]
assert df.schema["timestamp"] == pl.Datetime("us", "UTC")
assert provider.last_fetch_metadata["price_basis"] == "yahoo_auto_adjusted"

def test_a_rate_limit_while_confirming_the_symbol_is_a_rate_limit(self, provider):
"""Prevents: a throttled confirmation being reported as an unknown symbol."""

def history(**kwargs):
if "period" in kwargs:
raise YFRateLimitError()
raise YFPricesMissingError("SPY", "(1d 2025-06-07 -> 2025-06-09)")

ticker = MagicMock()
ticker.history = MagicMock(side_effect=history)
with (
patch("ml4t.data.providers.yahoo.yf.download", return_value=pd.DataFrame()),
patch("ml4t.data.providers.yahoo.yf.Ticker", MagicMock(return_value=ticker)),
pytest.raises(RateLimitError),
):
provider._fetch_and_transform_data(*WEEKEND)

def test_an_unknown_symbol_over_a_weekend_is_still_not_found(self, provider):
"""Prevents the fix overreaching: no timezone means Yahoo does not know the symbol."""
factory = _probing(side_effect=YFTzMissingError("NOPE_ZZZ"))
with (
patch("ml4t.data.providers.yahoo.yf.download", return_value=pd.DataFrame()),
patch("ml4t.data.providers.yahoo.yf.Ticker", factory),
pytest.raises(SymbolNotFoundError) as excinfo,
):
provider.fetch_ohlcv("NOPE_ZZZ", "2025-06-07", "2025-06-08", "daily")

assert "no timezone found" in excinfo.value.details["reason"]

def test_a_symbol_without_recent_prices_is_still_not_found(self, provider):
"""Prevents the fix overreaching: a timezone alone does not make a symbol tradable.

yfinance caches timezones, so a delisted symbol can still resolve one. Only a symbol
with recent sessions turns an empty window into an empty frame.
"""
factory = _probing(side_effect=YFPricesMissingError("GONE", "(period=1mo)"))
with (
patch("ml4t.data.providers.yahoo.yf.download", return_value=pd.DataFrame()),
patch("ml4t.data.providers.yahoo.yf.Ticker", factory),
pytest.raises(SymbolNotFoundError),
):
provider.fetch_ohlcv("GONE", "2025-06-07", "2025-06-08", "daily")
15 changes: 11 additions & 4 deletions tests/test_yahoo_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,12 +272,19 @@ def test_a_row_with_prices_and_no_volume_is_kept(self, mock_download: MagicMock)
assert len(df) == 2

@patch("ml4t.data.providers.yahoo.yf.download")
def test_a_response_of_nothing_but_placeholders_is_not_data(
def test_a_response_of_nothing_but_placeholders_is_an_empty_window(
self, mock_download: MagicMock
) -> None:
"""Dropping every row must not report an empty fetch as a successful one."""
"""Dropping every row leaves a window without a bar, not an unknown symbol (#164).

Yahoo answered for the symbol, so it is known. The result is the empty canonical frame,
which callers test with ``is_empty()``; an initial load still refuses to store it.
"""
frame = self._frame_with_placeholder().iloc[1:]
mock_download.return_value = frame

with pytest.raises(SymbolNotFoundError):
YahooFinanceProvider().fetch_ohlcv("AAPL", "2026-09-03", "2026-09-03", "daily")
provider = YahooFinanceProvider()
df = provider.fetch_ohlcv("AAPL", "2026-09-03", "2026-09-03", "daily")

assert df.is_empty()
assert df.schema == provider._create_empty_dataframe().schema
Loading