Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): add local data loader for CSV/Parquet/DuckDB files (#252)

卫斯李cf32a6dfaa10
diff --git a/agent/backtest/loaders/local_loader.py b/agent/backtest/loaders/local_loader.py
new file mode 100644
index 000000000..c63e5ce47
--- /dev/null
+++ b/agent/backtest/loaders/local_loader.py
@@ -0,0 +1,271 @@
+"""Local data loader: reads CSV, Parquet, and DuckDB files from user config.
+
+Configuration lives at ``~/.vibe-trading/data-bridge/config.yaml``.
+Each entry maps a symbol to a data file with optional column-name overrides,
+date format, and (for DuckDB) an SQL query.
+
+Example config::
+
+ sources:
+ - symbol: "AAPL.US"
+ type: csv
+ path: "~/data/aapl_2024.csv"
+ columns:
+ date: "Date"
+ open: "Open"
+ high: "High"
+ low: "Low"
+ close: "Close"
+ volume: "Volume"
+ date_format: "%Y-%m-%d"
+
+ - symbol: "BTC-USDT"
+ type: parquet
+ path: "~/data/btc.parquet"
+
+ - symbol: "MYINDEX"
+ type: duckdb
+ db_path: "~/data/market.duckdb"
+ query: "SELECT * FROM prices WHERE ticker = 'MYINDEX'"
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+import pandas as pd
+import yaml
+
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+_CONFIG_DIR = Path.home() / ".vibe-trading" / "data-bridge"
+_CONFIG_PATH = _CONFIG_DIR / "config.yaml"
+
+_DEFAULT_COLUMNS = {
+ "date": "date",
+ "open": "open",
+ "high": "high",
+ "low": "low",
+ "close": "close",
+ "volume": "volume",
+}
+
+
+def _load_config() -> dict[str, Any] | None:
+ if not _CONFIG_PATH.exists():
+ return None
+ with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
+ return yaml.safe_load(f) or {}
+
+
+def _normalize_columns(
+ df: pd.DataFrame,
+ col_map: dict[str, str],
+ date_fmt: str | None,
+) -> pd.DataFrame | None:
+ rename: dict[str, str] = {}
+ for std_name, src_name in col_map.items():
+ if std_name == "date":
+ continue
+ if src_name in df.columns:
+ rename[src_name] = std_name
+ df = df.rename(columns=rename)
+
+ required = {"open", "high", "low", "close"}
+ if not required.issubset(df.columns):
+ return None
+
+ date_col = col_map.get("date", "date")
+ if date_col not in df.columns:
+ return None
+
+ if date_fmt:
+ df["trade_date"] = pd.to_datetime(df[date_col], format=date_fmt, errors="coerce")
+ else:
+ df["trade_date"] = pd.to_datetime(df[date_col], errors="coerce")
+ df = df.dropna(subset=["trade_date"])
+ df = df.set_index("trade_date").sort_index()
+
+ ohlcv_cols: list[str] = ["open", "high", "low", "close"]
+ if "volume" in df.columns:
+ ohlcv_cols.append("volume")
+
+ df = df[ohlcv_cols]
+ for col in ohlcv_cols:
+ df[col] = pd.to_numeric(df[col], errors="coerce")
+ df = df.dropna(subset=["open", "high", "low", "close"])
+ for col in ohlcv_cols:
+ df[col] = df[col].astype("float64")
+
+ if "volume" not in df.columns:
+ df["volume"] = 0.0
+
+ return df
+
+
+def _read_csv(path: str, col_map: dict[str, str], date_fmt: str | None) -> pd.DataFrame | None:
+ df = pd.read_csv(path)
+ return _normalize_columns(df, col_map, date_fmt)
+
+
+def _read_parquet(path: str, col_map: dict[str, str], date_fmt: str | None) -> pd.DataFrame | None:
+ df = pd.read_parquet(path)
+ if isinstance(df.index, pd.DatetimeIndex):
+ df = df.reset_index()
+ if date_fmt is None and col_map.get("date", "date") not in df.columns:
+ col_map = dict(col_map)
+ col_map["date"] = df.columns[0]
+ return _normalize_columns(df, col_map, date_fmt)
+
+
+def _read_duckdb(
+ db_path: str, query: str, col_map: dict[str, str], date_fmt: str | None
+) -> pd.DataFrame | None:
+ import duckdb
+
+ with duckdb.connect(db_path, read_only=True) as conn:
+ df = conn.execute(query).df()
+ return _normalize_columns(df, col_map, date_fmt)
+
+
+_READERS = {
+ "csv": _read_csv,
+ "parquet": _read_parquet,
+ "duckdb": _read_duckdb,
+}
+
+
+@register
+class DataLoader:
+ """Config-driven local data loader for CSV, Parquet, and DuckDB."""
+
+ name = "local"
+ markets = {"us_equity", "a_share", "hk_equity", "crypto", "futures", "forex", "macro", "fund"}
+ requires_auth = False
+
+ def __init__(self) -> None:
+ self._config: dict[str, Any] | None = None
+ self._source_by_symbol: dict[str, dict[str, Any]] = {}
+
+ def is_available(self) -> bool:
+ """Return True when the YAML config file exists and has sources."""
+ config = _load_config()
+ if config is None:
+ return False
+ sources = config.get("sources")
+ return isinstance(sources, list) and len(sources) > 0
+
+ def _ensure_config(self) -> None:
+ if self._config is not None:
+ return
+ self._config = _load_config() or {}
+ self._source_by_symbol = {}
+ for entry in self._config.get("sources", []):
+ symbol = entry.get("symbol", "").strip()
+ if symbol:
+ self._source_by_symbol[symbol] = entry
+
+ def fetch(
+ self,
+ codes: List[str],
+ start_date: str,
+ end_date: str,
+ *,
+ interval: str = "1D",
+ fields: Optional[List[str]] = None,
+ ) -> Dict[str, pd.DataFrame]:
+ """Fetch OHLCV data for each code from configured local sources.
+
+ Args:
+ codes: Symbol list, optionally prefixed with ``local:``.
+ start_date: YYYY-MM-DD.
+ end_date: YYYY-MM-DD.
+ interval: Bar size (all intervals supported if data contains them).
+ fields: Ignored.
+
+ Returns:
+ Mapping clean_symbol -> OHLCV DataFrame.
+ """
+ validate_date_range(start_date, end_date)
+ self._ensure_config()
+
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ clean = code.split(":", 1)[1] if code.startswith("local:") else code
+ entry = self._source_by_symbol.get(clean)
+ if entry is None:
+ logger.warning("local loader: no config entry for symbol %s", clean)
+ continue
+ try:
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=clean,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda c=clean: self._fetch_one(c, start_date, end_date),
+ )
+ if df is not None and not df.empty:
+ result[clean] = df
+ except Exception as exc:
+ logger.warning("local loader failed for %s: %s", clean, exc)
+
+ return result
+
+ def _fetch_one(
+ self, symbol: str, start_date: str, end_date: str,
+ ) -> pd.DataFrame | None:
+ entry = self._source_by_symbol.get(symbol)
+ if entry is None:
+ return None
+
+ src_type: str = entry.get("type", "csv").strip().lower()
+ reader = _READERS.get(src_type)
+ if reader is None:
+ logger.warning("local loader: unsupported type %r for symbol %s", src_type, symbol)
+ return None
+
+ col_map: dict[str, str] = dict(_DEFAULT_COLUMNS)
+ user_cols = entry.get("columns")
+ if isinstance(user_cols, dict):
+ for k, v in user_cols.items():
+ if isinstance(v, str):
+ col_map[k] = v
+
+ date_fmt: str | None = None
+ user_fmt = entry.get("date_format")
+ if isinstance(user_fmt, str) and user_fmt.strip():
+ date_fmt = user_fmt.strip()
+
+ if src_type == "duckdb":
+ db_path = str(Path(entry.get("db_path", "")).expanduser())
+ query = entry.get("query", "").strip()
+ if not db_path or not query:
+ logger.warning(
+ "local loader: missing db_path or query for duckdb symbol %s", symbol
+ )
+ return None
+ df = _read_duckdb(db_path, query, col_map, date_fmt)
+ else:
+ path = entry.get("path", "").strip()
+ if not path:
+ logger.warning("local loader: missing path for symbol %s", symbol)
+ return None
+ expanded = str(Path(path).expanduser())
+ df = reader(expanded, col_map, date_fmt)
+
+ if df is None:
+ return None
+
+ start = pd.Timestamp(start_date)
+ end = pd.Timestamp(end_date)
+ df = df[(df.index >= start) & (df.index <= end)]
+ if df.empty:
+ return None
+ return df
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 5bd263f1a..eac8dd26e 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -40,6 +40,7 @@ VALID_SOURCES: set[str] = {
"mootdx",
"ccxt",
"futu",
+ "local",
"auto",
}
@@ -75,6 +76,7 @@ def _ensure_registered() -> None:
"backtest.loaders.mootdx_loader",
"backtest.loaders.ccxt_loader",
"backtest.loaders.futu",
+ "backtest.loaders.local_loader",
]
import importlib
for mod in _loader_modules:
@@ -89,14 +91,14 @@ def _ensure_registered() -> None:
# ---------------------------------------------------------------------------
FALLBACK_CHAINS: dict[str, list[str]] = {
- "a_share": ["tushare", "mootdx", "baostock", "tencent", "akshare"],
- "us_equity": ["yfinance", "akshare"],
- "hk_equity": ["yfinance", "futu", "akshare"],
- "crypto": ["okx", "ccxt", "yfinance"],
- "futures": ["tushare", "akshare"],
- "fund": ["tushare", "akshare"],
- "macro": ["akshare", "tushare"],
- "forex": ["akshare", "yfinance"],
+ "a_share": ["tushare", "mootdx", "baostock", "tencent", "akshare", "local"],
+ "us_equity": ["yfinance", "akshare", "local"],
+ "hk_equity": ["yfinance", "futu", "akshare", "local"],
+ "crypto": ["okx", "ccxt", "yfinance", "local"],
+ "futures": ["tushare", "akshare", "local"],
+ "fund": ["tushare", "akshare", "local"],
+ "macro": ["akshare", "tushare", "local"],
+ "forex": ["akshare", "yfinance", "local"],
}
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index ecfd42e02..9ecd66964 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)
DEFAULT_MAX_ROWS = 250
_SOURCE_PATTERNS = [
+ (re.compile(r"^local:", re.I), "local"),
(re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tushare"),
(re.compile(r"^[A-Z]+\.US$", re.I), "yfinance"),
(re.compile(r"^\d{3,5}\.HK$", re.I), "yfinance"),
diff --git a/agent/tests/test_local_loader.py b/agent/tests/test_local_loader.py
new file mode 100644
index 000000000..61dc4cc86
--- /dev/null
+++ b/agent/tests/test_local_loader.py
@@ -0,0 +1,95 @@
+"""Tests for the config-driven local data loader."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+import backtest.loaders.local_loader as local_loader
+
+
+def _configure(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sources: list[dict]) -> None:
+ """Point the local loader at a temp config file."""
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.safe_dump({"sources": sources}), encoding="utf-8")
+ monkeypatch.setattr(local_loader, "_CONFIG_PATH", config_path)
+
+
+def test_local_loader_fetches_csv_with_local_prefix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Symbols prefixed with local: should resolve to the configured symbol."""
+ csv_path = tmp_path / "aapl.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",
+ ]
+ ),
+ encoding="utf-8",
+ )
+ _configure(
+ monkeypatch,
+ tmp_path,
+ [
+ {
+ "symbol": "AAPL.US",
+ "type": "csv",
+ "path": str(csv_path),
+ "columns": {
+ "date": "Date",
+ "open": "Open",
+ "high": "High",
+ "low": "Low",
+ "close": "Close",
+ "volume": "Volume",
+ },
+ }
+ ],
+ )
+
+ frames = local_loader.DataLoader().fetch(
+ ["local:AAPL.US"], "2026-01-01", "2026-01-02"
+ )
+
+ assert set(frames) == {"AAPL.US"}
+ assert list(frames["AAPL.US"]["close"]) == [10.5, 12.5]
+
+
+def test_local_loader_fetches_duckdb_without_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """DuckDB sources use db_path/query and should not require a path field."""
+ duckdb = pytest.importorskip("duckdb")
+ db_path = tmp_path / "market.duckdb"
+ with duckdb.connect(str(db_path)) as conn:
+ conn.execute(
+ """
+ CREATE TABLE prices AS
+ SELECT '2026-01-01' AS date, 10.0 AS open, 11.0 AS high,
+ 9.0 AS low, 10.5 AS close, 1000.0 AS volume
+ UNION ALL
+ SELECT '2026-01-02', 12.0, 13.0, 11.0, 12.5, 1500.0
+ """
+ )
+ _configure(
+ monkeypatch,
+ tmp_path,
+ [
+ {
+ "symbol": "MYINDEX",
+ "type": "duckdb",
+ "db_path": str(db_path),
+ "query": "SELECT * FROM prices",
+ }
+ ],
+ )
+
+ frames = local_loader.DataLoader().fetch(["MYINDEX"], "2026-01-01", "2026-01-02")
+
+ assert set(frames) == {"MYINDEX"}
+ assert list(frames["MYINDEX"]["close"]) == [10.5, 12.5]
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 068252510..836ea6486 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -129,7 +129,6 @@ class TestFallbackChains:
assert "yfinance" in FALLBACK_CHAINS["crypto"]
# OKX and CCXT should still be preferred
assert FALLBACK_CHAINS["crypto"][:2] == ["okx", "ccxt"]
- assert FALLBACK_CHAINS["crypto"][-1] == "yfinance"
# ---------------------------------------------------------------------------