Chuyển đến nội dung
Skillpedia
Học máy37k · #7533

ml-strategy

Skill này làm gì

Skill này huấn luyện các mô hình học máy đơn giản để dự đoán giá sẽ tăng hay giảm. Skill dành cho nhà phân tích muốn tín hiệu giao dịch dựa trên dữ liệu.

Khi nào nên dùng

  • ✓Khi bạn muốn kiểm thử một mô hình học máy để dự đoán lợi nhuận cổ phiếu hoặc crypto.
  • ✓Khi bạn cần một tín hiệu được xây từ các đặc trưng như động lượng, biến động và khối lượng.
  • ✓Khi bạn muốn kiểm tra một mô hình mà không để nó nhìn thấy dữ liệu tương lai.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/ml-strategy/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Xây dựng một mô hình học máy dự đoán liệu cổ phiếu này có tăng vào tuần tới không.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill tạo các đặc trưng như động lượng và RSI từ dữ liệu giá và khối lượng. Sau đó nó chỉ huấn luyện mô hình trên các cửa sổ quá khứ và tiến dần theo từng ngày, nên không bao giờ nhìn vào tương lai.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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
Câu hỏi thường gặp

Skill dùng những mô hình nào?

Nó dùng các mô hình scikit-learn như RandomForest, GradientBoosting và Ridge.

Huấn luyện tiến dần (walk-forward) là gì?

Là huấn luyện chỉ trên dữ liệu quá khứ và tiến dần theo thời gian, nên mỗi lần kiểm thử dùng dữ liệu mô hình chưa từng thấy.

Điều này có đảm bảo kết quả tốt không?

Không. Dự đoán luôn có độ không chắc chắn, nên hãy kiểm tra kết quả kỹ trước khi tin vào bất kỳ tín hiệu nào.

Chi tiết

Mô tả gốc của tác giả

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

repo: HKUDS/Vibe-Trading

Độ phổ biến

Sao GitHub
37k
Vị trí xếp hạng
#7533
Giấy phép
MIT
Cập nhật
1/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự