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
15 changes: 12 additions & 3 deletions src/ml4t/data/providers/binance_public.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down
30 changes: 30 additions & 0 deletions tests/test_binance_public_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]
Loading