From f3d84d0a69420d921298181bd29d3d3d18dcfc8e Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Tue, 24 Nov 2026 16:57:29 -0500 Subject: [PATCH] Decode microsecond timestamps in Binance spot kline archives --- src/ml4t/data/providers/binance_public.py | 15 +++++++++--- tests/test_binance_public_provider.py | 30 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/ml4t/data/providers/binance_public.py b/src/ml4t/data/providers/binance_public.py index 6c68a6ec..81528759 100644 --- a/src/ml4t/data/providers/binance_public.py +++ b/src/ml4t/data/providers/binance_public.py @@ -204,6 +204,16 @@ def _build_monthly_url(self, symbol: str, interval: str, year: int, month: int) return f"{self.BASE_URL}/{path}" + def _kline_timestamp(self) -> pl.Expr: + timestamp = pl.col("timestamp") + microseconds = timestamp * 1000 + if self.market == "spot": + # Spot archives switched to microseconds at 2025-01-01 00:00 UTC. + microseconds = ( + pl.when(timestamp >= 1_735_689_600_000_000).then(timestamp).otherwise(microseconds) + ) + return microseconds.cast(pl.Datetime("us", "UTC")).alias("timestamp") + def _download_and_parse_zip(self, url: str) -> pl.DataFrame | None: """Download ZIP file and parse CSV contents. @@ -298,8 +308,7 @@ def _download_and_parse_zip(self, url: str) -> pl.DataFrame | None: ] ) - # Convert timestamp from milliseconds - df = df.with_columns(pl.col("timestamp").cast(pl.Datetime("ms", "UTC"))) + df = df.with_columns(self._kline_timestamp()) return df @@ -1321,7 +1330,7 @@ def parse_zip_content(content: bytes) -> pl.DataFrame | None: ] ) - df = df.with_columns(pl.col("timestamp").cast(pl.Datetime("ms", "UTC"))) + df = df.with_columns(self._kline_timestamp()) return df return await asyncio.to_thread(parse_zip_content, response.content) diff --git a/tests/test_binance_public_provider.py b/tests/test_binance_public_provider.py index 398ff15b..aa58888f 100644 --- a/tests/test_binance_public_provider.py +++ b/tests/test_binance_public_provider.py @@ -817,3 +817,33 @@ def test_futures_market_complete_workflow(self): df = provider.fetch_ohlcv("BTCUSDT", "2024-01-01", "2024-01-05", "daily") assert not df.is_empty() + + +@pytest.mark.parametrize("market", ["spot", "futures"]) +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.asyncio +async def test_daily_archive_unit_change_keeps_both_sides_of_new_year(market, use_async): + def archive(url): + date = url.removesuffix(".zip")[-10:] + timestamp = {"2024-12-31": 1735603200000, "2025-01-01": 1735689600000}[date] + unit = 1000 if market == "spot" and date == "2025-01-01" else 1 + row = f"{timestamp * unit},100,101,99,100,1000,{(timestamp + 86400000) * unit - 1},100000,5,500,50000,0\n" + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zipped: + zipped.writestr(f"BTCUSDT-1d-{date}.csv", row) + return httpx.Response(200, content=buf.getvalue(), request=httpx.Request("GET", url)) + + with BinancePublicProvider(market=market) as provider: + args = ("BTCUSDT", "2024-12-31", "2025-01-01", "daily") + if use_async: + async with provider: + with patch.object(provider._async_session, "get", side_effect=archive): + bars = await provider.fetch_ohlcv_async(*args) + else: + with patch.object(provider.session, "get", side_effect=archive): + bars = provider.fetch_ohlcv(*args) + + assert bars.select("timestamp", "close").rows() == [ + (datetime(2024, 12, 31, tzinfo=UTC), 100.0), + (datetime(2025, 1, 1, tzinfo=UTC), 100.0), + ]