Aller au contenu
Skillpedia
Machine learning37k · #7533

ml-strategy

Ce qu’il fait

Cette compétence entraîne des modèles d'apprentissage automatique simples pour prédire si les cours vont monter ou baisser. Elle s'adresse aux analystes qui veulent des signaux de trading fondés sur les données.

Quand l’utiliser

  • ✓Quand vous voulez tester un modèle d'apprentissage automatique pour prédire les rendements d'une action ou d'une crypto.
  • ✓Quand vous avez besoin d'un signal construit à partir de caractéristiques de momentum, de volatilité et de volume.
  • ✓Quand vous voulez vérifier un modèle sans le laisser regarder les données futures.

Lien du skill

https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/ml-strategy/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/ml-strategy/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Construis un modèle d'apprentissage automatique qui prédit si cette action va monter la semaine prochaine.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

Elle crée des caractéristiques comme le momentum et le RSI à partir des données de prix et de volume. Elle entraîne ensuite un modèle uniquement sur des fenêtres passées et avance jour après jour, pour ne jamais regarder vers le futur.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis 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_bo
Questions fréquentes

Quels modèles utilise-t-elle ?

Elle utilise des modèles scikit-learn comme RandomForest, GradientBoosting et Ridge.

Qu'est-ce que l'entraînement en marche avant ?

C'est un entraînement qui n'utilise que des données passées et avance dans le temps, pour que chaque test porte sur des données que le modèle n'a pas vues.

Cela garantit-il de bons résultats ?

Non. Les prédictions restent incertaines, il faut donc examiner attentivement les résultats avant de faire confiance à un signal.

Détails

Description originale de l’auteur

Machine-learning predictive strategy based on sklearn walk-forward training, feature engineering, and signal generation. Suitable for any OHLCV data.

repo: HKUDS/Vibe-Trading

Popularité

Étoiles GitHub
37k
Position au classement
#7533
Licence
MIT
Mis à jour
01/11/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires