ml-strategy

ml-strategy is a skill for Claude Code, Codex from HKUDS/Vibe-Trading. It costs 30 tokens per session (3,099 once invoked), scanned A, original, MIT.

A machine-learning trading method that learns from past open, high, low, close, and volume data to predict future price direction. Walk-forward training means each prediction uses only data that would have been available at that time.

In plain words
What is it for?
Use it to build indicators such as momentum, volatility, RSI, moving-average ratios, and volume ratios, then produce trading signals from several scikit-learn models.
Why use it?
It helps test predictive models while reducing the risk of accidentally using future information in historical results.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one.

Good fit Use it to build indicators such as momentum, volatility, RSI, moving-average ratios, and volume ratios, then produce trading signals from several scikit-learn models.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/hkuds/vibe-trading/ml-strategy
About the project

Vibe-Trading is a personal trading agent that gives an AI system tools for market analysis, algorithmic trading, backtesting, and related workflows. It is for users who want an agent to research and evaluate trading strategies or manage simulated and other trading activities. The catalogue contains skills that expose these trading capabilities to compatible agents.

HKUDS/Vibe-Trading · 36,686 stars · on GitHub · vibetrading.wiki

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add HKUDS/Vibe-Trading --skill ml-strategy
Clone the repo
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for ml-strategy

