#!/usr/bin/env python3
"""
验证 cum_return_idx 和 cum_return_etf 是否独立计算
"""

import sys
from pathlib import Path
import json

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 读取已有的 backtest_detail_v2.json
detail_path = project_root / 'framework_v2' / 'results' / 'backtest_detail_v2.json'

if not detail_path.exists():
    print(f"❌ 文件不存在: {detail_path}")
    print("请先运行: python framework_v2/scripts/export_backtest_detail.py")
    sys.exit(1)

print("=" * 80)
print("   验证指数和 ETF 累计收益是否独立计算")
print("=" * 80)

with open(detail_path, 'r') as f:
    data = json.load(f)

# 检查每日数据
days = data['days']
print(f"\n总天数: {len(days)}")

# 统计有差异的天数
diff_count = 0
same_count = 0
total_checked = 0

for day in days[:100]:  # 检查前 100 天
    date = day['date']
    assets = day.get('assets', {})
    
    for code, asset in assets.items():
        if not asset.get('is_held'):
            continue
        
        cum_etf = asset.get('cum_return_etf')
        cum_idx = asset.get('cum_return_idx')
        
        if cum_etf is not None and cum_idx is not None:
            total_checked += 1
            
            if abs(cum_etf - cum_idx) > 0.0001:  # 差异超过 0.01%
                diff_count += 1
                if diff_count <= 5:  # 只显示前 5 个示例
                    print(f"\n✓ {date} - {code}:")
                    print(f"  ETF 累计收益: {cum_etf:.4f} ({cum_etf*100:.2f}%)")
                    print(f"  指数累计收益: {cum_idx:.4f} ({cum_idx*100:.2f}%)")
                    print(f"  差异: {abs(cum_etf - cum_idx)*100:.2f}%")
            else:
                same_count += 1

print(f"\n{'=' * 80}")
print(f"统计结果（前 100 天，持仓标的）:")
print(f"  总检查次数: {total_checked}")
print(f"  有差异: {diff_count} ({diff_count/total_checked*100:.1f}%)")
print(f"  相同: {same_count} ({same_count/total_checked*100:.1f}%)")

if diff_count > 0:
    print(f"\n✅ 修复成功！指数和 ETF 累计收益已独立计算")
else:
    print(f"\n❌ 仍有问题：指数和 ETF 累计收益完全相同")
    print("   需要重新生成 backtest_detail_v2.json")
