import json import os from pathlib import Path import pandas as pd # 定义结果目录 data_dir = Path('./result') # 指定要分析的文件 target_file = data_dir / 'backtest-result-2025-10-14_13-45-04.json' # 输出文件 export_file = data_dir / 'backtest_trades_with_adjustments.csv' print(f"分析文件: {target_file}") print(f"文件大小: {target_file.stat().st_size / (1024 * 1024):.2f} MB") # 读取文件 try: with open(target_file, 'r', encoding='utf-8') as f: data = json.load(f) print("文件加载成功") except Exception as e: print(f"文件加载失败: {e}") exit(1) # 检查数据结构 if 'strategy' not in data: print("数据中没有 'strategy' 字段") exit(1) strategy_name = 'FreqaiPrimer' if strategy_name not in data['strategy']: print(f"策略 '{strategy_name}' 不在数据中") print(f"可用策略: {list(data['strategy'].keys())}") exit(1) strategy_data = data['strategy'][strategy_name] if 'trades' not in strategy_data: print("策略数据中没有 'trades' 字段") exit(1) trades = strategy_data['trades'] print(f"总交易数: {len(trades)}") # 分析交易中的加仓情况 results = [] trades_with_adjustments = 0 for i, trade in enumerate(trades): # 每1000笔交易显示进度 if (i + 1) % 1000 == 0: print(f"已分析 {i + 1} 笔交易") pair = trade.get('pair', 'Unknown') open_date = trade.get('open_date', 'Unknown') open_rate = trade.get('open_rate', 0) profit_ratio = trade.get('profit_ratio', 0) # 检查是否有orders字段 if 'orders' in trade: orders = trade['orders'] # 筛选入场订单 entry_orders = [order for order in orders if order.get('ft_is_entry', False)] # 按时间戳排序 entry_orders.sort(key=lambda x: x.get('order_filled_timestamp', 0)) # 统计加仓情况 if len(entry_orders) > 1: trades_with_adjustments += 1 base_price = entry_orders[0].get('safe_price', open_rate) for j in range(1, len(entry_orders)): current_order = entry_orders[j] current_price = current_order.get('safe_price', 0) if base_price > 0 and current_price > 0: # 计算降幅百分比 price_drop_percent = ((base_price - current_price) / base_price) * 100 # 保存结果 results.append({ 'trade_index': i, 'pair': pair, 'open_date': open_date, 'adjustment_number': j, 'base_price': base_price, 'current_price': current_price, 'price_drop_percent': price_drop_percent, 'open_rate': open_rate, 'profit_ratio': profit_ratio }) # 输出统计结果 print(f"\n分析完成!") print(f"总交易数: {len(trades)}") print(f"包含加仓的交易数: {trades_with_adjustments}") print(f"总共分析到的加仓次数: {len(results)}") # 如果有结果,保存到CSV文件 if results: df = pd.DataFrame(results) df.to_csv(export_file, index=False) print(f"\n加仓分析结果已保存到: {export_file}") # 显示统计信息 print("\n加仓价格降幅统计:") print(f"平均降幅: {df['price_drop_percent'].mean():.2f}%") print(f"最大降幅: {df['price_drop_percent'].max():.2f}%") print(f"最小降幅: {df['price_drop_percent'].min():.2f}%") # 显示前10条记录 print("\n前10条加仓记录:") print(df.head(10).to_string(index=False)) else: print("\n未发现任何加仓记录") # 创建一个空的CSV文件,包含所有字段 if not export_file.exists(): empty_df = pd.DataFrame(columns=[ 'trade_index', 'pair', 'open_date', 'adjustment_number', 'base_price', 'current_price', 'price_drop_percent', 'open_rate', 'profit_ratio' ]) empty_df.to_csv(export_file, index=False) print(f"已创建空的结果文件: {export_file}")