import pandas as pd

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

print("资金流动与累计盈亏差异分析:")
print("=" * 80)

# 分析前5笔交易的资金流动
print("前5笔交易的详细资金流动:")
for i in range(min(5, len(df))):
    row = df.iloc[i]
    entry_capital = row['开仓时总资金']
    exit_capital = row['平仓时总资金']
    recorded_pnl = row['盈亏金额']
    
    # 计算成本
    entry_cost = row['开仓市值'] * 0.0004
    exit_cost = row['平仓市值'] * 0.0004
    
    print(f"交易#{i+1}:")
    print(f"  开仓资金: {entry_capital:,.2f}元")
    print(f"  平仓资金: {exit_capital:,.2f}元")
    print(f"  资金变化: {exit_capital - entry_capital:,.2f}元")
    print(f"  记录盈亏: {recorded_pnl:,.2f}元")
    print(f"  开仓成本: {entry_cost:.2f}元")
    print(f"  卖出成本: {exit_cost:.2f}元")
    print(f"  总成本: {entry_cost + exit_cost:.2f}元")
    print()

# 计算累计成本
total_entry_cost = (df['开仓市值'] * 0.0004).sum()
total_exit_cost = (df['平仓市值'] * 0.0004).sum()
total_cost = total_entry_cost + total_exit_cost

print(f"全市场累计成本:")
print(f"累计开仓成本: {total_entry_cost:,.2f}元")
print(f"累计卖出成本: {total_exit_cost:,.2f}元")
print(f"累计总成本: {total_cost:,.2f}元")

print(f"\n盈亏与资金关系:")
print(f"累计盈亏: {df['盈亏金额'].sum():,.2f}元")
print(f"累计成本: {total_cost:,.2f}元")
print(f"实际资金变化: {df.iloc[-1]['平仓时总资金'] - df.iloc[0]['开仓时总资金']:,.2f}元")

# 问题：盈亏应该是扣除成本后的，但资金流动可能没有正确反映
print(f"\n问题分析:")
print(f"如果盈亏计算正确，那么:")
expected_final = df.iloc[0]['开仓时总资金'] + df['盈亏金额'].sum()
print(f"预期最终资金: {expected_final:,.2f}元")
print(f"实际最终资金: {df.iloc[-1]['平仓时总资金']:,.2f}元")
print(f"差异: {expected_final - df.iloc[-1]['平仓时总资金']:,.2f}元")

print(f"\n这个差异就是开仓成本的重复扣除问题！")
print(f"每笔交易的开仓成本在资金流中扣除了，但在盈亏计算中可能又扣除了")