import pandas as pd

df = pd.read_csv('cyb50_optimized_trades_2017-06-01_2026-01-19.csv')
df['买入日期'] = pd.to_datetime(df['买入日期'])
df['卖出日期'] = pd.to_datetime(df['卖出日期'])

print("Bug修复后验证报告")
print("=" * 80)

# 1. 持仓天数验证
print("\n【1. 持仓天数验证】")
df['计算天数'] = (df['卖出日期'] - df['买入日期']).dt.days + 1
df['天数差异'] = df['计算天数'] - df['持仓天数']

day_errors = df[df['天数差异'] != 0]
print(f"总交易数: {len(df)}")
print(f"天数不准确的交易: {len(day_errors)}")

if len(day_errors) > 0:
    print(f"前5个不准确的交易:")
    for i, row in day_errors.head(5).iterrows():
        print(f"  交易#{int(row['交易编号'])}: 记录{int(row['持仓天数'])}天 vs 实际{int(row['计算天数'])}天 (差异: {int(row['天数差异'])}天)")
else:
    print("✅ 所有持仓天数记录准确！")

# 2. 开仓市值验证
print(f"\n【2. 开仓市值验证】")
df['计算市值'] = df['持仓数量'] * df['买入价格']
df['市值差异'] = df['开仓市值'] - df['计算市值']

position_errors = df[abs(df['市值差异']) > 1]  # 允许1元误差
print(f"市值不准确的交易: {len(position_errors)}")

if len(position_errors) > 0:
    print(f"市值差异统计:")
    print(f"  平均差异: {df['市值差异'].mean():.6f}元")
    print(f"  最大差异: {df['市值差异'].max():.6f}元")
    print(f"  绝对值平均: {df['市值差异'].abs().mean():.6f}元")
else:
    print("✅ 所有开仓市值计算准确！")

# 3. 资金连续性验证
print(f"\n【3. 资金连续性验证】")
capital_issues = 0
for i in range(1, len(df)):
    prev_final = df.iloc[i-1]['平仓时总资金']
    curr_initial = df.iloc[i]['开仓时总资金']
    if abs(prev_final - curr_initial) > 1:  # 允许1元误差
        capital_issues += 1
        if capital_issues <= 3:
            print(f"  资金不连续 #{i}: {prev_final:,.2f} -> {curr_initial:,.2f}")

if capital_issues == 0:
    print("✅ 资金连续性完美！")
else:
    print(f"❌ 仍有{capital_issues}笔资金不连续")

# 4. 净值一致性验证
print(f"\n【4. 净值一致性验证】")
total_pnl = df['盈亏金额'].sum()
initial_capital = 1000000
final_net_value = df.iloc[-1]['平仓时总资金']
net_change = final_net_value - initial_capital

print(f"交易累计盈亏: {total_pnl:,.2f}元")
print(f"净值变化: {net_change:,.2f}元")
print(f"差异: {abs(total_pnl - net_change):,.2f}元")

if abs(total_pnl - net_change) < 1000:  # 允许1000元误差
    print("✅ 净值与交易累计基本一致！")
else:
    print(f"❌ 仍有较大差异")

# 5. 盈亏计算准确性验证
print(f"\n【5. 盈亏计算准确性验证】")
pnl_errors = 0
for i, row in df.iterrows():
    calculated_pnl = (row['卖出价格'] - row['买入价格']) * row['持仓数量']
    calculated_pnl -= row['平仓市值'] * 0.0004  # 扣除交易成本
    if abs(calculated_pnl - row['盈亏金额']) > 10:  # 允许10元误差
        pnl_errors += 1
        if pnl_errors <= 3:
            print(f"  盈亏计算差异 #{int(row['交易编号'])}: 记录{row['盈亏金额']:.2f} vs 计算{calculated_pnl:.2f}")

if pnl_errors == 0:
    print("✅ 所有盈亏计算准确！")
else:
    print(f"❌ 仍有{pnl_errors}笔盈亏计算不准确")

# 总体评分
print(f"\n【总体评分】")
score = 5
if len(day_errors) > 0:
    score -= 1
if len(position_errors) > 0:
    score -= 1
if capital_issues > 0:
    score -= 1
if abs(total_pnl - net_change) > 1000:
    score -= 1
if pnl_errors > 0:
    score -= 1

print(f"修复后评分: {score}/5")

if score == 5:
    print("🎉 所有计算问题已修复！")
else:
    print(f"⚠️ 仍有{5 - score}个问题需要解决")

print("\n" + "=" * 80)