import pandas as pd

df = pd.read_csv('cyb50_optimized_trades_2017-06-01_2026-01-19.csv')

print("盈亏与收益率矛盾分析:")
print("=" * 80)

# 计算累计盈亏
total_pnl = df['盈亏金额'].sum()
print(f"记录的累计盈亏: {total_pnl:,.2f}元")

# 计算资金变化
initial_capital = 1000000
final_capital = df.iloc[-1]['平仓时总资金']
actual_return = final_capital - initial_capital
print(f"实际资金变化: {actual_return:,.2f}元")
print(f"差异: {abs(total_pnl - actual_return):,.2f}元")

# 分析原因
print(f"\n矛盾原因分析:")
print(f"初始资金: {initial_capital:,.2f}元")
print(f"最终资金: {final_capital:,.2f}元")
print(f"理论最终资金: {initial_capital + total_pnl:,.2f}元 (如果盈亏记录准确)")

# 检查每一笔交易的资金连续性
print(f"\n逐笔交易资金分析:")
cash_discrepancies = []
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:
        cash_discrepancies.append({
            'trade': i+1,
            'prev_final': prev_final,
            'curr_initial': curr_initial,
            'diff': abs(prev_final - curr_initial)
        })

if cash_discrepancies:
    print(f"发现{len(cash_discrepancies)}笔资金不连续:")
    for item in cash_discrepancies[:5]:
        print(f"  交易#{item['trade']}: {item['prev_final']:,.2f} -> {item['curr_initial']:,.2f} (差异: {item['diff']:,.2f})")
else:
    print("资金连续性检查通过")

# 检查盈亏计算的准确性
print(f"\n盈亏计算准确性:")
pnl_errors = 0
for i, row in df.iterrows():
    # 计算理论盈亏
    gross_pnl = (row['卖出价格'] - row['买入价格']) * row['持仓数量']
    exit_cost = row['平仓市值'] * 0.0004  # 卖出成本
    theoretical_pnl = gross_pnl - exit_cost
    
    if abs(theoretical_pnl - row['盈亏金额']) > 100:  # 允许100元误差
        pnl_errors += 1
        if pnl_errors <= 3:
            print(f"  交易#{int(row['交易编号'])}: 记录{row['盈亏金额']:.2f} vs 理论{theoretical_pnl:.2f}")

if pnl_errors == 0:
    print("盈亏计算基本准确")
else:
    print(f"发现{pnl_errors}笔盈亏计算可能不准确")

print(f"\n根本原因:")
print(f"累计盈亏记录的是{total_pnl:,.2f}元")
print(f"但实际资金只增长了{actual_return:,.2f}元")
print(f"差异为{abs(total_pnl - actual_return):,.2f}元")
print(f"\n这说明盈亏计算或资金记录存在系统性偏差")