log
2026-07-23 c9a0711438d32f33b65ffa29d8efd7aa37d61bdc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/env python3
"""训练、验证并保存每日主控使用的独立ML因子组合模型。"""
 
import argparse
import json
import os
import pickle
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
 
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error, mean_squared_error
 
 
PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))
 
from code.strategy.ml_factor_combiner import (  # noqa: E402
    DEFAULT_ML_FEATURES,
    MLFactorCombiner,
)
from scripts.enhanced_factor_system import EnhancedFactorSystem  # noqa: E402
 
 
DEFAULT_DATA_PATH = PROJECT_ROOT / 'data' / 'akshare_real_data_fixed.pkl'
DEFAULT_MODEL_PATH = PROJECT_ROOT / 'models' / 'ml_factor_combiner.pkl'
DEFAULT_METADATA_PATH = (
    PROJECT_ROOT / 'models' / 'ml_factor_combiner_metadata.json'
)
DEFAULT_CANDIDATE_MODEL_PATH = (
    PROJECT_ROOT / 'models' / 'ml_factor_combiner_candidate.pkl'
)
DEFAULT_CANDIDATE_METADATA_PATH = (
    PROJECT_ROOT / 'models' / 'ml_factor_combiner_candidate_metadata.json'
)
TARGET_COLUMN = 'return_5d'
TARGET_HORIZON_DAYS = 5
MODEL_NAMES = {
    'gbdt': '梯度提升树',
    'rf': '随机森林',
    'ridge': 'Ridge线性模型',
    'lasso': 'Lasso线性模型',
}
 
 
def _failure(message: str, **details) -> Dict:
    return {
        'success': False,
        'approved': False,
        'message': message,
        **details,
    }
 
 
def _write_json_atomic(path: Path, payload: Dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f'{path.name}.tmp')
    try:
        with open(temporary, 'w', encoding='utf-8') as file:
            json.dump(payload, file, ensure_ascii=False, indent=2)
        os.replace(temporary, path)
    finally:
        if temporary.exists():
            temporary.unlink()
 
 
def load_market_data(data_path: Path = DEFAULT_DATA_PATH) -> pd.DataFrame:
    """读取本地正式行情,不修改原始数据文件。"""
    if not data_path.exists():
        raise FileNotFoundError(f'行情数据不存在: {data_path}')
    with open(data_path, 'rb') as file:
        data = pickle.load(file)
    if not isinstance(data, pd.DataFrame) or data.empty:
        raise ValueError('行情数据为空或格式不正确')
    return data.copy()
 
 
def build_factor_dataset(data: pd.DataFrame) -> pd.DataFrame:
    """在内存中生成模型特征和未来5日标签。"""
    required = {
        'date', 'stock_code', 'close', 'high', 'low', 'volume',
        'amount', 'turnover', 'change_pct',
    }
    missing = sorted(required.difference(data.columns))
    if missing:
        raise ValueError(f"行情数据缺少字段: {', '.join(missing)}")
 
    prepared = data.copy()
    prepared['date'] = pd.to_datetime(prepared['date'], errors='coerce')
    prepared['stock_code'] = (
        prepared['stock_code'].astype(str).str.extract(r'(\d+)', expand=False)
        .fillna('').str.zfill(6)
    )
    prepared = prepared.dropna(subset=['date'])
    prepared = prepared[prepared['stock_code'].str.fullmatch(r'\d{6}')]
    prepared = prepared.sort_values(['stock_code', 'date']).reset_index(drop=True)
 
    system = EnhancedFactorSystem()
    prepared = system.calculate_target_returns(prepared)
    prepared = system.calculate_quality_factors(prepared)
    prepared = system.calculate_growth_factors(prepared)
    prepared = system.calculate_sentiment_factors(prepared)
    prepared = system.calculate_cross_sectional_factors(prepared)
    return prepared
 
 
def _prepare_labeled_rows(factor_data: pd.DataFrame) -> pd.DataFrame:
    missing = sorted(set(DEFAULT_ML_FEATURES).difference(factor_data.columns))
    if missing:
        raise ValueError(f"因子计算结果缺少字段: {', '.join(missing)}")
 
    columns = ['date', 'stock_code', TARGET_COLUMN, *DEFAULT_ML_FEATURES]
    labeled = factor_data[columns].copy()
    labeled[TARGET_COLUMN] = pd.to_numeric(
        labeled[TARGET_COLUMN],
        errors='coerce',
    )
    labeled[DEFAULT_ML_FEATURES] = (
        labeled[DEFAULT_ML_FEATURES]
        .apply(pd.to_numeric, errors='coerce')
        .replace([np.inf, -np.inf], np.nan)
    )
    minimum_available = max(3, int(len(DEFAULT_ML_FEATURES) * 0.6))
    feature_coverage = labeled[DEFAULT_ML_FEATURES].notna().sum(axis=1)
    labeled = labeled[
        labeled[TARGET_COLUMN].notna()
        & labeled['date'].notna()
        & (feature_coverage >= minimum_available)
    ]
    return labeled.sort_values(['date', 'stock_code']).copy()
 
 
def _temporal_split(
    labeled: pd.DataFrame,
    validation_ratio: float = 0.2,
    purge_days: int = TARGET_HORIZON_DAYS,
):
    dates = list(pd.Index(labeled['date'].dropna().unique()).sort_values())
    if len(dates) < 60:
        raise ValueError(f'有效交易日不足: {len(dates)},至少需要60日')
 
    validation_days = max(20, int(np.ceil(len(dates) * validation_ratio)))
    validation_start = len(dates) - validation_days
    training_end = validation_start - purge_days
    if training_end < 30:
        raise ValueError('训练区间不足,无法完成带隔离期的时间切分')
 
    training_dates = dates[:training_end]
    validation_dates = dates[validation_start:]
    training = labeled[labeled['date'].isin(training_dates)].copy()
    validation = labeled[labeled['date'].isin(validation_dates)].copy()
    return training, validation, training_dates, validation_dates
 
 
def _evaluate_holdout(
    model: MLFactorCombiner,
    validation: pd.DataFrame,
    training_target: pd.Series,
) -> Dict:
    predictions = model.predict(validation[DEFAULT_ML_FEATURES])
    evaluated = validation[['date', TARGET_COLUMN]].copy()
    evaluated['prediction'] = predictions
 
    daily_ic = []
    for _, group in evaluated.groupby('date'):
        valid = group[[TARGET_COLUMN, 'prediction']].dropna()
        if len(valid) < 20:
            continue
        ic = valid[TARGET_COLUMN].corr(valid['prediction'], method='spearman')
        if pd.notna(ic):
            daily_ic.append(float(ic))
 
    actual = evaluated[TARGET_COLUMN].to_numpy()
    predicted = evaluated['prediction'].to_numpy()
    baseline = np.full(len(actual), float(training_target.median()))
    ic_mean = float(np.mean(daily_ic)) if daily_ic else None
    ic_std = float(np.std(daily_ic)) if daily_ic else None
    return {
        'validation_samples': int(len(evaluated)),
        'valid_ic_days': int(len(daily_ic)),
        'ic_mean': ic_mean,
        'ic_std': ic_std,
        'ir': (
            float(ic_mean / ic_std)
            if ic_mean is not None and ic_std not in (None, 0.0)
            else None
        ),
        'ic_positive_rate': (
            float(np.mean(np.asarray(daily_ic) > 0))
            if daily_ic
            else None
        ),
        'mse': float(mean_squared_error(actual, predicted)),
        'mae': float(mean_absolute_error(actual, predicted)),
        'baseline_mae': float(mean_absolute_error(actual, baseline)),
    }
 
 
def train_and_save_model(
    model_type: str = 'gbdt',
    data_path: Path = DEFAULT_DATA_PATH,
    model_path: Path = DEFAULT_MODEL_PATH,
    metadata_path: Path = DEFAULT_METADATA_PATH,
    minimum_samples: int = 1000,
) -> Dict:
    """运行无未来泄漏的训练流程,并仅发布通过样本外验证的模型。"""
    if model_type not in MODEL_NAMES:
        return _failure(f'不支持的模型类型: {model_type}')
 
    try:
        print(f'读取本地行情: {data_path}')
        raw_data = load_market_data(Path(data_path))
        print(f'生成训练因子,共 {len(raw_data):,} 条原始记录...')
        factor_data = build_factor_dataset(raw_data)
        labeled = _prepare_labeled_rows(factor_data)
        if len(labeled) < minimum_samples:
            return _failure(
                f'有效训练样本不足: {len(labeled):,},至少需要{minimum_samples:,}条'
            )
 
        training, validation, training_dates, validation_dates = _temporal_split(
            labeled
        )
        if len(training) < 500 or len(validation) < 200:
            return _failure(
                f'时间切分后样本不足: 训练{len(training):,}条,'
                f'验证{len(validation):,}条'
            )
 
        print(
            f'时间切分: 训练 {len(training):,} 条,'
            f'隔离 {TARGET_HORIZON_DAYS} 个交易日,'
            f'验证 {len(validation):,} 条'
        )
        evaluation_model = MLFactorCombiner(model_type=model_type)
        fit_result = evaluation_model.fit(
            training[DEFAULT_ML_FEATURES],
            training[TARGET_COLUMN],
            validate=False,
        )
        if not fit_result.get('success'):
            return _failure(
                f"训练失败: {fit_result.get('message', '未知错误')}"
            )
 
        metrics = _evaluate_holdout(
            evaluation_model,
            validation,
            training[TARGET_COLUMN],
        )
        approved = (
            metrics['valid_ic_days'] >= 10
            and metrics['ic_mean'] is not None
            and metrics['ic_mean'] > 0
        )
 
        production_model = MLFactorCombiner(model_type=model_type)
        production_fit = production_model.fit(
            labeled[DEFAULT_ML_FEATURES],
            labeled[TARGET_COLUMN],
            validate=False,
        )
        if not production_fit.get('success'):
            return _failure(
                f"全量重训失败: {production_fit.get('message', '未知错误')}"
            )
 
        metadata = {
            'artifact_version': 1,
            'trained_at': datetime.now().astimezone().isoformat(timespec='seconds'),
            'model_type': model_type,
            'model_name': MODEL_NAMES[model_type],
            'target': TARGET_COLUMN,
            'target_horizon_trading_days': TARGET_HORIZON_DAYS,
            'feature_names': list(DEFAULT_ML_FEATURES),
            'training_samples': int(len(training)),
            'all_labeled_samples': int(len(labeled)),
            'training_start_date': str(pd.Timestamp(training_dates[0]).date()),
            'training_end_date': str(pd.Timestamp(training_dates[-1]).date()),
            'validation_start_date': str(
                pd.Timestamp(validation_dates[0]).date()
            ),
            'validation_end_date': str(
                pd.Timestamp(validation_dates[-1]).date()
            ),
            'purge_trading_days': TARGET_HORIZON_DAYS,
            'validation': metrics,
            'promotion_status': 'approved' if approved else 'rejected',
            'promotion_rule': '有效IC日>=10且样本外IC均值>0',
            'feature_importance': production_model.get_factor_weights(),
        }
        production_model.training_metadata = metadata
 
        candidate_model_path = Path(model_path).with_name(
            'ml_factor_combiner_candidate.pkl'
        )
        candidate_metadata_path = Path(metadata_path).with_name(
            'ml_factor_combiner_candidate_metadata.json'
        )
        production_model.save(candidate_model_path)
        _write_json_atomic(candidate_metadata_path, metadata)
 
        active_model_preserved = False
        if approved:
            production_model.save(Path(model_path))
            _write_json_atomic(Path(metadata_path), metadata)
        else:
            active_model_preserved = Path(model_path).exists()
 
        return {
            'success': True,
            'approved': approved,
            'message': (
                '训练完成并已发布为每日主控模型'
                if approved
                else '训练完成,但样本外验证未通过,未发布为每日主控模型'
            ),
            'model_type': model_type,
            'model_name': MODEL_NAMES[model_type],
            'metrics': metrics,
            'metadata': metadata,
            'model_path': str(model_path) if approved else None,
            'candidate_model_path': str(candidate_model_path),
            'active_model_preserved': active_model_preserved,
        }
    except Exception as error:
        return _failure(f'训练流程失败: {error}')
 
 
def load_model_summary(
    metadata_path: Path = DEFAULT_METADATA_PATH,
) -> Optional[Dict]:
    """优先返回正式模型摘要;没有正式模型时返回最近候选摘要。"""
    metadata_path = Path(metadata_path)
    candidate_path = metadata_path.with_name(
        'ml_factor_combiner_candidate_metadata.json'
    )
    for path, artifact_kind in (
        (metadata_path, 'active'),
        (candidate_path, 'candidate'),
    ):
        if not path.exists():
            continue
        try:
            with open(path, 'r', encoding='utf-8') as file:
                summary = json.load(file)
            summary['artifact_kind'] = artifact_kind
            summary['metadata_path'] = str(path)
            return summary
        except (OSError, ValueError, TypeError):
            continue
    return None
 
 
def main() -> int:
    parser = argparse.ArgumentParser(description='训练ML因子组合模型')
    parser.add_argument(
        '--model',
        choices=sorted(MODEL_NAMES),
        default='gbdt',
        help='模型类型,默认gbdt',
    )
    parser.add_argument('--data', type=Path, default=DEFAULT_DATA_PATH)
    args = parser.parse_args()
 
    result = train_and_save_model(model_type=args.model, data_path=args.data)
    print(result['message'])
    if result.get('metrics'):
        metrics = result['metrics']
        ic = metrics.get('ic_mean')
        print(
            '样本外结果: '
            f"IC={ic:.4f}" if ic is not None else '样本外结果: IC不可用'
        )
        print(
            f"有效IC日={metrics.get('valid_ic_days', 0)}, "
            f"MAE={metrics.get('mae', 0):.6f}"
        )
    return 0 if result.get('approved') else 1
 
 
if __name__ == '__main__':
    raise SystemExit(main())