Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loaders): honor interval in local loader by resampling

Lanre Shittu12bdca5c1c94
diff --git a/agent/backtest/loaders/local_loader.py b/agent/backtest/loaders/local_loader.py
index 879b4de52..00bfa5f97 100644
--- a/agent/backtest/loaders/local_loader.py
+++ b/agent/backtest/loaders/local_loader.py
@@ -55,6 +55,73 @@ _DEFAULT_COLUMNS = {
"volume": "volume",
}
+# Map the project's bar intervals (see ``backtest.runner._VALID_INTERVALS``) to
+# pandas offset aliases used for resampling. All entries are fixed-duration so
+# ``pd.Timedelta`` of the alias is well defined.
+_RESAMPLE_RULES = {
+ "1m": "1min",
+ "5m": "5min",
+ "15m": "15min",
+ "30m": "30min",
+ "1H": "1h",
+ "4H": "4h",
+ "1D": "1D",
+}
+
+_OHLCV_AGG = {
+ "open": "first",
+ "high": "max",
+ "low": "min",
+ "close": "last",
+ "volume": "sum",
+}
+
+
+def _resample_to_interval(df: pd.DataFrame, interval: str, symbol: str) -> pd.DataFrame:
+ """Resample an OHLCV frame to the requested bar ``interval``.
+
+ Local files can hold any native granularity, so a requested interval the
+ file does not already match must be honored explicitly. Previously
+ ``interval`` was passed only to the cache key, so requesting e.g. ``4H``
+ against hourly data silently returned the file's native bars.
+
+ Coarser-than-source requests are downsampled with the standard OHLCV
+ aggregation. A finer-than-source request cannot be fabricated from a file,
+ so the source bars are returned unchanged with a warning. Requests that
+ already match the source granularity are returned unchanged.
+ """
+ rule = _RESAMPLE_RULES.get(interval)
+ if df.empty:
+ return df
+ if rule is None:
+ logger.warning(
+ "local loader: unsupported interval %r for %s; returning source bars",
+ interval,
+ symbol,
+ )
+ return df
+
+ target = pd.Timedelta(rule)
+ if len(df.index) >= 2:
+ source = df.index.to_series().diff().dropna().median()
+ if pd.notna(source):
+ if target < source:
+ logger.warning(
+ "local loader: cannot upsample %s source bars to %s for %s; "
+ "returning source bars",
+ source,
+ interval,
+ symbol,
+ )
+ return df
+ if target == source:
+ return df
+
+ resampled = df.resample(rule).agg(_OHLCV_AGG)
+ resampled = resampled.dropna(subset=["open", "high", "low", "close"])
+ resampled.index.name = df.index.name
+ return resampled
+
def _load_config() -> dict[str, Any] | None:
if not _CONFIG_PATH.exists():
@@ -214,7 +281,7 @@ class DataLoader:
start_date=start_date,
end_date=end_date,
fields=None,
- fetch=lambda c=clean: self._fetch_one(c, start_date, end_date),
+ fetch=lambda c=clean: self._fetch_one(c, start_date, end_date, interval),
)
if df is not None and not df.empty:
result[clean] = df
@@ -224,7 +291,7 @@ class DataLoader:
return result
def _fetch_one(
- self, symbol: str, start_date: str, end_date: str,
+ self, symbol: str, start_date: str, end_date: str, interval: str = "1D",
) -> pd.DataFrame | None:
entry = self._source_by_symbol.get(symbol)
if entry is None:
@@ -269,8 +336,14 @@ class DataLoader:
return None
start = pd.Timestamp(start_date)
- end = pd.Timestamp(end_date)
+ # Treat ``end_date`` as inclusive of the whole day so intraday bars on
+ # the end day survive the filter (a bare midnight bound dropped them,
+ # which would defeat any sub-daily ``interval``).
+ end = pd.Timestamp(end_date) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)
df = df[(df.index >= start) & (df.index <= end)]
+ if df.empty:
+ return None
+ df = _resample_to_interval(df, interval, symbol)
if df.empty:
return None
return df
diff --git a/agent/tests/test_local_loader.py b/agent/tests/test_local_loader.py
index e9c6b1fc8..2e5bdab86 100644
--- a/agent/tests/test_local_loader.py
+++ b/agent/tests/test_local_loader.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import logging
from pathlib import Path
import pytest
@@ -60,6 +61,114 @@ def test_local_loader_fetches_csv_with_local_prefix(
assert list(frames["AAPL.US"]["close"]) == [10.5, 12.5]
+def _intraday_csv(tmp_path: Path) -> Path:
+ """Write 8 hourly bars on 2026-01-01 (00:00..07:00)."""
+ rows = ["Date,Open,High,Low,Close,Volume"]
+ bars = [
+ ("2026-01-01 00:00:00", 10, 12, 9, 11, 100),
+ ("2026-01-01 01:00:00", 11, 13, 10, 12, 110),
+ ("2026-01-01 02:00:00", 12, 14, 11, 13, 120),
+ ("2026-01-01 03:00:00", 13, 15, 12, 14, 130),
+ ("2026-01-01 04:00:00", 14, 16, 13, 15, 140),
+ ("2026-01-01 05:00:00", 15, 17, 14, 16, 150),
+ ("2026-01-01 06:00:00", 16, 18, 15, 17, 160),
+ ("2026-01-01 07:00:00", 17, 19, 16, 18, 170),
+ ]
+ rows += [f"{d},{o},{h},{lo},{c},{v}" for d, o, h, lo, c, v in bars]
+ path = tmp_path / "intraday.csv"
+ path.write_text("\n".join(rows), encoding="utf-8")
+ return path
+
+
+def _intraday_source(csv_path: Path) -> dict:
+ return {
+ "symbol": "AAA.US",
+ "type": "csv",
+ "path": str(csv_path),
+ "columns": {
+ "date": "Date",
+ "open": "Open",
+ "high": "High",
+ "low": "Low",
+ "close": "Close",
+ "volume": "Volume",
+ },
+ }
+
+
+def test_local_loader_resamples_intraday_to_coarser_interval(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Requesting 4H against hourly bars must aggregate, not silently return hourly."""
+ csv_path = _intraday_csv(tmp_path)
+ _configure(monkeypatch, tmp_path, [_intraday_source(csv_path)])
+
+ frames = local_loader.DataLoader().fetch(
+ ["AAA.US"], "2026-01-01", "2026-01-01", interval="4H"
+ )
+
+ df = frames["AAA.US"]
+ assert len(df) == 2 # 00:00-03:59 and 04:00-07:59 buckets
+ first, second = df.iloc[0], df.iloc[1]
+ # First 4H bar aggregates hours 0-3.
+ assert first["open"] == 10
+ assert first["high"] == 15
+ assert first["low"] == 9
+ assert first["close"] == 14
+ assert first["volume"] == 100 + 110 + 120 + 130
+ # Second 4H bar aggregates hours 4-7.
+ assert second["open"] == 14
+ assert second["close"] == 18
+ assert second["volume"] == 140 + 150 + 160 + 170
+
+
+def test_local_loader_warns_and_keeps_source_when_upsampling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ """Requesting a finer interval than the file holds cannot fabricate bars."""
+ csv_path = tmp_path / "daily.csv"
+ csv_path.write_text(
+ "\n".join(
+ [
+ "Date,Open,High,Low,Close,Volume",
+ "2026-01-01,10,11,9,10.5,1000",
+ "2026-01-02,12,13,11,12.5,1500",
+ "2026-01-03,13,14,12,13.5,1200",
+ ]
+ ),
+ encoding="utf-8",
+ )
+ _configure(
+ monkeypatch,
+ tmp_path,
+ [
+ {
+ "symbol": "AAA.US",
+ "type": "csv",
+ "path": str(csv_path),
+ "columns": {
+ "date": "Date",
+ "open": "Open",
+ "high": "High",
+ "low": "Low",
+ "close": "Close",
+ "volume": "Volume",
+ },
+ }
+ ],
+ )
+
+ with caplog.at_level(logging.WARNING, logger="backtest.loaders.local_loader"):
+ frames = local_loader.DataLoader().fetch(
+ ["AAA.US"], "2026-01-01", "2026-01-03", interval="4H"
+ )
+
+ df = frames["AAA.US"]
+ assert len(df) == 3 # daily source bars returned unchanged
+ assert list(df["close"]) == [10.5, 12.5, 13.5]
+ assert any("upsample" in rec.message.lower() for rec in caplog.records)
+
+
def test_local_loader_fetches_duckdb_without_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: