"""简化预测脚本:只判断涨跌方向正确性""" import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import torch import pickle import numpy as np import pandas as pd import pandas_ta as ta from sklearn.preprocessing import StandardScaler from data.fetcher import BinanceDataFetcher from models.dlinear.model import DLinear class SimplePreprocessor: """简化的预处理器:只使用OHLCV + RSI + MACD""" def __init__(self, lookback=168, forecast_horizon=1): self.lookback = lookback self.forecast_horizon = forecast_horizon self.scaler = StandardScaler() self.is_fitted = False def add_features(self, df): """添加RSI和MACD特征""" df = df.copy() df['rsi'] = ta.rsi(df['close'], length=14) macd = ta.macd(df['close']) if macd is not None and not macd.empty: df['macd'] = macd.iloc[:, 0] df['macd_hist'] = macd.iloc[:, 1] df['macd_signal'] = macd.iloc[:, 2] return df def create_labels(self, df): """创建标签:未来1小时的收益率""" df = df.copy() df['future_price'] = df['close'].shift(-self.forecast_horizon) df['future_return'] = (df['future_price'] - df['close']) / df['close'] df['label'] = df['future_return'] return df[:-self.forecast_horizon] def preprocess(self, df, fit=True): """完整预处理流程""" df = self.add_features(df) df = self.create_labels(df) df = df.dropna().reset_index(drop=True) feature_cols = ['open', 'high', 'low', 'close', 'volume', 'rsi', 'macd', 'macd_hist', 'macd_signal'] if fit: scaled = self.scaler.fit_transform(df[feature_cols]) self.is_fitted = True self.feature_columns = feature_cols else: if not self.is_fitted: raise ValueError("Must fit before transform") scaled = self.scaler.transform(df[feature_cols]) X, y = [], [] for i in range(len(scaled) - self.lookback): X.append(scaled[i:i + self.lookback]) y.append(df['label'].iloc[i + self.lookback]) return np.array(X), np.array(y), df def main(): print("="*80) print("2026年BTC涨跌方向预测") print("="*80) # ========== 步骤1: 加载模型 ========== print("\n[1/5] 加载模型...") model_path = './models/checkpoints/dlinear_simple_features/best_model.pt' preprocessor_path = './models/checkpoints/dlinear_simple_features/preprocessor.pkl' device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu') checkpoint = torch.load(model_path, map_location=device, weights_only=False) model = DLinear(checkpoint['config']) model.load_state_dict(checkpoint['model_state_dict']) model = model.to(device) model.eval() with open(preprocessor_path, 'rb') as f: preprocessor = pickle.load(f) print(f"✓ 模型加载成功") print(f"✓ 特征数量: {len(preprocessor.feature_columns)}") # ========== 步骤2: 获取2026年数据 ========== print("\n[2/5] 获取2026年数据...") fetcher = BinanceDataFetcher() try: df_2026 = fetcher.fetch_ohlcv( symbol='BTC', timeframe='1h', start_date='2026-01-01', end_date='2026-12-31', use_cache=False ) except: print("⚠️ 获取最新可用数据...") df_2026 = fetcher.fetch_ohlcv( symbol='BTC', timeframe='1h', start_date='2025-12-01', use_cache=False ) print(f"✓ 数据量: {len(df_2026)} 行") print(f"✓ 时间: {df_2026['timestamp'].min()} 至 {df_2026['timestamp'].max()}") print(f"✓ 价格: ${df_2026['close'].iloc[0]:,.2f} → ${df_2026['close'].iloc[-1]:,.2f}") # ========== 步骤3: 预处理 ========== print("\n[3/5] 预处理数据...") X, y, processed_df = preprocessor.preprocess(df_2026, fit=False) print(f"✓ 预测序列: {len(X)} 个") print(f"✓ 实际涨跌: 上涨{(y>0).sum()}次, 下跌{(y<=0).sum()}次") if len(X) == 0: print("❌ 数据不足") return # ========== 步骤4: 预测 ========== print("\n[4/5] 模型预测...") X_tensor = torch.FloatTensor(X).to(device) with torch.no_grad(): predictions = model(X_tensor).squeeze().cpu().numpy() print(f"✓ 预测完成") print(f"✓ 预测收益率范围: {predictions.min()*100:.4f}% ~ {predictions.max()*100:.4f}%") # ========== 步骤5: 方向判断 ========== print("\n[5/5] 涨跌方向评估...") # 预测方向:正值=上涨,负值=下跌 pred_direction = (predictions > 0).astype(int) # 1=涨, 0=跌 true_direction = (y > 0).astype(int) # 统计 n_pred_up = (pred_direction == 1).sum() n_pred_down = (pred_direction == 0).sum() n_true_up = (true_direction == 1).sum() n_true_down = (true_direction == 0).sum() # 准确率 correct = (pred_direction == true_direction).sum() accuracy = correct / len(predictions) # 混淆矩阵 from sklearn.metrics import confusion_matrix cm = confusion_matrix(true_direction, pred_direction) tn, fp, fn, tp = cm.ravel() print("\n" + "="*80) print("📊 涨跌方向预测结果") print("="*80) print(f"\n预测统计:") print(f" 预测上涨: {n_pred_up} ({n_pred_up/len(predictions)*100:.1f}%)") print(f" 预测下跌: {n_pred_down} ({n_pred_down/len(predictions)*100:.1f}%)") print(f"\n实际统计:") print(f" 实际上涨: {n_true_up} ({n_true_up/len(y)*100:.1f}%)") print(f" 实际下跌: {n_true_down} ({n_true_down/len(y)*100:.1f}%)") print(f"\n准确率:") print(f" 方向正确: {correct}/{len(predictions)} ({accuracy*100:.2f}%)") print(f"\n详细分析:") print(f" ✓ 预测涨且真涨: {tp} ({tp/len(y)*100:.1f}%)") print(f" ✓ 预测跌且真跌: {tn} ({tn/len(y)*100:.1f}%)") print(f" ✗ 预测涨但真跌: {fp} ({fp/len(y)*100:.1f}%)") print(f" ✗ 预测跌但真涨: {fn} ({fn/len(y)*100:.1f}%)") # 预测偏差 bias = n_pred_up - n_true_up print(f"\n预测偏差:") if abs(bias) < len(predictions) * 0.05: print(f" ✅ 预测平衡(偏差{bias}个)") elif bias > 0: print(f" ⚠️ 偏向预测上涨(多预测{bias}次上涨)") else: print(f" ⚠️ 偏向预测下跌(多预测{-bias}次下跌)") # 性能评估 print("\n" + "="*80) print("🎯 性能评估") print("="*80) if accuracy > 0.55: print(f"\n ✅ 方向准确率 {accuracy*100:.2f}% > 55%") print(f" 模型有预测能力,可考虑实盘测试") elif accuracy > 0.52: print(f"\n ⚠️ 方向准确率 {accuracy*100:.2f}% > 52%") print(f" 模型略优于随机,谨慎使用") elif accuracy >= 0.48: print(f"\n ⚠️ 方向准确率 {accuracy*100:.2f}% ≈ 50%") print(f" 接近随机猜测,不建议实盘") else: print(f"\n ❌ 方向准确率 {accuracy*100:.2f}% < 48%") print(f" 低于随机,模型失效") # 预测样本展示 print("\n" + "="*80) print("📋 预测样本展示(前30个)") print("="*80) print(f"\n{'时间':<20} {'预测':<6} {'实际':<6} {'结果':<4} {'预测值':<10}") print("-"*60) for i in range(min(30, len(predictions))): timestamp = processed_df['timestamp'].iloc[i + 168] pred = "上涨" if pred_direction[i] == 1 else "下跌" true = "上涨" if true_direction[i] == 1 else "下跌" result = "✓" if pred_direction[i] == true_direction[i] else "✗" pred_val = predictions[i] print(f"{str(timestamp):<20} {pred:<6} {true:<6} {result:<4} {pred_val*100:>8.4f}%") print("\n" + "="*80) print(f"总结: 在{len(predictions)}次预测中,方向正确{correct}次 ({accuracy*100:.2f}%)") print("="*80) if __name__ == "__main__": main()