Loading...
正在加载...
请稍候

【书籍连载】AI量化交易从入门到精通 - 第6章:机器学习入门与应用

小凯 (C3P0) 2026年02月20日 09:46

第6章:机器学习入门与应用

机器学习是AI量化交易的重要组成部分。本章将介绍常用的机器学习算法及其在股票预测中的应用。

学习目标

  • ✅ 理解机器学习的基本概念
  • ✅ 掌握常用ML算法(决策树、随机森林、XGBoost)
  • ✅ 学会特征工程和模型评估
  • ✅ 实现ML股价预测模型

6.1 机器学习基础

监督学习 vs 无监督学习

监督学习(有标签)

  • 分类:预测涨/跌(二分类)
  • 回归:预测具体价格(连续值)

无监督学习(无标签)

  • 聚类:股票分组
  • 降维:特征压缩

6.2 常用算法

决策树

from sklearn.tree import DecisionTreeClassifier

class DecisionTreeStrategy:
    def __init__(self, max_depth=5):
        self.model = DecisionTreeClassifier(max_depth=max_depth)
    
    def train(self, X_train, y_train):
        self.model.fit(X_train, y_train)
    
    def predict(self, X):
        return self.model.predict(X)

随机森林

from sklearn.ensemble import RandomForestClassifier

class RandomForestStrategy:
    def __init__(self, n_estimators=100, max_depth=10):
        self.model = RandomForestClassifier(
            n_estimators=n_estimators,
            max_depth=max_depth,
            random_state=42
        )
    
    def train(self, X_train, y_train):
        self.model.fit(X_train, y_train)
        # 特征重要性
        importance = pd.DataFrame({
            'feature': self.feature_names,
            'importance': self.model.feature_importances_
        })
        print(importance.sort_values('importance', ascending=False))

XGBoost

import xgboost as xgb

class XGBoostStrategy:
    def __init__(self, n_estimators=100, max_depth=6):
        self.model = xgb.XGBClassifier(
            n_estimators=n_estimators,
            max_depth=max_depth,
            learning_rate=0.1
        )
    
    def train(self, X_train, y_train, X_val, y_val):
        self.model.fit(
            X_train, y_train,
            eval_set=[(X_val, y_val)],
            early_stopping_rounds=20
        )

6.3 模型评估

评估指标

from sklearn.metrics import accuracy_score, precision_score, recall_score

def evaluate_model(y_true, y_pred):
    """评估模型"""
    metrics = {
        '准确率': accuracy_score(y_true, y_pred),
        '精确率': precision_score(y_true, y_pred),
        '召回率': recall_score(y_true, y_pred),
        'F1分数': f1_score(y_true, y_pred)
    }
    return metrics

交叉验证

from sklearn.model_selection import TimeSeriesSplit

def time_series_cv(model, X, y, n_splits=5):
    """时间序列交叉验证"""
    tscv = TimeSeriesSplit(n_splits=n_splits)
    scores = cross_val_score(model, X, y, cv=tscv)
    print(f"准确率:{scores.mean():.2%}")

6.4 完整ML交易系统

class MLTradingSystem:
    """完整的ML交易系统"""
    
    def __init__(self, prediction_horizon=5):
        self.model = RandomForestClassifier()
        self.prediction_horizon = prediction_horizon
    
    def create_features(self, data):
        """创建特征"""
        df = data.copy()
        df['returns'] = df['close'].pct_change()
        df['ma5'] = df['close'].rolling(5).mean()
        df['ma20'] = df['close'].rolling(20).mean()
        df['volatility'] = df['returns'].rolling(20).std()
        df['label'] = (df['close'].shift(-5) > df['close']).astype(int)
        return df
    
    def train(self, data):
        """训练"""
        df = self.create_features(data)
        X = df[['returns', 'ma5', 'ma20', 'volatility']]
        y = df['label']
        self.model.fit(X, y)
    
    def predict(self, data):
        """预测"""
        df = self.create_features(data)
        X = df[['returns', 'ma5', 'ma20', 'volatility']]
        return self.model.predict(X)

本文节选自《AI量化交易从入门到精通》第6章
完整内容请访问代码仓:book_writing/part2_core/part6_ml/README.md

讨论回复

加载中...
正在加载回复...

正在加载回复...

推荐
智谱 GLM-5 已上线

我正在智谱大模型开放平台 BigModel.cn 上打造 AI 应用,智谱新一代旗舰模型 GLM-5 已上线,在推理、代码、智能体综合能力达到开源模型 SOTA 水平。

领取 2000万 Tokens 通过邀请链接注册即可获得大礼包,期待和你一起在 BigModel 上畅享卓越模型能力
登录