README.md
[![agentmods](https://agentmods.dev/badge/skills/hkuds/vibe-trading/ml-strategy/github.svg)](https://agentmods.dev/skills/hkuds/vibe-trading/ml-strategy)
Your own site
<a href="https://agentmods.dev/skills/hkuds/vibe-trading/ml-strategy"><img src="https://agentmods.dev/badge/skills/hkuds/vibe-trading/ml-strategy/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for ml-strategy

Your own site · 80×15
<a href="https://agentmods.dev/skills/hkuds/vibe-trading/ml-strategy"><img src="https://agentmods.dev/badge/skills/hkuds/vibe-trading/ml-strategy.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 30 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,099 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. ✓ AI security review Fable 5.1 · 6 Sept 2026 📄 Read the review Third-party audits
  • Snyk pass 7 Sept 2026
  • NVIDIA SkillSpector pass 7 Sept 2026
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00030 $0.03099
Opus 5.5 $0.00012 $0.01240
Sonnet 5.5 $0.00006 $0.00620
Haiku 4.5 $0.00003 $0.00310

Measured 1mo ago against content hash dab36e929cef, method: parsed. Prices are Anthropic first-party input rates as of 2026-10-07, from the pricing page.

Security

Grade A, and why

ml-strategy scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 1mo ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

Origin

Copies of this mod

1 near-identical copy found in the catalogue:

agent/src/skills/ml-strategy/SKILL.md · 291 lines

How it starts

The opening of the file, as written. The whole thing — 291 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Machine-Learning Predictive Strategy

Purpose

Use sklearn machine-learning models (RandomForest / GradientBoosting / Ridge) to predict the direction of future returns and generate trading signals. Walk-forward training is used to avoid future data leakage, and feature engineering extracts useful factors from OHLCV data.

Signal Logic

  1. Validate input: check OHLCV columns, minimum row count, NaN ratio — skip symbols that fail
  2. Feature engineering: build multi-dimensional factors from raw OHLCV data (momentum, volatility, RSI, moving-average ratios, volume ratio, and more). All features are sanitized (inf removed, division-by-zero guarded)
  3. Label construction: future N-day return > 0 is the positive class (1), < 0 is the negative class (0)
  4. Walk-forward training: use an expanding or sliding window, train on historical data only, and roll forward day by day for prediction
  5. Signal generation: map predict_proba[:, 1] to [-1.0, 1.0], or use discrete signals from predict in {-1, 0, 1}. Output is guaranteed clean (no NaN, clipped to range)

Complete SignalEngine Example

This is the recommended full pipeline. Copy and customise — safety is built in.

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler


def validate_data(df: pd.DataFrame, min_rows: int = 300) -> bool:
    """Check that OHLCV data meets minimum quality for ML training.

    Args:
        df: DataFrame with DatetimeIndex.
        min_rows: Minimum number of rows required.

    Returns:
        True if data is usable.
    """
    required = {"open", "high", "low", "close", "volume"}
    if not required.issubset(df.columns):
        return False
    if len(df) < min_rows:
        return False
    if df["close"].isnull().mean() > 0.2:
        return False
    return True


def build_features(df: pd.DataFrame) -> pd.DataFrame:
    """Build a machine-learning feature matrix from OHLCV data.

    All features are guarded against division-by-zero and sanitized
    (inf replaced with NaN) so downstream code never sees inf values.

    Args:
        df: DataFrame containing open, high, low, close, and volume columns.

    Returns:
        DataFrame with feature columns prefixed by 'f_'.
    """
    c = df["close"]
    v = df["volume"]
    ret = c.pct_change(fill_method=None)

    features = pd.DataFrame(index=df.index)
    features["f_ret_5d"] = c.pct_change(5, fill_method=None)
    features["f_ret_20d"] = c.pct_change(20, fill_method=None)
    features["f_vol_20d"] = ret.rolling(20).std()
    features["f_ma_ratio"] = c / c.rolling(20).mean()
    features["f_volume_ratio"] = v / v.rolling(20).mean()

    # RSI(14) — guard: loss=0 in zero-volatility periods produces inf
    delta = c.diff()
    gain = delta.clip(lower=0).rolling(14).mean()
    loss = (-delta.clip(upper=0)).rolling(14).mean()
    rs = gain / loss.replace(0, np.nan)
    features["f_rsi_14"] = 100 - (100 / (1 + rs))

    # Bollinger Band position — guard: bb_upper == bb_lower when std=0
    ma20 = c.rolling(20).mean()
    std20 = c.rolling(20).std()
    bb_upper = ma20 + 2 * std20
    bb_lower = ma20 - 2 * std20
    bb_range = (bb_upper - bb_lower).replace(0, np.nan)
    features["f_bb_position"] = (c - bb_lower) / bb_range

    # Intraday features
    features["f_high_low_ratio"] = (df["high"] - df["low"]) / c
    features["f_close_open_ratio"] = (c - df["open"]) / df["open"]
    features["f_skew_20d"] = ret.rolling(20).skew()

    # Sanitize: replace all inf with NaN (NaN handled by walk-forward)
    features = features.replace([np.inf, -np.inf], np.nan)
    return features


def walk_forward_predict(
    features: pd.DataFrame,
    labels: pd.Series,
    min_train_size: int = 252,
    retrain_freq: int = 20,
    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.

    Args:
        features: Feature matrix aligned with labels by row index.
        labels: Binary labels (0/1), representing the direction of future N-day returns.
        min_train_size: Minimum training-set size in trading days.
        retrain_freq: Retrain the model every N days.
        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.
    """
    predictions = pd.Series(0.0, index=features.index)
    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:
            # 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))
            X_train = X_train[valid]
            y_train = y_train[valid]

            # Too few rows, or a single class (a sustained one-directional
            # trend, which crashes fit()/predict_proba() on every model type
            # below): skip the retrain. The previous model keeps serving; before
            # the first model there is no prediction.
            if len(X_train) >= 50 and len(np.unique(y_train)) >= 2:
                # Standardization: fit only on training set
                scaler = StandardScaler()
                X_train = scaler.fit_transform(X_train)

                # Build the model
                if model_type == "random_forest":
                    model = RandomForestClassifier(
                        n_estimators=100, max_depth=5, random_state=42,
                    )
                elif model_type == "gradient_boosting":
                    model = GradientBoostingClassifier(
                        n_estimators=100, max_depth=3, learning_rate=0.05,
                        random_state=42,
                    )
                elif model_type == "ridge":
                    model = LogisticRegression(penalty="l2", C=1.0, random_state=42)
                else:
                    raise ValueError(f"Unsupported model_type: {model_type}")

                model.fit(X_train, y_train)

        if model is None:
            continue

        # Predict today
        X_today = features.iloc[i : i + 1].values
        if np.isnan(X_today).any():
            predictions.iloc[i] = 0.0
            continue

        X_today = scaler.transform(X_today)

        if hasattr(model, "predict_proba"):
            prob = model.predict_proba(X_today)[0, 1]
            predictions.iloc[i] = prob * 2 - 1  # [0,1] -> [-1,1]
        else:
            predictions.iloc[i] = float(model.predict(X_today)[0])

    # Output contract: no NaN, clipped to [-1, 1]
    predictions = predictions.fillna(0.0).clip(-1.0, 1.0)
    return predictions


class SignalEngine:
    """Complete ML strategy with built-in data validation and safety."""

    def generate(self, data_map: dict) -> dict:
        """Generate signals for each symbol.

        Args:
            data_map: code -> OHLCV DataFrame.

        Returns:
            code -> signal Series in [-1.0, 1.0].
        """
        signals = {}
        for code, df in data_map.items():
            if not validate_data(df):
                print(f"[WARN] {code}: data quality insufficient, skipping")
                continue

            features = build_features(df)
            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

Read the full file on GitHub · 291 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 1mo ago Changed · +5 lines dab36e929cef
  2. 1mo ago Changed · +19 lines eaf300c2ac19
  3. 1mo ago First seen · 267 lines · 30 tokens per session scan A 5138bc8d762a

Subscribe to this mod's changes

ml-strategy is a skill published in the GitHub repository HKUDS/Vibe-Trading (36,686 stars, last pushed today), licensed MIT. It adds 30 tokens to every session and 3,099 once invoked, about $0.0001 per session on Opus 5.5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

jccb

A code-search skill for finding information in framework source code using retrieval and grep, a command-line text search tool. It is used when the agent needs to inspect backend framework code.

cloudQuant/backtrader · 26 tokens

hyperliquid

Use when backtesting, deploying, checking funding readiness, or debugging a Hyperliquid strategy through Superior Trade Unified API — writing Freqtrade configs and strategy code, running sweeps, checking managed-wallet balances, trading HIP-3 perps, or diagnosing a deployment that will not start or trade.

Superior-Trade/superior-skills · 64 tokens

polymarket

Use when the user wants to trade, research, or backtest Polymarket prediction markets through Superior Trade — finding markets by slug or event URL, placing a single immediate market order, writing NautilusTrader strategies, running filled-data backtests, funding pUSD, or deploying and monitoring a live Polymarket…

Superior-Trade/superior-skills · 68 tokens

web-documents

Use before reading websites, reports, filings, spreadsheets, CSV files, PDFs, Word files, or ZIP archives from the web, and before doing math on the rows they contain.

Lumiwealth/lumibot · 40 tokens

options-trading

Use before researching, selecting, opening, modifying, or closing any option position, including single-leg options, vertical spreads, iron condors, butterflies, straddles, strangles, calendars, and other multi-leg structures. Also use when a broad trading mandate leads you to consider options even if the user did not…

Lumiwealth/lumibot · 71 tokens

backtesting

Use when running, interpreting, or designing backtests on Superior Trade — anything about backtest windows, trade-count thresholds, exit-reason mix, parameter sweeps, walk-forward validation, zero-trade diagnosis, compute-cost estimation, or "is this backtest result trustworthy?". Pair with the relevant strategy…

Superior-Trade/superior-skills · 73 tokens