Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(technical_indicators): optional end_date and read_identity with dataset_fingerprint

zeus22938b363e23a5f
diff --git a/agent/src/tools/technical_indicator_tool.py b/agent/src/tools/technical_indicator_tool.py
index c364a12a3..e9f87fb36 100644
--- a/agent/src/tools/technical_indicator_tool.py
+++ b/agent/src/tools/technical_indicator_tool.py
@@ -7,9 +7,10 @@ no new dependencies.
from __future__ import annotations
+import hashlib
import json
import logging
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from typing import Any
import pandas as pd
@@ -141,6 +142,20 @@ def _compute_volume_stats(
return {"latest": latest, "sma_20": sma, "ratio_20": ratio}
+def _dataset_fingerprint(
+ close: pd.Series, volume: pd.Series | None, interval: str
+) -> str:
+ """SHA-256 of the exact bars (date, close, volume) the indicators use."""
+ volumes = volume.tolist() if volume is not None else []
+ volumes += [None] * (len(close) - len(volumes))
+ bars = [
+ [str(label), float(price), None if pd.isna(vol) else float(vol)]
+ for label, price, vol in zip(close.index, close, volumes)
+ ]
+ canonical = json.dumps([interval, bars], separators=(",", ":"))
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+
+
def _compute_sma(close: pd.Series, period: int) -> float | None:
"""Simple moving average over the last *period* bars."""
if len(close) < period:
@@ -229,9 +244,10 @@ class TechnicalIndicatorTool(BaseTool):
"Compute common technical indicators (RSI, MACD, Bollinger Bands, "
"SMA, EMA) plus latest/20-bar volume statistics for a trading symbol "
"(volume.unit is the serving source's declared unit -- lots or shares -- "
- "or null when undeclared). "
- "Uses the project's data loaders "
- "to fetch price history, then computes indicators locally."
+ "or null when undeclared). Returns read_identity with the acquisition "
+ "boundary, serving provenance and a fingerprint of the exact bars used. "
+ "Uses the project's data loaders to fetch price history, then computes "
+ "indicators locally."
)
parameters = {
"type": "object",
@@ -256,6 +272,14 @@ class TechnicalIndicatorTool(BaseTool):
),
"default": _DEFAULT_LOOKBACK,
},
+ "end_date": {
+ "type": "string",
+ "description": (
+ "Optional YYYY-MM-DD acquisition boundary. Omit it for the "
+ "current local date. The boundary pins the requested period; "
+ "read_identity.dataset_fingerprint identifies the exact bars used."
+ ),
+ },
},
"required": ["symbol"],
}
@@ -287,10 +311,22 @@ class TechnicalIndicatorTool(BaseTool):
lookback = _DEFAULT_LOOKBACK
lookback = max(10, min(lookback, _MAX_LOOKBACK))
- # Fetch enough bars to cover the longest indicator window + buffer.
- end_date = datetime.now().strftime("%Y-%m-%d")
+ # One clock read per call, or an explicit zero-padded YYYY-MM-DD boundary.
+ end_date_raw = str(kwargs.get("end_date") or "").strip()
+ if end_date_raw:
+ try:
+ reference_date = date.fromisoformat(end_date_raw)
+ except ValueError:
+ reference_date = None
+ if reference_date is None or reference_date.isoformat() != end_date_raw:
+ return json.dumps(
+ {"ok": False, "error": "end_date must use YYYY-MM-DD"}
+ )
+ else:
+ reference_date = datetime.now().date()
+ end_date = reference_date.isoformat()
days = lookback * _CALENDAR_DAYS_PER_BAR.get(interval, 2)
- start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ start_date = (reference_date - timedelta(days=days)).isoformat()
try:
data = fetch_market_data(
@@ -375,6 +411,15 @@ class TechnicalIndicatorTool(BaseTool):
"interval": interval,
"latest_close": latest_close,
"latest_date": latest_date,
+ "read_identity": {
+ "mode": "pinned_boundary" if end_date_raw else "latest_boundary",
+ "requested_end_date": end_date,
+ "bar_count": len(close),
+ "dataset_fingerprint": _dataset_fingerprint(
+ close, volume, interval
+ ),
+ "provenance": provenance if isinstance(provenance, dict) else None,
+ },
"indicators": indicators,
},
ensure_ascii=False,
diff --git a/agent/tests/test_technical_indicator_tool.py b/agent/tests/test_technical_indicator_tool.py
index 5d3b68b14..050536846 100644
--- a/agent/tests/test_technical_indicator_tool.py
+++ b/agent/tests/test_technical_indicator_tool.py
@@ -331,6 +331,105 @@ class TestTechnicalIndicatorToolIntegration:
# But SMA 20 should be null, SMA 50/200 null — only EMA 20 needs 20 bars, null too
assert result["indicators"]["sma_20"] is None
+ def test_read_identity_pins_requested_boundary_and_provenance(
+ self, monkeypatch, sample_df
+ ):
+ seen = {}
+ provenance = {
+ "AAPL": {
+ "source": "fake",
+ "requested_source": "auto",
+ "fallback_used": False,
+ "volume_unit": "shares",
+ }
+ }
+
+ def _mock_fetch(**kwargs):
+ seen.update(kwargs)
+ return {"AAPL": sample_df, "_provenance": provenance}
+
+ monkeypatch.setattr(
+ "src.tools.technical_indicator_tool.fetch_market_data",
+ _mock_fetch,
+ )
+ result = json.loads(
+ TechnicalIndicatorTool().execute(
+ symbol="AAPL",
+ end_date="2026-09-24",
+ )
+ )
+
+ identity = result["read_identity"]
+ assert result["ok"] is True
+ assert seen["end_date"] == "2026-09-24"
+ assert identity["mode"] == "pinned_boundary"
+ assert identity["requested_end_date"] == "2026-09-24"
+ assert identity["bar_count"] == 200
+ assert identity["provenance"]["source"] == "fake"
+ assert len(identity["dataset_fingerprint"]) == 64
+
+ def test_dataset_fingerprint_is_stable_for_same_observation_and_changes_with_bars(
+ self, monkeypatch, sample_df
+ ):
+ payload = sample_df.copy()
+ provenance = {"AAPL": {"source": "fake", "fallback_used": False}}
+
+ def _mock_fetch(**kwargs):
+ return {"AAPL": payload.copy(), "_provenance": provenance}
+
+ monkeypatch.setattr(
+ "src.tools.technical_indicator_tool.fetch_market_data",
+ _mock_fetch,
+ )
+ tool = TechnicalIndicatorTool()
+ first = json.loads(tool.execute(symbol="AAPL", end_date="2026-09-24"))
+ second = json.loads(tool.execute(symbol="AAPL", end_date="2026-09-24"))
+ assert (
+ first["read_identity"]["dataset_fingerprint"]
+ == second["read_identity"]["dataset_fingerprint"]
+ )
+
+ payload.iloc[-1, payload.columns.get_loc("close")] += 1.0
+ changed = json.loads(tool.execute(symbol="AAPL", end_date="2026-09-24"))
+ assert (
+ changed["read_identity"]["dataset_fingerprint"]
+ != first["read_identity"]["dataset_fingerprint"]
+ )
+
+ @pytest.mark.parametrize(
+ "end_date",
+ [
+ "24-09-2026",
+ "2026-9-4",
+ "2026-09-4",
+ "2026-9-04",
+ ],
+ )
+ def test_invalid_end_date_fails_closed(self, monkeypatch, end_date):
+ called = False
+
+ def _mock_fetch(**kwargs):
+ nonlocal called
+ called = True
+ return {}
+
+ monkeypatch.setattr(
+ "src.tools.technical_indicator_tool.fetch_market_data",
+ _mock_fetch,
+ )
+ result = json.loads(
+ TechnicalIndicatorTool().execute(
+ symbol="AAPL",
+ end_date=end_date,
+ )
+ )
+ assert result["ok"] is False
+ assert "YYYY-MM-DD" in result["error"]
+ assert called is False
+
+ def test_declares_the_end_date_input(self):
+ assert "end_date" in TechnicalIndicatorTool().parameters["properties"]
+
class TestLoaderPayloadShapes:
"""Regression: #1002 — loader payloads arrive as list[dict], not DataFrame."""