From 63d48d73b1ed002bc97f7058b30b43f57d86e817 Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Tue, 24 Nov 2026 18:45:32 -0500 Subject: [PATCH 1/4] Refresh stored price history when overlap revisions would mix vintages --- docs/user-guide/incremental-updates.md | 6 ++ src/ml4t/data/managers/storage_manager.py | 39 ++++++++++++- tests/test_adjusted_history_update.py | 69 +++++++++++++++++++++++ 3 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 tests/test_adjusted_history_update.py diff --git a/docs/user-guide/incremental-updates.md b/docs/user-guide/incremental-updates.md index a81ee77..33fbedc 100644 --- a/docs/user-guide/incremental-updates.md +++ b/docs/user-guide/incremental-updates.md @@ -36,6 +36,12 @@ The overlap lets revised observations replace their stored values. The update me keeps the newest row for a duplicate timestamp, sorts the result, and publishes the replacement through the storage backend's atomic generation mechanism. +When a refetched open, high, low or close differs by more than a relative tolerance of +`1e-5` and the incremental response leaves older observations in the store, the update +requests the full range from the first stored date. This keeps dividend- and split-adjusted +history on the provider's current basis. If the full response omits an observed timestamp, +the update fails before writing and the previous generation remains available. + If `--provider` is omitted for an existing dataset, the update reuses the provider recorded in its metadata. Supplying the option overrides that value. diff --git a/src/ml4t/data/managers/storage_manager.py b/src/ml4t/data/managers/storage_manager.py index be15802..e867342 100644 --- a/src/ml4t/data/managers/storage_manager.py +++ b/src/ml4t/data/managers/storage_manager.py @@ -184,6 +184,18 @@ def _merge_data(self, existing: pl.DataFrame, new: pl.DataFrame) -> pl.DataFrame return merged_df + @staticmethod + def _overlap_prices_revised(existing: pl.DataFrame, incoming: pl.DataFrame) -> bool: + prices = [c for c in ("open", "high", "low", "close") if c in existing and c in incoming] + if not prices: + return False + old, new = align_frames_for_concat( + existing.select("timestamp", *prices), incoming.select("timestamp", *prices) + ) + overlap = old.join(new, on="timestamp", suffix="_new") + revised = [~pl.col(c).is_close(pl.col(f"{c}_new"), rel_tol=1e-5, abs_tol=0) for c in prices] + return bool(overlap.select(pl.any_horizontal(revised).any()).item()) + def _ensure_polars_df(self, df: Any) -> pl.DataFrame: """Convert any DataFrame type to Polars DataFrame. @@ -598,7 +610,7 @@ def update( provider = existing_provider # Get the date range from existing data - _, last_timestamp = timestamp_bounds(existing_df) + first_timestamp, last_timestamp = timestamp_bounds(existing_df) if last_timestamp.tzinfo is None: last_timestamp = last_timestamp.replace(tzinfo=UTC) else: @@ -646,8 +658,29 @@ def update( logger.info(f"Fetched {len(new_df)} rows of new data") self._report_progress(f"Merging data for {symbol}", 0.5) - # Merge data merged_df = self._merge_data(existing_df, new_df) + full_refresh = merged_df.height > new_df[ + "timestamp" + ].n_unique() and self._overlap_prices_revised(existing_df, new_df) + if full_refresh: + # A dividend or split can revise every bar before the overlap. + logger.info("Refetching history after revised overlap prices", symbol=symbol) + refreshed = self.fetch_manager.fetch_raw( + symbol=symbol, + start=first_timestamp.strftime("%Y-%m-%d"), + end=fetch_end.strftime("%Y-%m-%d"), + frequency=frequency, + provider=provider, + ) + expected, returned = align_frames_for_concat( + merged_df.select("timestamp"), refreshed.select("timestamp") + ) + if not expected.join(returned, on="timestamp", how="anti").is_empty(): + raise ValueError( + f"Full price-history refresh for {symbol} omitted previously observed " + "timestamps; stored history was preserved" + ) + merged_df = refreshed.sort("timestamp") logger.info( "Merged data", @@ -699,7 +732,7 @@ def update( { # BulkManager compares this legacy field with naive local cutoffs. "last_update": updated_at.astimezone().replace(tzinfo=None).isoformat(), - "update_type": "incremental", + "update_type": "full_price_revision" if full_refresh else "incremental", "gaps_filled": False, "gap_check_performed": gap_check_performed, "gap_count": len(gaps) if gap_check_performed else None, diff --git a/tests/test_adjusted_history_update.py b/tests/test_adjusted_history_update.py new file mode 100644 index 0000000..66685a8 --- /dev/null +++ b/tests/test_adjusted_history_update.py @@ -0,0 +1,69 @@ +"""Exercise incremental updates with provider vintages on disk.""" + +from unittest.mock import patch + +import pandas as pd +import pytest +from click.testing import CliRunner + +from ml4t.data.cli_interface import cli +from ml4t.data.storage import create_storage + + +@pytest.mark.parametrize( + "factor, incomplete", [(0.997052, False), (1.0000016, False), (0.997052, True)] +) +def test_adjusted_update_preserves_returns_and_avoids_refetch_for_noise( + tmp_path, factor, incomplete +): + dates = pd.bdate_range("2025-06-02", "2025-06-24", name="Date") + dates = dates[dates != pd.Timestamp("2025-06-19")] + prices = pd.Series(range(100, 100 + len(dates)), index=dates, dtype=float) + old = pd.DataFrame( + {"Open": prices, "High": prices + 1, "Low": prices - 1, "Close": prices, "Volume": 1000} + ) + fresh = old.copy() + price_columns = ["Open", "High", "Low", "Close"] + fresh.loc[:"2025-06-18", price_columns] *= factor + calls = [] + + def download(symbol, *, start, end, **kwargs): + calls.append(start) + source = old if len(calls) == 1 else fresh + if incomplete and len(calls) == 3: + source = source.iloc[1:] + return source[(source.index >= start) & (source.index < end)] + + runner = CliRunner() + args = [ + "update", + "--symbol", + "SPY", + "--provider", + "yahoo", + "--frequency", + "daily", + "--asset-class", + "equities", + "--storage-path", + str(tmp_path), + ] + with patch("yfinance.download", side_effect=download): + load = runner.invoke( + cli, [*args, "--initial-start", "2025-06-02", "--initial-end", "2025-06-18"] + ) + assert load.exit_code == 0, load.output + update = runner.invoke(cli, args) + bars = create_storage(tmp_path).read("equities/daily/SPY").collect().sort("timestamp") + if incomplete: + assert update.exit_code != 0 + assert "omitted previously observed timestamps" in update.output + assert bars["close"].to_list() == old.loc[:"2025-06-18", "Close"].to_list() + return + assert update.exit_code == 0, update.output + close = pd.Series(bars["close"].to_list(), index=dates) + assert close.to_list() == pytest.approx(fresh["Close"].to_list(), rel=1e-5) + assert close.pct_change().dropna().to_list() == pytest.approx( + fresh["Close"].pct_change().dropna().to_list(), abs=1e-5 + ) + assert calls == ["2025-06-02", "2025-06-11"] + (["2025-06-02"] if factor < 1 else []) From b0f80ed668421eb606943d0c2cb78e1c84729a79 Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Tue, 24 Nov 2026 18:52:38 -0500 Subject: [PATCH 2/4] Keep range-dependent synthetic observations out of revision detection --- src/ml4t/data/managers/storage_manager.py | 10 +++++++--- tests/test_adjusted_history_update.py | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/ml4t/data/managers/storage_manager.py b/src/ml4t/data/managers/storage_manager.py index e867342..a416567 100644 --- a/src/ml4t/data/managers/storage_manager.py +++ b/src/ml4t/data/managers/storage_manager.py @@ -659,9 +659,13 @@ def update( self._report_progress(f"Merging data for {symbol}", 0.5) merged_df = self._merge_data(existing_df, new_df) - full_refresh = merged_df.height > new_df[ - "timestamp" - ].n_unique() and self._overlap_prices_revised(existing_df, new_df) + source = self.fetch_manager.router.get_provider(symbol, override=provider) + # Synthetic draws depend on the requested start, so an overlap cannot indicate a revision. + full_refresh = ( + source != "synthetic" + and merged_df.height > new_df["timestamp"].n_unique() + and self._overlap_prices_revised(existing_df, new_df) + ) if full_refresh: # A dividend or split can revise every bar before the overlap. logger.info("Refetching history after revised overlap prices", symbol=symbol) diff --git a/tests/test_adjusted_history_update.py b/tests/test_adjusted_history_update.py index 66685a8..268f817 100644 --- a/tests/test_adjusted_history_update.py +++ b/tests/test_adjusted_history_update.py @@ -31,7 +31,7 @@ def download(symbol, *, start, end, **kwargs): calls.append(start) source = old if len(calls) == 1 else fresh if incomplete and len(calls) == 3: - source = source.iloc[1:] + source = source.drop(dates[2]) return source[(source.index >= start) & (source.index < end)] runner = CliRunner() From a30475d0c46fafbaa597767c1417a086a06a359b Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Tue, 24 Nov 2026 18:55:17 -0500 Subject: [PATCH 3/4] Rewrite stored history when a provider restates the update overlap Incremental updates replaced the refetched overlap rows without comparing them with the stored ones. After a dividend or split a provider serving adjusted prices restates every earlier price, so the stored series ended up on two price bases with a spurious return where they met. Reproduced with the CLI against Yahoo: stored and fresh SPY closes differed by up to 0.3%, and the stored total return was 0.37 percentage points short. Every path that merges new rows into stored history now compares the overlapping closes first (find_overlap_revision, 1e-5 relative, which is about six times Yahoo's retrieval noise). A change confined to the last stored bar is treated as a bar stored before its session closed. - StorageManager.update (DataManager.update, the CLI update) refetches the full stored range, rewrites the dataset, logs a warning with the size of the change and records update_type full_refresh. It raises and leaves storage unchanged when the provider no longer serves the first stored row. - ProviderUpdater refetches from the first stored row the same way. - IncrementalUpdater has no provider to refetch from, so INCREMENTAL and APPEND_ONLY return success=False and leave storage unchanged; the error names FULL_REFRESH. Two existing tests fed restated overlaps by accident: SyntheticProvider restarts its random walk at each start date, and an IncrementalUpdater test changed every overlapping close. Their subjects (absences survive an update, overlap rows replace stored values) are unchanged; they now use a range-stable series and an open-only correction. Closes #163 --- docs/user-guide/incremental-updates.md | 14 + src/ml4t/data/core/overlap.py | 111 ++++++++ src/ml4t/data/managers/storage_manager.py | 100 ++++++- src/ml4t/data/provider_updater.py | 46 ++++ src/ml4t/data/update_manager.py | 39 +++ tests/test_incremental_update_system.py | 6 +- tests/test_preserve_market_absences.py | 28 +- tests/test_provider_updater.py | 3 + tests/test_update_adjustment_basis.py | 319 ++++++++++++++++++++++ 9 files changed, 657 insertions(+), 9 deletions(-) create mode 100644 src/ml4t/data/core/overlap.py create mode 100644 tests/test_update_adjustment_basis.py diff --git a/docs/user-guide/incremental-updates.md b/docs/user-guide/incremental-updates.md index a81ee77..0b0b34b 100644 --- a/docs/user-guide/incremental-updates.md +++ b/docs/user-guide/incremental-updates.md @@ -36,6 +36,20 @@ The overlap lets revised observations replace their stored values. The update me keeps the newest row for a duplicate timestamp, sorts the result, and publishes the replacement through the storage backend's atomic generation mechanism. +The overlap is also compared with the stored rows. A provider that serves adjusted prices, such as +Yahoo, restates every earlier price after a dividend or split. When an overlapping close differs +from the stored one by more than 1e-5 relative, merging would leave the older rows on the previous +price basis, so the update refetches the full stored range and rewrites the dataset instead. It +logs a warning with the number of changed rows and the largest relative change, and records +`update_type: full_refresh` in the dataset attributes. A change confined to the last stored bar, +which may have been stored before its session closed, is merged as usual. If the provider no longer +serves the first stored row, the update raises and leaves storage unchanged. + +`IncrementalUpdater` receives data rather than a provider, so it cannot refetch. With the +`INCREMENTAL` or `APPEND_ONLY` strategy it returns `success=False` and leaves storage unchanged +when new data restates stored rows; fetch the full stored range and apply `FULL_REFRESH`. +`ProviderUpdater` refetches the stored range the same way `update` does. + If `--provider` is omitted for an existing dataset, the update reuses the provider recorded in its metadata. Supplying the option overrides that value. diff --git a/src/ml4t/data/core/overlap.py b/src/ml4t/data/core/overlap.py new file mode 100644 index 0000000..59a1f37 --- /dev/null +++ b/src/ml4t/data/core/overlap.py @@ -0,0 +1,111 @@ +"""Detect a refetch whose overlapping rows no longer match the stored rows. + +Providers that serve adjusted prices restate every earlier price after a dividend or split. +Splicing such a refetch onto stored history puts the rows before the overlap on the old basis +and the rest on the new one, with a spurious return where they meet. Update paths compare the +overlap first and rewrite the whole stored range when it changed. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +import polars as pl + +from ml4t.data.core.schemas import align_frames_for_concat + +#: Relative change in an overlapping close above which the provider counts as having restated +#: the row. Repeated Yahoo retrievals of the same adjusted close differ by up to about 1.6e-6 +#: relative; a dividend of 0.1% of the price changes every earlier close by 1e-3. +OVERLAP_RTOL = 1e-5 + + +@dataclass(frozen=True) +class OverlapRevision: + """Stored rows that a refetch of the same timestamps no longer reproduces.""" + + rows_compared: int + rows_revised: int + max_relative_change: float + first_revised: datetime + last_revised: datetime + + def log_fields(self) -> dict[str, Any]: + """Return the revision as structured-log fields.""" + return { + "rows_compared": self.rows_compared, + "rows_revised": self.rows_revised, + "max_relative_change": self.max_relative_change, + "first_revised": self.first_revised.isoformat(), + "last_revised": self.last_revised.isoformat(), + } + + def describe(self) -> str: + """Return a one-line description for error messages.""" + return ( + f"{self.rows_revised} of {self.rows_compared} overlapping rows changed, " + f"by up to {self.max_relative_change:.3e} relative in close, " + f"between {self.first_revised.isoformat()} and {self.last_revised.isoformat()}" + ) + + +def find_overlap_revision( + stored: pl.DataFrame, + refetched: pl.DataFrame, + *, + column: str = "close", + rtol: float = OVERLAP_RTOL, +) -> OverlapRevision | None: + """Compare a refetch with the stored rows that share its timestamps. + + Args: + stored: Rows already in storage for one instrument. + refetched: Rows the provider returned now for the same instrument. + column: Price column to compare. + rtol: Relative change above which a row counts as revised. + + Returns: + The revision when any overlapping row changed by more than ``rtol``, else None. + Rows where either value is null are not compared. A change confined to the last + stored row is not a revision when earlier overlapping rows match: that row may have + been a bar still forming when it was stored, and a restatement changes every row + before the corporate action, not one. + """ + if column not in stored.columns or column not in refetched.columns: + return None + if stored.is_empty() or refetched.is_empty(): + return None + left, right = align_frames_for_concat( + stored.select("timestamp", column), refetched.select("timestamp", column) + ) + joined = ( + left.unique(subset=["timestamp"], keep="last") + .join( + right.unique(subset=["timestamp"], keep="last"), + on="timestamp", + suffix="_refetched", + ) + .drop_nulls() + ) + if joined.is_empty(): + return None + before = pl.col(column).cast(pl.Float64) + after = pl.col(f"{column}_refetched").cast(pl.Float64) + change = (after - before).abs() + relative = pl.when(before != 0).then(change / before.abs()).otherwise(change) + compared = joined.with_columns(relative.alias("relative_change")) + revised = compared.filter(pl.col("relative_change") > rtol).sort("timestamp") + if revised.is_empty(): + return None + last_stored = left["timestamp"].max() + if compared.height > 1 and revised["timestamp"].to_list() == [last_stored]: + return None + return OverlapRevision( + rows_compared=compared.height, + rows_revised=revised.height, + max_relative_change=float(revised["relative_change"].abs().max() or 0.0), + first_revised=revised["timestamp"][0], + last_revised=revised["timestamp"][-1], + ) diff --git a/src/ml4t/data/managers/storage_manager.py b/src/ml4t/data/managers/storage_manager.py index be15802..c38865b 100644 --- a/src/ml4t/data/managers/storage_manager.py +++ b/src/ml4t/data/managers/storage_manager.py @@ -18,6 +18,7 @@ from pydantic import ValidationError from tenacity import RetryError +from ml4t.data.core.overlap import OverlapRevision, find_overlap_revision from ml4t.data.core.schemas import align_frames_for_concat, timestamp_bounds from ml4t.data.sessions.assigner import SessionAssigner from ml4t.data.storage.backend import normalize_storage_metadata @@ -184,6 +185,81 @@ def _merge_data(self, existing: pl.DataFrame, new: pl.DataFrame) -> pl.DataFrame return merged_df + def _refetch_restated_history( + self, + key: str, + symbol: str, + existing_df: pl.DataFrame, + fetch_end: datetime, + frequency: str, + provider: str | None, + max_history_days: int | None, + revision: OverlapRevision, + ) -> pl.DataFrame: + """Refetch the stored range from the provider whose overlap no longer matches. + + Returns the refetched series, which replaces the stored one. Raises ValueError, + leaving storage untouched, when the provider no longer serves the first stored row. + """ + stored_start, _ = timestamp_bounds(existing_df) + stored_start = ( + stored_start.replace(tzinfo=UTC) + if stored_start.tzinfo is None + else stored_start.astimezone(UTC) + ) + rebuild_hint = ( + f"Stored rows for '{key}' no longer match what the provider serves " + f"({revision.describe()}): it has restated its history, as adjusted prices are " + "after a dividend or split. Splicing the update onto the stored rows would mix two " + "price bases, so " + ) + if max_history_days is not None and stored_start < fetch_end - timedelta( + days=max_history_days + ): + raise ValueError( + rebuild_hint + f"the stored range from {stored_start.date()} has to be " + f"refetched, and the provider serves only the last {max_history_days} days. " + "Storage is unchanged; reload the dataset over a range the provider serves." + ) + + logger.warning( + "Provider restated stored history; refetching the full stored range", + key=key, + provider=provider, + refetch_start=stored_start.date().isoformat(), + **revision.log_fields(), + ) + refetched = self.fetch_manager.fetch_raw( + symbol=symbol, + start=stored_start.strftime("%Y-%m-%d"), + end=fetch_end.strftime("%Y-%m-%d"), + frequency=frequency, + provider=provider, + ) + if refetched.is_empty() or timestamp_bounds(refetched)[0] > stored_start: + first = None if refetched.is_empty() else timestamp_bounds(refetched)[0] + raise ValueError( + rebuild_hint + f"the stored range from {stored_start.date()} has to be " + f"refetched, and the provider returned rows only from {first}. " + "Storage is unchanged; reload the dataset over a range the provider serves." + ) + refetched = refetched.unique(subset=["timestamp"], keep="last").sort("timestamp") + _, refetched = align_frames_for_concat( + existing_df.head(0), + refetched, + left_fill_values={"dividends": 0.0, "splits": 1.0}, + right_fill_values={"dividends": 0.0, "splits": 1.0}, + ) + dropped = existing_df.join(refetched.select("timestamp"), on="timestamp", how="anti") + logger.warning( + "Rewrote stored history on the provider's current basis", + key=key, + rows_before=len(existing_df), + rows_after=len(refetched), + stored_rows_not_served=len(dropped), + ) + return refetched + def _ensure_polars_df(self, df: Any) -> pl.DataFrame: """Convert any DataFrame type to Polars DataFrame. @@ -646,8 +722,25 @@ def update( logger.info(f"Fetched {len(new_df)} rows of new data") self._report_progress(f"Merging data for {symbol}", 0.5) - # Merge data - merged_df = self._merge_data(existing_df, new_df) + # A provider of adjusted prices restates earlier rows after a dividend or split. + # Splicing its refetch onto stored rows would mix two price bases, so a changed + # overlap means the whole stored range is refetched and rewritten. + update_type = "incremental" + revision = find_overlap_revision(existing_df, new_df) + if revision is None: + merged_df = self._merge_data(existing_df, new_df) + else: + merged_df = self._refetch_restated_history( + key, + symbol, + existing_df, + fetch_end, + frequency, + provider, + max_history_days, + revision, + ) + update_type = "full_refresh" logger.info( "Merged data", @@ -699,7 +792,7 @@ def update( { # BulkManager compares this legacy field with naive local cutoffs. "last_update": updated_at.astimezone().replace(tzinfo=None).isoformat(), - "update_type": "incremental", + "update_type": update_type, "gaps_filled": False, "gap_check_performed": gap_check_performed, "gap_count": len(gaps) if gap_check_performed else None, @@ -784,6 +877,7 @@ def update( logger.info( "Incremental update completed", key=key, + update_type=update_type, total_rows=len(merged_df), added_rows=len(merged_df) - len(existing_df), ) diff --git a/src/ml4t/data/provider_updater.py b/src/ml4t/data/provider_updater.py index cbf11ac..5b57b94 100644 --- a/src/ml4t/data/provider_updater.py +++ b/src/ml4t/data/provider_updater.py @@ -12,6 +12,7 @@ import polars as pl import structlog +from ml4t.data.core.overlap import find_overlap_revision from ml4t.data.storage.protocols import IncrementalStorageBackend logger = structlog.get_logger(__name__) @@ -149,6 +150,13 @@ def update_symbol( # Step 4: Save data if not dry_run: + refetch_start = self._restated_history_start(symbol, transformed) + if refetch_start is not None: + start_time = refetch_start + transformed = self._refetch_stored_range(symbol, start_time, end_time, **kwargs) + stats["start_time"] = start_time + stats["records_fetched"] = len(transformed) + stats["full_refresh"] = True records_added = self._save_data(transformed, symbol, start_time, end_time) stats["records_added"] = records_added @@ -348,6 +356,44 @@ def _get_time_range( return start_time, end_time + def _restated_history_start(self, symbol: str, data: pl.DataFrame) -> datetime | None: + """Return the first stored timestamp when ``data`` restates the stored rows it overlaps. + + Adjusted prices change after a dividend or split. Merging such a refetch into the + combined file would leave the rows before the overlap on the older price basis, so + the caller refetches the stored range instead. + """ + stored = self.storage.read_data(symbol, self.provider_name) + if stored.is_empty(): + return None + revision = find_overlap_revision(stored, data) + if revision is None: + return None + stored_start = stored["timestamp"].min() + if not isinstance(stored_start, datetime) or data["timestamp"].min() <= stored_start: + return None + self.logger.warning( + "Provider restated stored history; refetching the full stored range", + symbol=symbol, + refetch_start=stored_start, + **revision.log_fields(), + ) + return stored_start + + def _refetch_stored_range( + self, symbol: str, start_time: datetime, end_time: datetime, **kwargs: Any + ) -> pl.DataFrame: + """Fetch and transform the full stored range, refusing a refetch that falls short.""" + raw = self._fetch_data(symbol, start_time, end_time, **kwargs) + data = self._transform_data(raw, symbol, **kwargs) if raw is not None and len(raw) else None + if data is None or data.is_empty() or data["timestamp"].min() > start_time: + raise ValueError( + f"{self.provider_name} restated stored history for {symbol}, and the refetch " + f"from {start_time} does not reach the first stored row. Merging it would mix " + "two price bases; storage is unchanged. Reload the symbol with incremental=False." + ) + return data + def _save_data( self, data: pl.DataFrame, diff --git a/src/ml4t/data/update_manager.py b/src/ml4t/data/update_manager.py index 0229591..5c61d6e 100644 --- a/src/ml4t/data/update_manager.py +++ b/src/ml4t/data/update_manager.py @@ -12,6 +12,7 @@ import polars as pl import structlog +from ml4t.data.core.overlap import find_overlap_revision from ml4t.data.core.schemas import align_frames_for_concat from ml4t.data.providers.base import BaseProvider from ml4t.data.providers.protocols import TimestampRangeProvider @@ -70,6 +71,40 @@ def _rewrite_preserving_metadata( ) +def _restated_overlap_error( + existing: pl.DataFrame, new_data: pl.DataFrame, strategy: UpdateStrategy +) -> UpdateResult | None: + """Refuse to splice new rows onto stored rows the provider has since restated. + + A refetch that starts at or before the first stored row replaces all of it and is safe. + Otherwise a changed overlap means the stored rows before it are on an older price basis, + and only a refetch of the full stored range can put them on the current one. + """ + revision = find_overlap_revision(existing, new_data) + if revision is None: + return None + if _ensure_datetime(new_data["timestamp"].min()) <= _ensure_datetime( + existing["timestamp"].min() + ): + return None + message = ( + f"New data restates stored rows ({revision.describe()}), as adjusted prices change " + "after a dividend or split. Splicing it onto the stored rows would mix two price " + "bases; storage is unchanged. Fetch the full stored range and apply " + "UpdateStrategy.FULL_REFRESH." + ) + logger.warning("Refusing to splice restated rows", **revision.log_fields()) + return UpdateResult( + success=False, + update_type=strategy.value, + rows_added=0, + rows_updated=0, + rows_before=len(existing), + rows_after=len(existing), + errors=[message], + ) + + class UpdateStrategy(Enum): """Update strategy types.""" @@ -813,6 +848,8 @@ def apply_strategy( if storage.exists(key): existing_df = storage.read(key).collect() existing_df, new_data = align_frames_for_concat(existing_df, new_data) + if refusal := _restated_overlap_error(existing_df, new_data, strategy): + return refusal max_existing = existing_df["timestamp"].max() # Filter new data to only include timestamps after existing @@ -917,6 +954,8 @@ def apply_strategy( if storage.exists(key): existing_df = storage.read(key).collect() existing_df, new_data = align_frames_for_concat(existing_df, new_data) + if refusal := _restated_overlap_error(existing_df, new_data, strategy): + return refusal # Separate overlapping and new data min_new = _ensure_datetime(new_data["timestamp"].min()) diff --git a/tests/test_incremental_update_system.py b/tests/test_incremental_update_system.py index e0c4ec7..7418275 100644 --- a/tests/test_incremental_update_system.py +++ b/tests/test_incremental_update_system.py @@ -276,7 +276,9 @@ def test_incremental_update_with_overlap_handling(self): ) storage.write(df1, "BTC") - # Simulate new data with some overlap + # Simulate new data with some overlap. The overlapping rows correct the open and + # keep the stored close; a changed close in every overlapping row is a restatement, + # which the updater refuses to splice (tests/test_update_adjustment_basis.py). dates2 = pl.date_range( datetime(2024, 1, 8), # Overlaps last 3 days datetime(2024, 1, 15), @@ -287,7 +289,7 @@ def test_incremental_update_with_overlap_handling(self): { "timestamp": dates2, "open": [102.0] * len(dates2), - "close": [103.0] * len(dates2), + "close": [101.0] * 3 + [103.0] * (len(dates2) - 3), } ) diff --git a/tests/test_preserve_market_absences.py b/tests/test_preserve_market_absences.py index 01ade4c..a16e1dd 100644 --- a/tests/test_preserve_market_absences.py +++ b/tests/test_preserve_market_absences.py @@ -18,6 +18,26 @@ from ml4t.data.utils.gaps import GapDetector +def _serve_one_synthetic_history(monkeypatch) -> pl.DataFrame: + """Make SyntheticProvider serve slices of one fixed series, as a market data source does. + + The generator restarts its random walk at each requested start, so a refetch of a stored + date returns a different price. The update path treats that as restated history and + rewrites the dataset; these tests are about absences in history that was not restated. + """ + with SyntheticProvider(seed=42) as provider: + history = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-15", "daily") + + def fetch(self, symbol, start, end, frequency): + day = pl.col("timestamp").dt.date() + return history.filter( + day.is_between(date.fromisoformat(start[:10]), date.fromisoformat(end[:10])) + ) + + monkeypatch.setattr(SyntheticProvider, "_fetch_and_transform_data", fetch) + return history + + @pytest.mark.parametrize("backend", [FlatStorage, HiveStorage]) @pytest.mark.parametrize("check", ["absent_timestamp", "observed_null"]) def test_default_real_provider_update_preserves_historical_absence_and_observed_null( @@ -29,8 +49,8 @@ def now(cls, tz=UTC): return cls(2025, 7, 15, 23, tzinfo=tz) monkeypatch.setattr("ml4t.data.managers.storage_manager.datetime", Clock) - with SyntheticProvider(seed=42) as provider: - frame = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-14", "daily") + history = _serve_one_synthetic_history(monkeypatch) + frame = history.filter(pl.col("timestamp").dt.date() <= date(2025, 7, 14)) observed = frame.filter(pl.col("timestamp").dt.date() != date(2025, 7, 9)).with_columns( pl.when(pl.col("timestamp").dt.date() == date(2025, 7, 8)) .then(None) @@ -135,8 +155,8 @@ def now(cls, tz=UTC): return cls(2025, 7, 15, 23, tzinfo=tz) monkeypatch.setattr("ml4t.data.managers.storage_manager.datetime", Clock) - with SyntheticProvider(seed=42) as provider: - complete = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-14", "daily") + history = _serve_one_synthetic_history(monkeypatch) + complete = history.filter(pl.col("timestamp").dt.date() <= date(2025, 7, 14)) observed = complete.filter(pl.col("timestamp").dt.date() != date(2025, 7, 9)) storage = HiveStorage(StorageConfig(base_path=tmp_path)) with DataManager(storage=storage, enable_validation=False) as manager: diff --git a/tests/test_provider_updater.py b/tests/test_provider_updater.py index 935b514..759c90a 100644 --- a/tests/test_provider_updater.py +++ b/tests/test_provider_updater.py @@ -71,6 +71,9 @@ def __init__(self, latest_timestamp=None): def get_latest_timestamp(self, symbol, provider): return self._latest_timestamp + def read_data(self, symbol, provider, start_time=None, end_time=None): + return pl.DataFrame() + def save_chunk(self, data, symbol, provider, start_time, end_time): self.save_chunk_calls.append( { diff --git a/tests/test_update_adjustment_basis.py b/tests/test_update_adjustment_basis.py new file mode 100644 index 0000000..3ec2518 --- /dev/null +++ b/tests/test_update_adjustment_basis.py @@ -0,0 +1,319 @@ +"""Updates must not splice a provider's restated history onto stored rows (ml4t/data#163). + +A provider serving back-adjusted prices restates every earlier price after a dividend or split. +The update used to replace only the refetched overlap rows, so the store kept the rows before +the overlap on the old basis and gained a spurious return where the two bases met. + +The fake provider below serves a deterministic daily series back-adjusted for the dividends it +currently knows about. Storage is seeded through the storage API with the series as it was +served before the ex-date, and the update runs through ``DataManager.update``, the path the +``ml4t-data update`` command uses. +""" + +from __future__ import annotations + +from datetime import UTC, date, datetime, timedelta +from typing import Any, ClassVar + +import polars as pl +import pytest +from polars.testing import assert_frame_equal + +from ml4t.data import DataManager +from ml4t.data.provider_updater import ProviderUpdater +from ml4t.data.providers.base import BaseProvider +from ml4t.data.storage.config import StorageConfig +from ml4t.data.storage.hive import HiveStorage +from ml4t.data.update_manager import IncrementalUpdater, UpdateStrategy + +KEY = "equities/daily/SPY" +FIRST_SESSION = date(2025, 1, 2) +LAST_STORED = date(2025, 6, 18) +EX_DATE = date(2025, 6, 20) +# SPY's 2025-06-20 dividend: 1 - 1.7610 / close(2025-06-18), as measured in the issue. +FACTOR = 0.997052 +# Repeated Yahoo retrievals of the same adjusted close differ by up to about 1.6e-6 relative. +RETRIEVAL_NOISE = 2e-6 + + +def _sessions(start: date, end: date) -> list[date]: + days = pl.date_range(start, end, "1d", eager=True) + return [day for day in days.to_list() if day.weekday() < 5] + + +def adjusted_series( + start: date, + end: date, + dividends: list[tuple[date, float]], + *, + noise: float = 0.0, + first_available: date = FIRST_SESSION, +) -> pl.DataFrame: + """Daily bars back-adjusted for ``dividends``, as an adjusted-price provider serves them.""" + rows = [] + for day in _sessions(max(start, first_available), end): + index = (day - FIRST_SESSION).days + close = 500.0 * 1.0004**index + for ex_date, factor in dividends: + if day < ex_date: + close *= factor + close *= 1.0 + noise + rows.append( + { + "timestamp": datetime(day.year, day.month, day.day, tzinfo=UTC), + "symbol": "SPY", + "open": close, + "high": close * 1.01, + "low": close * 0.99, + "close": close, + "volume": 1_000_000.0, + } + ) + frame = pl.DataFrame(rows) + return frame.with_columns(pl.col("timestamp").cast(pl.Datetime("us", "UTC"))) + + +class AdjustedProvider(BaseProvider): + """Serves ``adjusted_series`` for the dividends declared on the class at call time.""" + + dividends: ClassVar[list[tuple[date, float]]] = [] + noise: ClassVar[float] = 0.0 + first_available: ClassVar[date] = FIRST_SESSION + calls: ClassVar[list[tuple[str, str]]] = [] + + @property + def name(self) -> str: + return "adjusted_stub" + + def _fetch_and_transform_data( + self, symbol: str, start: str, end: str, frequency: str + ) -> pl.DataFrame: + type(self).calls.append((start, end)) + return adjusted_series( + date.fromisoformat(start), + date.fromisoformat(end), + type(self).dividends, + noise=type(self).noise, + first_available=type(self).first_available, + ) + + +@pytest.fixture +def provider_class(): + class Provider(AdjustedProvider): + dividends: ClassVar[list[tuple[date, float]]] = [] + noise: ClassVar[float] = 0.0 + first_available: ClassVar[date] = FIRST_SESSION + calls: ClassVar[list[tuple[str, str]]] = [] + + return Provider + + +@pytest.fixture +def storage(tmp_path): + """A store holding SPY as the provider served it before the ex-date.""" + storage = HiveStorage(StorageConfig(base_path=tmp_path)) + seeded = adjusted_series(FIRST_SESSION, LAST_STORED, []) + storage.write(seeded, KEY, {"provider": "adjusted_stub", "symbol": "SPY"}) + return storage + + +def _update(storage: HiveStorage, provider_class: type[AdjustedProvider]) -> None: + with DataManager(storage=storage) as manager: + manager._provider_manager.register_provider("adjusted_stub", provider_class) + manager.update("SPY", asset_class="equities", frequency="daily") + + +def _today() -> date: + return datetime.now(UTC).date() + + +def _returns(frame: pl.DataFrame) -> pl.Series: + return frame.sort("timestamp")["close"].pct_change().drop_nulls() + + +class TestUpdateAfterACorporateAction: + def test_stored_history_is_rewritten_on_the_providers_current_basis( + self, storage, provider_class + ): + """Prevents: rows before the overlap staying on the pre-dividend basis. + + On main the store ends up 0.2948% too high on every row before the lookback window. + """ + provider_class.dividends = [(EX_DATE, FACTOR)] + + _update(storage, provider_class) + + stored = storage.read(KEY).collect().sort("timestamp") + current = adjusted_series(FIRST_SESSION, _today(), provider_class.dividends) + assert stored["timestamp"].to_list() == current["timestamp"].to_list() + assert_frame_equal( + stored.select("timestamp", "open", "high", "low", "close"), + current.select("timestamp", "open", "high", "low", "close"), + rtol=1e-12, + ) + + def test_no_spurious_return_where_the_refetch_meets_stored_rows(self, storage, provider_class): + """Prevents: a dividend-sized return on the first overlap row instead of the ex-date.""" + provider_class.dividends = [(EX_DATE, FACTOR)] + + _update(storage, provider_class) + + stored = storage.read(KEY).collect() + current = adjusted_series(FIRST_SESSION, _today(), provider_class.dividends) + gap = (_returns(stored) - _returns(current)).abs().max() + assert gap is not None and gap < 1e-9 + + def test_the_rewrite_is_a_full_refetch_from_the_first_stored_session( + self, storage, provider_class + ): + """Prevents: rebasing the old rows by the overlap ratio instead of refetching them. + + A ratio is correct only for one multiplicative event in the gap; the provider's own + series is the only reference for anything else. + """ + provider_class.dividends = [(EX_DATE, FACTOR)] + + _update(storage, provider_class) + + assert len(provider_class.calls) == 2 + assert provider_class.calls[1][0] == FIRST_SESSION.isoformat() + metadata = storage.get_metadata(KEY)["custom"] + assert metadata["attributes"]["update_type"] == "full_refresh" + + def test_history_the_provider_no_longer_serves_is_left_untouched(self, storage, provider_class): + """Prevents: writing a mixed-basis store when the full range cannot be refetched.""" + provider_class.dividends = [(EX_DATE, FACTOR)] + provider_class.first_available = date(2025, 3, 3) + before = storage.read(KEY).collect() + + with pytest.raises(ValueError, match="restated"): + _update(storage, provider_class) + + assert_frame_equal(storage.read(KEY).collect(), before) + + +class TestUpdateWithoutACorporateAction: + def test_retrieval_noise_keeps_the_update_incremental(self, storage, provider_class): + """Prevents: a full refetch on every update because of float noise in the overlap. + + The overlap differs from the stored rows by Yahoo-sized retrieval noise only, so the + update must fetch once and leave the stored rows before the lookback window as they are. + """ + provider_class.noise = RETRIEVAL_NOISE + before = storage.read(KEY).collect() + + _update(storage, provider_class) + + assert len(provider_class.calls) == 1 + stored = storage.read(KEY).collect().sort("timestamp") + assert stored["timestamp"].max().date() > LAST_STORED + untouched = stored.filter(pl.col("timestamp") < before["timestamp"].max() - timedelta(7)) + assert_frame_equal( + untouched, before.filter(pl.col("timestamp").is_in(untouched["timestamp"])) + ) + metadata = storage.get_metadata(KEY)["custom"] + assert metadata["attributes"]["update_type"] == "incremental" + + def test_a_bar_still_forming_when_stored_keeps_the_update_incremental(self, tmp_path): + """Prevents: a full refetch after every update run during the trading day. + + The last stored bar was retrieved before the session closed, so its close differs + from the final one. Earlier overlap rows match, so nothing was restated. + """ + storage = HiveStorage(StorageConfig(base_path=tmp_path)) + seeded = adjusted_series(FIRST_SESSION, LAST_STORED, []) + seeded = seeded.with_columns( + pl.when(pl.col("timestamp") == pl.col("timestamp").max()) + .then(pl.col(column) * 0.995) + .otherwise(pl.col(column)) + .alias(column) + for column in ("open", "high", "low", "close") + ) + storage.write(seeded, KEY, {"provider": "adjusted_stub", "symbol": "SPY"}) + + class Provider(AdjustedProvider): + calls: ClassVar[list[tuple[str, str]]] = [] + + _update(storage, Provider) + + assert len(Provider.calls) == 1 + stored = storage.read(KEY).collect().sort("timestamp") + final = adjusted_series(FIRST_SESSION, _today(), []) + assert_frame_equal( + stored.select("timestamp", "close"), final.select("timestamp", "close"), rtol=1e-12 + ) + + +class TestIncrementalUpdaterRefusesToSplice: + """``IncrementalUpdater`` receives data, not a provider, so it cannot refetch.""" + + def _refetch(self, start: date, dividends: list[tuple[date, float]]) -> pl.DataFrame: + return adjusted_series(start, date(2025, 7, 3), dividends) + + @pytest.mark.parametrize("strategy", [UpdateStrategy.INCREMENTAL, UpdateStrategy.APPEND_ONLY]) + def test_a_restated_overlap_fails_and_leaves_the_store_unchanged(self, storage, strategy): + """Prevents: splicing restated rows onto stored history through the library API.""" + before = storage.read(KEY).collect() + refetched = self._refetch(date(2025, 6, 11), [(EX_DATE, FACTOR)]) + + result = IncrementalUpdater().update_incremental( + storage, None, KEY, refetched, "adjusted_stub", strategy + ) + + assert not result.success + assert result.errors and "FULL_REFRESH" in result.errors[0] + assert_frame_equal(storage.read(KEY).collect(), before) + + def test_a_refetch_covering_the_whole_store_replaces_it(self, storage): + """Prevents the refusal overreaching: a refetch of the full range is not a splice.""" + refetched = self._refetch(FIRST_SESSION, [(EX_DATE, FACTOR)]) + + result = IncrementalUpdater().update_incremental( + storage, None, KEY, refetched, "adjusted_stub", UpdateStrategy.INCREMENTAL + ) + + assert result.success + stored = storage.read(KEY).collect().sort("timestamp") + assert_frame_equal(stored.select(refetched.columns), refetched, check_dtypes=False) + + +class _AdjustedUpdater(ProviderUpdater): + """A ``ProviderUpdater`` over an adjusted-price source, as the class docstring shows.""" + + def __init__(self, storage: HiveStorage, dividends: list[tuple[date, float]]) -> None: + super().__init__("adjusted_stub", storage) + self.dividends = dividends + self.calls: list[tuple[datetime, datetime]] = [] + + def _fetch_data( + self, symbol: str, start_time: datetime, end_time: datetime, **kwargs: Any + ) -> pl.DataFrame: + self.calls.append((start_time, end_time)) + return adjusted_series(start_time.date(), end_time.date(), self.dividends) + + def _transform_data(self, data: pl.DataFrame, symbol: str, **kwargs: Any) -> pl.DataFrame: + return data + + def _get_default_start_time(self, symbol: str) -> datetime: + return datetime(2025, 1, 2, tzinfo=UTC) + + +class TestProviderUpdaterAfterACorporateAction: + def test_combined_file_is_rewritten_on_the_current_basis(self, tmp_path): + """Prevents: ``ProviderUpdater`` splicing a restated last row onto stored history.""" + storage = HiveStorage(StorageConfig(base_path=tmp_path)) + seed = _AdjustedUpdater(storage, []) + seed.update_symbol( + "SPY", + start_time=datetime(2025, 1, 2, tzinfo=UTC), + end_time=datetime(2025, 6, 18, tzinfo=UTC), + ) + updater = _AdjustedUpdater(storage, [(EX_DATE, FACTOR)]) + + stats = updater.update_symbol("SPY", end_time=datetime(2025, 7, 3, tzinfo=UTC)) + + assert stats["success"], stats["errors"] + stored = storage.read_data("SPY", "adjusted_stub").sort("timestamp") + current = adjusted_series(FIRST_SESSION, date(2025, 7, 3), [(EX_DATE, FACTOR)]) + assert_frame_equal(stored.select(current.columns), current, check_dtypes=False) From b31b0ea2855c34d92f34b2729d701bf0b66f764e Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Tue, 24 Nov 2026 19:08:45 -0500 Subject: [PATCH 4/4] Keep synthetic and fixture histories fixed in tests that are not about restatement Six more tests fed the update paths a restated overlap by accident and failed once restatements trigger a rewrite or a refusal: - tests/test_ingestion_calendar_declarations.py (two update tests) and tests/test_preserve_market_absences.py use SyntheticProvider, which restarts its random walk at each requested start. A range_stable_synthetic fixture in conftest serves slices of one series per symbol instead, replacing the module-local helper from the previous commit. - TestIncrementalUpdaterStrategies in tests/test_update_manager.py changed every overlapping close by 5%. Its new_data now keeps the stored close on the overlapping days (and a low consistent with it). What each test checks is unchanged; all of them also pass on main. --- tests/conftest.py | 35 +++++++++++++++++++ tests/test_ingestion_calendar_declarations.py | 6 ++-- tests/test_preserve_market_absences.py | 34 +++++------------- tests/test_update_manager.py | 10 ++++-- 4 files changed, 54 insertions(+), 31 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 77243de..2b3eb61 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -214,3 +214,38 @@ def close_yfinance_caches(): _close_yfinance_caches() yield _close_yfinance_caches() + + +@pytest.fixture +def range_stable_synthetic(monkeypatch): + """Make every SyntheticProvider serve slices of one series per symbol, as a market source does. + + The generator restarts its random walk at each requested start, so a refetch of a stored + date returns a different price. Update paths treat that as restated history and rewrite + the dataset. Tests about something else use this fixture to keep their history fixed. The + series is shared across instances and seeds, so a CLI-created provider serves it too. + """ + from datetime import UTC, date, datetime, timedelta + + import polars as pl + + from ml4t.data.providers.synthetic import SyntheticProvider + + generate = SyntheticProvider._fetch_and_transform_data + first_day = date(2025, 1, 1) + last_day = datetime.now(UTC).date() + timedelta(days=2) + series: dict[tuple[str, str], pl.DataFrame] = {} + + def fetch(self, symbol, start, end, frequency): + cache_key = (symbol, frequency) + if cache_key not in series: + series[cache_key] = generate( + self, symbol, first_day.isoformat(), last_day.isoformat(), frequency + ) + start_day, end_day = date.fromisoformat(start[:10]), date.fromisoformat(end[:10]) + assert first_day <= start_day, "range_stable_synthetic starts on 2025-01-01" + return series[cache_key].filter( + pl.col("timestamp").dt.date().is_between(start_day, end_day) + ) + + monkeypatch.setattr(SyntheticProvider, "_fetch_and_transform_data", fetch) diff --git a/tests/test_ingestion_calendar_declarations.py b/tests/test_ingestion_calendar_declarations.py index 6279ab0..d00036b 100644 --- a/tests/test_ingestion_calendar_declarations.py +++ b/tests/test_ingestion_calendar_declarations.py @@ -86,7 +86,7 @@ def test_invalid_calendar_does_not_replace_existing_generation(manager): assert_frame_equal(storage.read(key).collect(), frame) -def test_disabled_update_does_not_impute_an_old_provider_outage(manager): +def test_disabled_update_does_not_impute_an_old_provider_outage(manager, range_stable_synthetic): instance, storage = manager historic = provider_frame().filter(pl.col("timestamp").dt.date() != date(2025, 7, 16)) recent_day = (datetime.now(UTC) - timedelta(days=3)).date() @@ -158,7 +158,9 @@ def test_declared_grid_and_timezone_survive_import_and_model_projection(manager) assert getattr(restored, name) == getattr(feed, name) -def test_explicit_update_disable_overrides_stored_schedule_without_filling(manager): +def test_explicit_update_disable_overrides_stored_schedule_without_filling( + manager, range_stable_synthetic +): instance, storage = manager historic = provider_frame().filter(pl.col("timestamp").dt.date() != date(2025, 7, 16)) recent_day = (datetime.now(UTC) - timedelta(days=3)).date() diff --git a/tests/test_preserve_market_absences.py b/tests/test_preserve_market_absences.py index a16e1dd..f603c5c 100644 --- a/tests/test_preserve_market_absences.py +++ b/tests/test_preserve_market_absences.py @@ -18,30 +18,10 @@ from ml4t.data.utils.gaps import GapDetector -def _serve_one_synthetic_history(monkeypatch) -> pl.DataFrame: - """Make SyntheticProvider serve slices of one fixed series, as a market data source does. - - The generator restarts its random walk at each requested start, so a refetch of a stored - date returns a different price. The update path treats that as restated history and - rewrites the dataset; these tests are about absences in history that was not restated. - """ - with SyntheticProvider(seed=42) as provider: - history = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-15", "daily") - - def fetch(self, symbol, start, end, frequency): - day = pl.col("timestamp").dt.date() - return history.filter( - day.is_between(date.fromisoformat(start[:10]), date.fromisoformat(end[:10])) - ) - - monkeypatch.setattr(SyntheticProvider, "_fetch_and_transform_data", fetch) - return history - - @pytest.mark.parametrize("backend", [FlatStorage, HiveStorage]) @pytest.mark.parametrize("check", ["absent_timestamp", "observed_null"]) def test_default_real_provider_update_preserves_historical_absence_and_observed_null( - tmp_path, monkeypatch, backend, check + tmp_path, monkeypatch, backend, check, range_stable_synthetic ): class Clock(datetime): @classmethod @@ -49,8 +29,8 @@ def now(cls, tz=UTC): return cls(2025, 7, 15, 23, tzinfo=tz) monkeypatch.setattr("ml4t.data.managers.storage_manager.datetime", Clock) - history = _serve_one_synthetic_history(monkeypatch) - frame = history.filter(pl.col("timestamp").dt.date() <= date(2025, 7, 14)) + with SyntheticProvider(seed=42) as provider: + frame = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-14", "daily") observed = frame.filter(pl.col("timestamp").dt.date() != date(2025, 7, 9)).with_columns( pl.when(pl.col("timestamp").dt.date() == date(2025, 7, 8)) .then(None) @@ -148,15 +128,17 @@ def test_real_cli_rejects_imputation_before_creating_a_dataset(tmp_path): assert HiveStorage(StorageConfig(base_path=tmp_path)).list_keys() == [] -def test_real_cli_default_update_preserves_a_historical_missing_observation(tmp_path, monkeypatch): +def test_real_cli_default_update_preserves_a_historical_missing_observation( + tmp_path, monkeypatch, range_stable_synthetic +): class Clock(datetime): @classmethod def now(cls, tz=UTC): return cls(2025, 7, 15, 23, tzinfo=tz) monkeypatch.setattr("ml4t.data.managers.storage_manager.datetime", Clock) - history = _serve_one_synthetic_history(monkeypatch) - complete = history.filter(pl.col("timestamp").dt.date() <= date(2025, 7, 14)) + with SyntheticProvider(seed=42) as provider: + complete = provider.fetch_ohlcv("SPY", "2025-07-07", "2025-07-14", "daily") observed = complete.filter(pl.col("timestamp").dt.date() != date(2025, 7, 9)) storage = HiveStorage(StorageConfig(base_path=tmp_path)) with DataManager(storage=storage, enable_validation=False) as manager: diff --git a/tests/test_update_manager.py b/tests/test_update_manager.py index 16feb6a..b13b1d5 100644 --- a/tests/test_update_manager.py +++ b/tests/test_update_manager.py @@ -478,15 +478,19 @@ def existing_data(self) -> pl.DataFrame: @pytest.fixture def new_data(self) -> pl.DataFrame: - """Create new data (Jan 10-25, overlapping).""" + """Create new data (Jan 10-25, overlapping). + + Overlapping rows keep the stored close: a changed close in every overlapping row is a + restatement, which the incremental strategies refuse to splice. + """ dates = [datetime(2024, 1, 10) + timedelta(days=i) for i in range(16)] return pl.DataFrame( { "timestamp": dates, "open": [105.0] * 16, "high": [106.0] * 16, - "low": [104.0] * 16, - "close": [105.0] * 16, + "low": [99.0] * 16, + "close": [100.0] * 6 + [105.0] * 10, "volume": [2000000] * 16, } )