Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(ml-strategy): purge unavailable future labels

Lanre Shittucc1c66396cc1
diff --git a/agent/src/skills/ml-strategy/SKILL.md b/agent/src/skills/ml-strategy/SKILL.md
index c0b53fada..5733098fb 100644
--- a/agent/src/skills/ml-strategy/SKILL.md
+++ b/agent/src/skills/ml-strategy/SKILL.md
@@ -105,6 +105,7 @@ def walk_forward_predict(
model_type: str = "random_forest",
window_type: str = "expanding",
sliding_size: int = 504,
+ prediction_horizon: int = 5,
) -> pd.Series:
"""Walk-forward training and prediction to avoid future data leakage.
@@ -116,6 +117,7 @@ def walk_forward_predict(
model_type: One of "random_forest" / "gradient_boosting" / "ridge".
window_type: "expanding" uses all history; "sliding" uses a fixed lookback.
sliding_size: Lookback window size when window_type is "sliding".
+ prediction_horizon: Number of bars each target label looks ahead.
Returns:
Predicted signal series with range [-1.0, 1.0], no NaN values.
@@ -124,12 +126,21 @@ def walk_forward_predict(
model = None
scaler = None
+ if prediction_horizon < 1:
+ raise ValueError("prediction_horizon must be >= 1")
+
for i in range(min_train_size, len(features)):
# Retrain every retrain_freq days
if model is None or (i - min_train_size) % retrain_freq == 0:
- start = max(0, i - sliding_size) if window_type == "sliding" else 0
- X_train = features.iloc[start:i].values
- y_train = labels.iloc[start:i].values
+ # A label at row t is observable only once t + horizon <= i.
+ train_stop = max(0, i - prediction_horizon + 1)
+ start = (
+ max(0, train_stop - sliding_size)
+ if window_type == "sliding"
+ else 0
+ )
+ X_train = features.iloc[start:train_stop].values
+ y_train = labels.iloc[start:train_stop].values
# Drop rows with NaN
valid = ~(np.isnan(X_train).any(axis=1) | np.isnan(y_train))
@@ -198,8 +209,16 @@ class SignalEngine:
continue
features = build_features(df)
- labels = (df["close"].pct_change(5).shift(-5) > 0).astype(int)
- signal = walk_forward_predict(features, labels)
+ prediction_horizon = 5
+ future_returns = (
+ df["close"].shift(-prediction_horizon) / df["close"] - 1
+ )
+ labels = (future_returns > 0).astype(float).where(future_returns.notna())
+ signal = walk_forward_predict(
+ features,
+ labels,
+ prediction_horizon=prediction_horizon,
+ )
signals[code] = signal
return signals
diff --git a/agent/tests/test_ml_strategy_skill.py b/agent/tests/test_ml_strategy_skill.py
new file mode 100644
index 000000000..0c0f0555f
--- /dev/null
+++ b/agent/tests/test_ml_strategy_skill.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+
+SKILL_PATH = Path(__file__).parents[1] / "src" / "skills" / "ml-strategy" / "SKILL.md"
+
+
+def _python_block() -> str:
+ text = SKILL_PATH.read_text(encoding="utf-8")
+ return text.split("```python", 1)[1].split("```", 1)[0]
+
+
+def _load_node(name: str, node_type: type[ast.AST], namespace: dict) -> object:
+ tree = ast.parse(_python_block())
+ node = next(
+ item for item in tree.body if isinstance(item, node_type) and item.name == name
+ )
+ module = ast.Module(body=[node], type_ignores=[])
+ exec(compile(module, str(SKILL_PATH), "exec"), namespace)
+ return namespace[name]
+
+
+class _IdentityScaler:
+ def fit_transform(self, values):
+ return values
+
+ def transform(self, values):
+ return values
+
+
+class _RecordingModel:
+ fits: list[np.ndarray] = []
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def fit(self, values, labels):
+ self.fits.append(values.copy())
+ return self
+
+ def predict_proba(self, values):
+ return np.array([[0.5, 0.5]])
+
+
+def _namespace() -> dict:
+ return {
+ "np": np,
+ "pd": pd,
+ "StandardScaler": _IdentityScaler,
+ "RandomForestClassifier": _RecordingModel,
+ "GradientBoostingClassifier": _RecordingModel,
+ "LogisticRegression": _RecordingModel,
+ }
+
+
+def test_walk_forward_purges_labels_not_observable_at_prediction_time() -> None:
+ walk_forward_predict = _load_node(
+ "walk_forward_predict",
+ ast.FunctionDef,
+ _namespace(),
+ )
+ features = pd.DataFrame({"row": np.arange(70, dtype=float)})
+ labels = pd.Series(np.zeros(70, dtype=float))
+ _RecordingModel.fits.clear()
+
+ walk_forward_predict(features, labels, min_train_size=60, retrain_freq=100)
+
+ assert _RecordingModel.fits[0][-1, 0] == 55.0
+
+
+def test_one_bar_horizon_preserves_existing_training_window() -> None:
+ walk_forward_predict = _load_node(
+ "walk_forward_predict",
+ ast.FunctionDef,
+ _namespace(),
+ )
+ features = pd.DataFrame({"row": np.arange(70, dtype=float)})
+ labels = pd.Series(np.zeros(70, dtype=float))
+ _RecordingModel.fits.clear()
+
+ walk_forward_predict(
+ features,
+ labels,
+ min_train_size=60,
+ retrain_freq=100,
+ prediction_horizon=1,
+ )
+
+ assert _RecordingModel.fits[0][-1, 0] == 59.0
+
+
+def test_signal_engine_preserves_unavailable_future_labels_as_nan() -> None:
+ captured: dict[str, object] = {}
+
+ def fake_predict(features, labels, **kwargs):
+ captured["labels"] = labels.copy()
+ captured["prediction_horizon"] = kwargs.get("prediction_horizon")
+ return pd.Series(0.0, index=features.index)
+
+ namespace = {
+ "np": np,
+ "pd": pd,
+ "validate_data": lambda df: True,
+ "build_features": lambda df: pd.DataFrame(
+ {"x": np.arange(len(df))}, index=df.index
+ ),
+ "walk_forward_predict": fake_predict,
+ }
+ signal_engine = _load_node("SignalEngine", ast.ClassDef, namespace)
+
+ frame = pd.DataFrame({"close": np.arange(1, 11, dtype=float)})
+ signal_engine().generate({"TEST": frame})
+
+ labels = captured["labels"]
+ assert captured["prediction_horizon"] == 5
+ assert labels.iloc[:5].eq(1.0).all()
+ assert labels.iloc[-5:].isna().all()