Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): opt-in local data cache for all backtest data sources (#177)

Matt Van Hornff56134b91ac
diff --git a/agent/.env.example b/agent/.env.example
index eb8c0ee3f..35e26beb2 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -105,6 +105,13 @@ TUSHARE_TOKEN=your-tushare-token
# FUTU_HOST=127.0.0.1
# FUTU_PORT=11111
+# Opt-in local market-data cache for backtest loaders (off by default).
+# When enabled, every data source caches settled historical bars under
+# ~/.vibe-trading/cache/loaders/ so repeated/long-horizon backtests skip the
+# network. Only fully-elapsed days are cached (ranges ending today are always
+# re-fetched). Clear it any time with: rm -rf ~/.vibe-trading/cache
+# VIBE_TRADING_DATA_CACHE=1
+
# ============================================================================
# API Server (optional)
# ============================================================================
diff --git a/agent/backtest/loaders/akshare_loader.py b/agent/backtest/loaders/akshare_loader.py
index 43d052e7e..e4b981f8b 100644
--- a/agent/backtest/loaders/akshare_loader.py
+++ b/agent/backtest/loaders/akshare_loader.py
@@ -11,7 +11,7 @@ from typing import Dict, List, Optional
import pandas as pd
-from backtest.loaders.base import validate_date_range
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
from backtest.loaders.registry import register
logger = logging.getLogger(__name__)
@@ -116,7 +116,15 @@ class DataLoader:
result: Dict[str, pd.DataFrame] = {}
for code in codes:
try:
- df = self._fetch_one(code, start_date, end_date, interval)
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date, interval),
+ )
if df is not None and not df.empty:
result[code] = df
except Exception as exc:
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.py
index e450928bd..45fdb2547 100644
--- a/agent/backtest/loaders/base.py
+++ b/agent/backtest/loaders/base.py
@@ -1,4 +1,4 @@
-"""DataLoader Protocol, shared exceptions, and bounded-retry helpers.
+"""DataLoader Protocol, shared exceptions, retry helpers, and loader cache.
The retry/budget helpers are the canonical pattern for any loader that calls
a flaky external API: a wall-clock deadline plus a small backoff schedule
@@ -9,11 +9,20 @@ re-implementing the loop.
from __future__ import annotations
+import datetime as dt
+import hashlib
+import json
+import logging
+import os
import time
+import uuid
+from pathlib import Path
from typing import Callable, Protocol, TypeVar, runtime_checkable
import pandas as pd
+logger = logging.getLogger(__name__)
+
class NoAvailableSourceError(Exception):
"""Raised when no data source is available for a given market."""
@@ -123,6 +132,356 @@ def retry_with_budget(
raise AssertionError("unreachable: retry loop must return or raise") # pragma: no cover
+# ---------------------------------------------------------------------------
+# Opt-in local loader cache.
+# ---------------------------------------------------------------------------
+
+LOADER_CACHE_ENV = "VIBE_TRADING_DATA_CACHE"
+_LOADER_CACHE_TRUE_VALUES = {"1", "true", "yes", "on"}
+# Bump when the key payload or on-disk layout changes so stale entries are
+# simply never matched (old files become unreachable garbage, safe to delete).
+_LOADER_CACHE_VERSION = 2
+
+
+def loader_cache_enabled() -> bool:
+ """Return whether the local market-data cache is explicitly enabled."""
+ return os.getenv(LOADER_CACHE_ENV, "").strip().lower() in _LOADER_CACHE_TRUE_VALUES
+
+
+def make_loader_cache_key(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None = None,
+) -> str:
+ """Build a stable content-addressed key for one loader payload."""
+ payload = _loader_cache_payload(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ )
+ blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
+ return hashlib.sha256(blob).hexdigest()
+
+
+def loader_cache_path(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None = None,
+) -> Path:
+ """Return the parquet cache path for one loader payload."""
+ key = make_loader_cache_key(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ )
+ source_dir = _sanitize_cache_segment(source)
+ return Path.home() / ".vibe-trading" / "cache" / "loaders" / source_dir / f"{key}.parquet"
+
+
+def loader_cache_range_is_final(end_date: str) -> bool:
+ """Return whether ``end_date`` is settled enough to cache.
+
+ The key is content-addressed on ``end_date`` but not on wall-clock fetch
+ time, so caching a range whose last bar is still forming (``end_date`` today
+ or in the future) would pin a provisional bar and serve it on every later
+ run. Only fully-elapsed days (strictly before today) are cacheable.
+ """
+ try:
+ end = pd.Timestamp(end_date).normalize().date()
+ except Exception: # noqa: BLE001 - an unparseable date is treated as not cacheable
+ return False
+ return end < dt.date.today()
+
+
+def loader_cache_get(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None = None,
+) -> pd.DataFrame | None:
+ """Return a cached DataFrame for one payload, or ``None`` on any miss.
+
+ Misses include: cache disabled, range not yet settled, entry absent, or a
+ corrupt entry. A corrupt entry is non-fatal — the caller falls back to the
+ live provider.
+ """
+ if not loader_cache_enabled() or not loader_cache_range_is_final(end_date):
+ return None
+ cache_path = loader_cache_path(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ )
+ return _read_loader_cache_frame(cache_path)
+
+
+def loader_cache_put(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None,
+ frame: pd.DataFrame | None,
+) -> None:
+ """Write one non-empty DataFrame to the cache; a no-op when not cacheable.
+
+ Skips a disabled cache, an unsettled range, and empty/non-DataFrame results.
+ Write failures are swallowed so a fetch never fails because of the cache.
+ """
+ if not loader_cache_enabled() or not loader_cache_range_is_final(end_date):
+ return
+ if not isinstance(frame, pd.DataFrame) or frame.empty:
+ return
+ cache_path = loader_cache_path(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ )
+ _write_loader_cache_frame(cache_path, frame)
+
+
+def cached_loader_fetch(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None,
+ fetch: Callable[[], pd.DataFrame | None],
+) -> pd.DataFrame | None:
+ """Fetch one DataFrame through the opt-in local cache.
+
+ Convenience wrapper over :func:`loader_cache_get` / :func:`loader_cache_put`
+ for the common per-symbol loader loop: return the cached frame when present,
+ otherwise call ``fetch`` and cache a non-empty result. Cache read/write
+ failures are non-fatal and fall back to ``fetch``.
+ """
+ cached = loader_cache_get(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ )
+ if cached is not None:
+ return cached
+
+ frame = fetch()
+ loader_cache_put(
+ source=source,
+ symbol=symbol,
+ timeframe=timeframe,
+ start_date=start_date,
+ end_date=end_date,
+ fields=fields,
+ frame=frame,
+ )
+ return frame
+
+
+def _loader_cache_payload(
+ *,
+ source: str,
+ symbol: str,
+ timeframe: str,
+ start_date: str,
+ end_date: str,
+ fields: list[str] | tuple[str, ...] | None,
+) -> dict[str, object]:
+ return {
+ "version": _LOADER_CACHE_VERSION,
+ "source": str(source),
+ "symbol": str(symbol),
+ "timeframe": str(timeframe),
+ "start_date": _normalize_cache_date(start_date),
+ "end_date": _normalize_cache_date(end_date),
+ "fields": [str(field) for field in (fields or ())],
+ }
+
+
+def _normalize_cache_date(value: str) -> str:
+ return pd.Timestamp(value).strftime("%Y-%m-%d")
+
+
+def _sanitize_cache_segment(value: str) -> str:
+ cleaned = "".join(ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in value.strip().lower())
+ return cleaned or "unknown"
+
+
+def _loader_cache_metadata_path(cache_path: Path) -> Path:
+ return cache_path.with_suffix(cache_path.suffix + ".json")
+
+
+def _read_loader_cache_frame(cache_path: Path) -> pd.DataFrame | None:
+ if not cache_path.is_file():
+ return None
+
+ metadata_path = _loader_cache_metadata_path(cache_path)
+ try:
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ except Exception as exc: # noqa: BLE001 - local cache miss is non-fatal
+ logger.warning("loader cache metadata read failed for %s: %s", cache_path.name, exc)
+ return None
+
+ con = None
+ try:
+ import duckdb
+
+ con = duckdb.connect(database=":memory:")
+ frame = con.execute(
+ f"SELECT * FROM read_parquet({_duckdb_sql_string(cache_path)})"
+ ).fetchdf()
+ except Exception as exc: # noqa: BLE001 - corrupt cache falls back to provider
+ logger.warning("loader cache read failed for %s: %s", cache_path.name, exc)
+ return None
+ finally:
+ if con is not None:
+ con.close()
+
+ index_columns = metadata.get("index_columns") or []
+ if index_columns:
+ missing = [column for column in index_columns if column not in frame.columns]
+ if missing:
+ logger.warning("loader cache %s missing index column(s): %s", cache_path.name, missing)
+ return None
+ frame = frame.set_index(index_columns)
+ frame.index.names = metadata.get("index_names") or index_columns
+ frame = _restore_cache_index_dtypes(frame, metadata.get("index_dtypes"))
+ frame.columns.name = metadata.get("columns_name")
+ return frame
+
+
+def _restore_cache_index_dtypes(frame: pd.DataFrame, index_dtypes: object) -> pd.DataFrame:
+ """Best-effort restore of the per-level index dtypes recorded at write time.
+
+ Cosmetic and non-fatal: duckdb parquet may rewrite datetime resolution, so
+ we cast each level back to its original dtype. A failed cast leaves the
+ duckdb-provided dtype rather than failing the read.
+ """
+ if not isinstance(index_dtypes, list) or frame.index.nlevels != len(index_dtypes):
+ return frame
+ try:
+ if frame.index.nlevels == 1:
+ frame.index = frame.index.astype(index_dtypes[0])
+ else:
+ for level, dtype in enumerate(index_dtypes):
+ frame.index = frame.index.set_levels(
+ frame.index.levels[level].astype(dtype), level=level
+ )
+ except Exception: # noqa: BLE001 - index dtype restore is cosmetic
+ logger.debug("loader cache index dtype restore skipped: %s", index_dtypes)
+ return frame
+
+
+def _write_loader_cache_frame(cache_path: Path, frame: pd.DataFrame) -> None:
+ metadata_path = _loader_cache_metadata_path(cache_path)
+ # pid + uuid so two concurrent writers of the same key never share a tmp
+ # path; os.replace then swaps each file in atomically.
+ unique = f"{os.getpid()}.{uuid.uuid4().hex}"
+ tmp_path = cache_path.with_name(f"{cache_path.name}.{unique}.tmp")
+ tmp_metadata_path = metadata_path.with_name(f"{metadata_path.name}.{unique}.tmp")
+
+ try:
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ cache_frame, metadata = _frame_for_loader_cache(frame)
+
+ import duckdb
+
+ con = duckdb.connect(database=":memory:")
+ try:
+ con.register("cache_frame", cache_frame)
+ con.execute(f"COPY cache_frame TO {_duckdb_sql_string(tmp_path)} (FORMAT PARQUET)")
+ finally:
+ con.close()
+
+ tmp_metadata_path.write_text(
+ json.dumps(metadata, sort_keys=True, separators=(",", ":")),
+ encoding="utf-8",
+ )
+ os.replace(tmp_path, cache_path)
+ os.replace(tmp_metadata_path, metadata_path)
+ except Exception as exc: # noqa: BLE001 - cache write failures should not fail fetches
+ logger.warning("loader cache write failed for %s: %s", cache_path.name, exc)
+ for path in (tmp_path, tmp_metadata_path):
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+ except OSError:
+ pass
+
+
+def _frame_for_loader_cache(frame: pd.DataFrame) -> tuple[pd.DataFrame, dict[str, object]]:
+ cache_frame = frame.copy()
+ original_index_names = list(cache_frame.index.names)
+ columns_name = cache_frame.columns.name
+ index_dtypes = [
+ str(cache_frame.index.get_level_values(level).dtype)
+ for level in range(cache_frame.index.nlevels)
+ ]
+ index_columns = _cache_index_columns(cache_frame)
+ cache_frame.index = cache_frame.index.set_names(index_columns)
+ metadata: dict[str, object] = {
+ "version": _LOADER_CACHE_VERSION,
+ "index_columns": index_columns,
+ "index_names": original_index_names,
+ # Preserve the columns-axis name (e.g. yfinance leaves "Price") and the
+ # per-level index dtypes so a cached frame round-trips byte-identical to
+ # a freshly fetched one (duckdb parquet otherwise rewrites datetime
+ # resolution, e.g. [s] -> [us]).
+ "columns_name": None if columns_name is None else str(columns_name),
+ "index_dtypes": index_dtypes,
+ }
+ return cache_frame.reset_index(), metadata
+
+
+def _cache_index_columns(frame: pd.DataFrame) -> list[str]:
+ columns = {str(column) for column in frame.columns}
+ used: set[str] = set()
+ index_columns: list[str] = []
+ for pos, name in enumerate(frame.index.names):
+ base = str(name) if name is not None else f"__vibe_loader_index_{pos}__"
+ candidate = base
+ suffix = 1
+ while candidate in columns or candidate in used:
+ candidate = f"{base}_{suffix}"
+ suffix += 1
+ index_columns.append(candidate)
+ used.add(candidate)
+ return index_columns
+
+
+def _duckdb_sql_string(path: Path) -> str:
+ return "'" + str(path).replace("'", "''") + "'"
+
+
@runtime_checkable
class DataLoaderProtocol(Protocol):
"""Interface that every data source loader must satisfy."""
diff --git a/agent/backtest/loaders/ccxt_loader.py b/agent/backtest/loaders/ccxt_loader.py
index bd38acc4e..865655c0c 100644
--- a/agent/backtest/loaders/ccxt_loader.py
+++ b/agent/backtest/loaders/ccxt_loader.py
@@ -15,6 +15,7 @@ from typing import Dict, List, Optional
import pandas as pd
from backtest.loaders.base import (
+ cached_loader_fetch,
check_budget,
retry_with_budget,
validate_date_range,
@@ -116,16 +117,34 @@ class DataLoader:
"""
validate_date_range(start_date, end_date)
- exchange = self._get_exchange()
timeframe = _INTERVAL_MAP.get(interval, "1d")
since_ms = int(pd.Timestamp(start_date).timestamp() * 1000)
end_ms = int((pd.Timestamp(end_date) + pd.Timedelta(days=1)).timestamp() * 1000)
+ # Build the exchange lazily so a full cache hit never imports ccxt or
+ # opens an exchange object.
+ exchange_holder: Dict[str, object] = {}
+
+ def get_exchange():
+ if "exchange" not in exchange_holder:
+ exchange_holder["exchange"] = self._get_exchange()
+ return exchange_holder["exchange"]
+
result: Dict[str, pd.DataFrame] = {}
for code in codes:
try:
ccxt_symbol = code.replace("-", "/").upper()
- df = self._fetch_one(exchange, ccxt_symbol, timeframe, since_ms, end_ms)
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda ccxt_symbol=ccxt_symbol: self._fetch_one(
+ get_exchange(), ccxt_symbol, timeframe, since_ms, end_ms
+ ),
+ )
if df is not None and not df.empty:
result[code] = df
except Exception as exc:
diff --git a/agent/backtest/loaders/futu.py b/agent/backtest/loaders/futu.py
index 2215a9c5f..02d1576fe 100644
--- a/agent/backtest/loaders/futu.py
+++ b/agent/backtest/loaders/futu.py
@@ -8,7 +8,12 @@ from typing import Dict, List, Optional
import pandas as pd
-from backtest.loaders.base import NoAvailableSourceError, validate_date_range
+from backtest.loaders.base import (
+ NoAvailableSourceError,
+ loader_cache_get,
+ loader_cache_put,
+ validate_date_range,
+)
from backtest.loaders.registry import register
logger = logging.getLogger(__name__)
@@ -133,6 +138,29 @@ class FutuLoader:
return {}
validate_date_range(start_date, end_date)
+ results: Dict[str, pd.DataFrame] = {}
+
+ # Serve cached symbols first; only open a FutuOpenD connection when at
+ # least one symbol is uncached, so a fully-cached request needs no
+ # running gateway.
+ pending: List[str] = []
+ for code in codes:
+ cached = loader_cache_get(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ )
+ if cached is not None:
+ results[code] = cached.copy()
+ else:
+ pending.append(code)
+
+ if not pending:
+ return results
+
try:
import futu # noqa: PLC0415
ktype = _to_futu_ktype(interval)
@@ -142,9 +170,8 @@ class FutuLoader:
f"Cannot connect to FutuOpenD at {self._host}:{self._port}: {exc}"
) from exc
- results: Dict[str, pd.DataFrame] = {}
try:
- for code in codes:
+ for code in pending:
futu_code = _to_futu_symbol(code)
ret, data = ctx.request_history_kline(
futu_code,
@@ -156,7 +183,17 @@ class FutuLoader:
if ret != futu.RET_OK:
logger.warning("Futu returned error for %s: %s", futu_code, data)
continue
- results[code] = _normalize_frame(data)
+ normalized = _normalize_frame(data)
+ loader_cache_put(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ frame=normalized,
+ )
+ results[code] = normalized
finally:
ctx.close()
diff --git a/agent/backtest/loaders/mootdx_loader.py b/agent/backtest/loaders/mootdx_loader.py
index 0c7a7b36f..cc540fbbf 100644
--- a/agent/backtest/loaders/mootdx_loader.py
+++ b/agent/backtest/loaders/mootdx_loader.py
@@ -17,7 +17,7 @@ from typing import Dict, List, Optional
import pandas as pd
-from backtest.loaders.base import validate_date_range
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
from backtest.loaders.registry import register
logger = logging.getLogger(__name__)
@@ -132,7 +132,15 @@ class DataLoader:
)
continue
try:
- df = self._fetch_one(code, start_date, end_date, interval)
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date, interval),
+ )
if df is not None and not df.empty:
result[code] = df
except Exception as exc:
diff --git a/agent/backtest/loaders/okx.py b/agent/backtest/loaders/okx.py
index f655e21e9..a10797064 100644
--- a/agent/backtest/loaders/okx.py
+++ b/agent/backtest/loaders/okx.py
@@ -13,6 +13,7 @@ import pandas as pd
import requests
from backtest.loaders.base import (
+ cached_loader_fetch,
check_budget,
retry_with_budget,
validate_date_range,
@@ -85,7 +86,17 @@ class DataLoader:
result: Dict[str, pd.DataFrame] = {}
for symbol in codes:
try:
- df = self._fetch_candles(symbol, start_ts, end_ts, interval, max_pages)
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=symbol,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda symbol=symbol: self._fetch_candles(
+ symbol, start_ts, end_ts, interval, max_pages
+ ),
+ )
if df is not None and not df.empty:
result[symbol] = df
except Exception as exc:
diff --git a/agent/backtest/loaders/tushare.py b/agent/backtest/loaders/tushare.py
index 5e555fc72..cdd342286 100644
--- a/agent/backtest/loaders/tushare.py
+++ b/agent/backtest/loaders/tushare.py
@@ -9,7 +9,7 @@ from typing import Dict, List, Optional
import pandas as pd
-from backtest.loaders.base import validate_date_range
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
from backtest.loaders.registry import register
@@ -62,28 +62,61 @@ class DataLoader:
sd = start_date.replace("-", "")
ed = end_date.replace("-", "")
+ cache_fields = list(fields or [])
result: Dict[str, pd.DataFrame] = {}
+ # Every code goes through the opt-in cache helper, which is a direct
+ # passthrough when the cache is disabled. Fundamentals are merged inside
+ # the cached unit so a cached entry already carries its extra columns.
for code in codes:
- try:
- df = self.api.daily(ts_code=code, start_date=sd, end_date=ed)
- if df is None or df.empty:
- continue
- df = df.sort_values("trade_date")
- df["trade_date"] = pd.to_datetime(df["trade_date"])
- df = df.set_index("trade_date")
- df = df.rename(columns={"vol": "volume"})
- for col in ["open", "high", "low", "close", "volume"]:
- if col in df.columns:
- df[col] = pd.to_numeric(df[col], errors="coerce")
- ohlcv = df[["open", "high", "low", "close", "volume"]].dropna(
- subset=["open", "high", "low", "close"]
- )
- result[code] = ohlcv
- except Exception as exc:
- print(f"[WARN] failed to fetch {code}: {exc}")
+ def _fetch_one(code: str = code) -> Optional[pd.DataFrame]:
+ try:
+ df = self._fetch_daily_frame(code, sd, ed)
+ if df is None:
+ return None
+ merged = self._merge_basic_fields(
+ {code: df}, [code], start_date, end_date, cache_fields
+ )
+ return merged.get(code)
+ except Exception as exc:
+ print(f"[WARN] failed to fetch {code}: {exc}")
+ return None
+
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe="1D",
+ start_date=start_date,
+ end_date=end_date,
+ fields=cache_fields,
+ fetch=_fetch_one,
+ )
+ if df is not None and not df.empty:
+ result[code] = df
- return self._merge_basic_fields(result, codes, start_date, end_date, fields)
+ return result
+
+ def _fetch_daily_frame(
+ self,
+ code: str,
+ start_date: str,
+ end_date: str,
+ ) -> Optional[pd.DataFrame]:
+ """Fetch and normalize one daily OHLCV frame."""
+ df = self.api.daily(ts_code=code, start_date=start_date, end_date=end_date)
+ if df is None or df.empty:
+ return None
+ df = df.sort_values("trade_date")
+ df["trade_date"] = pd.to_datetime(df["trade_date"])
+ df = df.set_index("trade_date")
+ df = df.rename(columns={"vol": "volume"})
+ for col in ["open", "high", "low", "close", "volume"]:
+ if col in df.columns:
+ df[col] = pd.to_numeric(df[col], errors="coerce")
+ ohlcv = df[["open", "high", "low", "close", "volume"]].dropna(
+ subset=["open", "high", "low", "close"]
+ )
+ return ohlcv
def _merge_basic_fields(
self,
diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.py
index 952ff593f..cc8d24cb7 100644
--- a/agent/backtest/loaders/yfinance_loader.py
+++ b/agent/backtest/loaders/yfinance_loader.py
@@ -8,7 +8,7 @@ from typing import Dict, List, Optional, Union
import pandas as pd
import yfinance as yf
-from backtest.loaders.base import validate_date_range
+from backtest.loaders.base import loader_cache_get, loader_cache_put, validate_date_range
from backtest.loaders.registry import register
_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]
@@ -243,15 +243,36 @@ class DataLoader:
unique_symbols = list(symbol_groups.keys())
results: Dict[str, pd.DataFrame] = {}
+ # Serve cached symbols first so a fully-cached request skips the bulk
+ # download entirely; only uncached symbols hit the network.
+ pending: List[str] = []
+ for symbol in unique_symbols:
+ cached = loader_cache_get(
+ source=self.name,
+ symbol=symbol,
+ timeframe=requested_interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ )
+ if cached is not None:
+ for original_code in symbol_groups[symbol]:
+ results[original_code] = cached.copy()
+ else:
+ pending.append(symbol)
+
+ if not pending:
+ return results
+
try:
- bulk_data = _download_history(unique_symbols, start_date, end_date, yf_interval)
+ bulk_data = _download_history(pending, start_date, end_date, yf_interval)
except Exception as exc:
- print(f"[WARN] yfinance bulk download failed for {unique_symbols}: {exc}")
+ print(f"[WARN] yfinance bulk download failed for {pending}: {exc}")
bulk_data = pd.DataFrame()
- for symbol in unique_symbols:
+ for symbol in pending:
try:
- symbol_frame = _extract_symbol_frame(bulk_data, symbol, len(unique_symbols))
+ symbol_frame = _extract_symbol_frame(bulk_data, symbol, len(pending))
if symbol_frame.empty:
symbol_frame = _download_history(symbol, start_date, end_date, yf_interval)
@@ -260,6 +281,15 @@ class DataLoader:
print(f"[WARN] yfinance returned no usable data for {symbol}")
continue
+ loader_cache_put(
+ source=self.name,
+ symbol=symbol,
+ timeframe=requested_interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ frame=normalized,
+ )
for original_code in symbol_groups[symbol]:
results[original_code] = normalized.copy()
except Exception as exc:
diff --git a/agent/tests/test_loader_retry_helpers.py b/agent/tests/test_loader_retry_helpers.py
index 8098c96ac..df74fb9a1 100644
--- a/agent/tests/test_loader_retry_helpers.py
+++ b/agent/tests/test_loader_retry_helpers.py
@@ -16,15 +16,26 @@ inherit the same guarantees:
from __future__ import annotations
+import datetime as dt
+import sys
import time
+from types import SimpleNamespace
+import pandas as pd
import pytest
import backtest.loaders.base as base
from backtest.loaders.base import (
DEFAULT_BACKOFF,
DEFAULT_MAX_RETRIES,
+ LOADER_CACHE_ENV,
+ cached_loader_fetch,
check_budget,
+ loader_cache_get,
+ loader_cache_path,
+ loader_cache_put,
+ loader_cache_range_is_final,
+ make_loader_cache_key,
retry_with_budget,
)
@@ -152,3 +163,313 @@ def test_check_budget_message_omits_budget_when_absent():
check_budget(time.monotonic() - 1, "label")
assert "budget" in str(ei.value)
assert "0s" not in str(ei.value) # don't print "0s budget" by accident
+
+
+def fake_duckdb(monkeypatch):
+ """Install a tiny DuckDB stand-in so cache tests stay dependency-light."""
+
+ class _Connection:
+ def __init__(self):
+ self._tables = {}
+ self._frame = None
+
+ def register(self, name, frame):
+ self._tables[name] = frame.copy()
+
+ def execute(self, sql):
+ path = _first_sql_string(sql)
+ if sql.strip().upper().startswith("COPY "):
+ self._tables["cache_frame"].to_pickle(path)
+ return self
+ self._frame = pd.read_pickle(path)
+ return self
+
+ def fetchdf(self):
+ return self._frame.copy()
+
+ def close(self):
+ pass
+
+ def _first_sql_string(sql):
+ start = sql.index("'") + 1
+ end = sql.index("'", start)
+ return sql[start:end].replace("''", "'")
+
+ monkeypatch.setitem(
+ sys.modules,
+ "duckdb",
+ SimpleNamespace(connect=lambda database=":memory:": _Connection()),
+ )
+
+
+def _cache_frame(value: float = 1.0) -> pd.DataFrame:
+ frame = pd.DataFrame(
+ {
+ "open": [value],
+ "high": [value + 1],
+ "low": [value - 1],
+ "close": [value + 0.5],
+ "volume": [100],
+ },
+ index=pd.DatetimeIndex(["2025-01-02"], name="trade_date"),
+ )
+ return frame
+
+
+def test_loader_cache_disabled_by_default_bypasses_home(tmp_path, monkeypatch):
+ monkeypatch.delenv(LOADER_CACHE_ENV, raising=False)
+ home = tmp_path / "home"
+ monkeypatch.setenv("HOME", str(home))
+ calls = {"count": 0}
+ frame = _cache_frame()
+
+ def fetch():
+ calls["count"] += 1
+ return frame
+
+ out = cached_loader_fetch(
+ source="tushare",
+ symbol="000001.SZ",
+ timeframe="1D",
+ start_date="2025-01-01",
+ end_date="2025-01-03",
+ fields=None,
+ fetch=fetch,
+ )
+
+ assert calls["count"] == 1
+ pd.testing.assert_frame_equal(out, frame)
+ assert not (home / ".vibe-trading").exists()
+
+
+def test_loader_cache_key_partitions_source_symbol_timeframe_date_and_fields():
+ base_args = {
+ "source": "tushare",
+ "symbol": "000001.SZ",
+ "timeframe": "1D",
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-03",
+ "fields": ["pe"],
+ }
+ key = make_loader_cache_key(**base_args)
+
+ assert make_loader_cache_key(**{**base_args, "source": "akshare"}) != key
+ assert make_loader_cache_key(**{**base_args, "symbol": "600519.SH"}) != key
+ assert make_loader_cache_key(**{**base_args, "timeframe": "1H"}) != key
+ assert make_loader_cache_key(**{**base_args, "start_date": "2024-12-31"}) != key
+ assert make_loader_cache_key(**{**base_args, "end_date": "2025-01-04"}) != key
+ assert make_loader_cache_key(**{**base_args, "fields": ["pb"]}) != key
+
+
+def test_loader_cache_happy_path_writes_then_reuses(
+ tmp_path,
+ monkeypatch,
+ fake_duckdb,
+):
+ monkeypatch.setenv(LOADER_CACHE_ENV, "1")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ calls = {"count": 0}
+ frame = _cache_frame()
+
+ def fetch():
+ calls["count"] += 1
+ return frame.copy()
+
+ kwargs = {
+ "source": "tushare",
+ "symbol": "000001.SZ",
+ "timeframe": "1D",
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-03",
+ "fields": ["pe"],
+ }
+ first = cached_loader_fetch(**kwargs, fetch=fetch)
+ second = cached_loader_fetch(**kwargs, fetch=fetch)
+
+ assert calls["count"] == 1
+ pd.testing.assert_frame_equal(first, frame)
+ pd.testing.assert_frame_equal(second, frame)
+ assert loader_cache_path(**kwargs).is_file()
+ assert str(loader_cache_path(**kwargs)).startswith(str(tmp_path / ".vibe-trading" / "cache"))
+
+
+def test_loader_cache_corrupt_entry_falls_back_to_live_fetch(
+ tmp_path,
+ monkeypatch,
+ fake_duckdb,
+):
+ monkeypatch.setenv(LOADER_CACHE_ENV, "true")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ kwargs = {
+ "source": "tushare",
+ "symbol": "000001.SZ",
+ "timeframe": "1D",
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-03",
+ "fields": [],
+ }
+ cache_path = loader_cache_path(**kwargs)
+ cache_path.parent.mkdir(parents=True)
+ cache_path.write_text("not a parquet file", encoding="utf-8")
+ base._loader_cache_metadata_path(cache_path).write_text(
+ '{"index_columns":["trade_date"],"index_names":["trade_date"],"version":1}',
+ encoding="utf-8",
+ )
+ calls = {"count": 0}
+ frame = _cache_frame()
+
+ def fetch():
+ calls["count"] += 1
+ return frame
+
+ out = cached_loader_fetch(**kwargs, fetch=fetch)
+
+ assert calls["count"] == 1
+ pd.testing.assert_frame_equal(out, frame)
+
+
+def test_tushare_daily_fetch_uses_opt_in_cache_for_bars_and_fields(
+ tmp_path,
+ monkeypatch,
+ fake_duckdb,
+):
+ monkeypatch.setenv(LOADER_CACHE_ENV, "yes")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("TUSHARE_TOKEN", "test-token")
+
+ class _FakeApi:
+ def __init__(self):
+ self.daily_calls = 0
+ self.daily_basic_calls = 0
+
+ def daily(self, ts_code, start_date, end_date):
+ self.daily_calls += 1
+ return pd.DataFrame(
+ {
+ "ts_code": [ts_code, ts_code],
+ "trade_date": ["20250103", "20250102"],
+ "open": [2.0, 1.0],
+ "high": [3.0, 2.0],
+ "low": [1.0, 0.5],
+ "close": [2.5, 1.5],
+ "vol": [200, 100],
+ }
+ )
+
+ def daily_basic(self, ts_code, start_date, end_date, fields):
+ self.daily_basic_calls += 1
+ return pd.DataFrame(
+ {
+ "ts_code": [ts_code, ts_code],
+ "trade_date": ["20250102", "20250103"],
+ "pe": [10.0, 11.0],
+ }
+ )
+
+ api = _FakeApi()
+ monkeypatch.setitem(sys.modules, "tushare", SimpleNamespace(pro_api=lambda token: api))
+
+ from backtest.loaders.tushare import DataLoader
+
+ loader = DataLoader()
+ first = loader.fetch(["000001.SZ"], "2025-01-01", "2025-01-03", fields=["pe"])
+ second = loader.fetch(["000001.SZ"], "2025-01-01", "2025-01-03", fields=["pe"])
+
+ assert api.daily_calls == 1
+ assert api.daily_basic_calls == 1
+ pd.testing.assert_frame_equal(first["000001.SZ"], second["000001.SZ"])
+ assert list(first["000001.SZ"].columns) == ["open", "high", "low", "close", "volume", "pe"]
+
+
+def test_loader_cache_range_is_final_only_for_settled_past():
+ today = dt.date.today()
+ yesterday = (today - dt.timedelta(days=1)).isoformat()
+ tomorrow = (today + dt.timedelta(days=1)).isoformat()
+
+ assert loader_cache_range_is_final(yesterday) is True
+ assert loader_cache_range_is_final(today.isoformat()) is False
+ assert loader_cache_range_is_final(tomorrow) is False
+ # An unparseable end date is conservatively treated as not cacheable.
+ assert loader_cache_range_is_final("not-a-date") is False
+
+
+def test_loader_cache_skips_unsettled_today_range(tmp_path, monkeypatch):
+ """A range ending today must never be cached: its last bar is still forming."""
+ monkeypatch.setenv(LOADER_CACHE_ENV, "1")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ today = dt.date.today().isoformat()
+ start = (dt.date.today() - dt.timedelta(days=5)).isoformat()
+ kwargs = {
+ "source": "okx",
+ "symbol": "BTC-USDT",
+ "timeframe": "1D",
+ "start_date": start,
+ "end_date": today,
+ "fields": None,
+ }
+
+ loader_cache_put(**kwargs, frame=_cache_frame())
+
+ assert loader_cache_get(**kwargs) is None
+ assert not loader_cache_path(**kwargs).exists()
+ assert not (tmp_path / ".vibe-trading").exists()
+
+
+def test_loader_cache_real_duckdb_round_trip(tmp_path, monkeypatch):
+ """Exercise the real duckdb -> parquet -> duckdb path (CI mocks duckdb elsewhere)."""
+ pytest.importorskip("duckdb")
+ monkeypatch.setenv(LOADER_CACHE_ENV, "1")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ frame = _cache_frame()
+ kwargs = {
+ "source": "yfinance",
+ "symbol": "AAPL.US",
+ "timeframe": "1D",
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-03",
+ "fields": None,
+ }
+
+ assert loader_cache_get(**kwargs) is None # cold miss
+ loader_cache_put(**kwargs, frame=frame)
+ restored = loader_cache_get(**kwargs)
+
+ assert restored is not None
+ assert loader_cache_path(**kwargs).is_file()
+ assert restored.index.name == "trade_date"
+ # The cache preserves columns name and per-level index dtype, so a real
+ # duckdb round-trip is byte-identical to the source frame.
+ pd.testing.assert_frame_equal(restored, frame)
+
+
+def test_yfinance_loader_serves_second_fetch_from_cache(tmp_path, monkeypatch, fake_duckdb):
+ """A batch loader (yfinance) must skip its bulk download on a full cache hit."""
+ monkeypatch.setenv(LOADER_CACHE_ENV, "1")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ import backtest.loaders.yfinance_loader as yfl
+
+ calls = {"n": 0}
+
+ def fake_download(tickers, start_date, end_date, interval):
+ calls["n"] += 1
+ return pd.DataFrame(
+ {
+ "Open": [1.0, 2.0],
+ "High": [1.5, 2.5],
+ "Low": [0.5, 1.5],
+ "Close": [1.2, 2.2],
+ "Volume": [100, 200],
+ },
+ index=pd.DatetimeIndex(["2025-01-02", "2025-01-03"], name="Date"),
+ )
+
+ monkeypatch.setattr(yfl, "_download_history", fake_download)
+
+ loader = yfl.DataLoader()
+ first = loader.fetch(["AAPL.US"], "2025-01-01", "2025-01-03")
+ second = loader.fetch(["AAPL.US"], "2025-01-01", "2025-01-03")
+
+ assert calls["n"] == 1 # second fetch is served from cache, no re-download
+ assert "AAPL.US" in first and "AAPL.US" in second
+ pd.testing.assert_frame_equal(first["AAPL.US"], second["AAPL.US"])