import pandas as pd

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

print("盈亏计算根本问题分析:")
print("=" * 80)

# 逐步验证第一笔交易
trade1 = df.iloc[0]
print("第一笔交易详细分析:")
print(f"买入价格: {trade1['买入价格']}")
print(f"卖出价格: {trade1['卖出价格']}")
print(f"持仓数量: {trade1['持仓数量']}")
print(f"开仓市值: {trade1['开仓市值']}")
print(f"平仓市值: {trade1['平仓市值']}")

# 计算各种成本
entry_cost = trade1['开仓市值'] * 0.0004  # 开仓成本
exit_cost = trade1['平仓市值'] * 0.0004   # 卖出成本
print(f"开仓成本: {entry_cost:.2f}元")
print(f"卖出成本: {exit_cost:.2f}元")
print(f"总成本: {entry_cost + exit_cost:.2f}元")

# 计算毛盈亏
gross_pnl = (trade1['卖出价格'] - trade1['买入价格']) * trade1['持仓数量']
print(f"毛盈亏: {gross_pnl:.2f}元")

# 计算净盈亏
net_pnl = gross_pnl - entry_cost - exit_cost
print(f"净盈亏: {net_pnl:.2f}元")
print(f"记录盈亏: {trade1['盈亏金额']:.2f}元")
print(f"差异: {abs(net_pnl - trade1['盈亏金额']):.2f}元")

# 资金流动分析
print(f"\n资金流动分析:")
print(f"开仓时总资金: {trade1['开仓时总资金']:.2f}元")
print(f"平仓时总资金: {trade1['平仓时总资金']:.2f}元")
print(f"实际资金变化: {trade1['平仓时总资金'] - trade1['开仓时总资金']:.2f}元")

# 如果第一笔交易应该的资金变化
expected_final = trade1['开仓时总资金'] + net_pnl
print(f"预期平仓资金: {expected_final:.2f}元 (开仓资金 + 净盈亏)")
print(f"实际平仓资金: {trade1['平仓时总资金']:.2f}元")
print(f"资金差异: {expected_final - trade1['平仓时总资金']:.2f}元")

print(f"\n结论:")
if abs(net_pnl - trade1['盈亏金额']) < 200:
    print("第一笔交易盈亏计算基本正确")
else:
    print(f"第一笔交易盈亏计算仍有问题: 记录{trade1['盈亏金额']:.2f} vs 计算{net_pnl:.2f}")

# 检查是否所有交易都有类似问题
total_recorded_pnl = df['盈亏金额'].sum()
total_actual_pnl = 0

for i, row in df.iterrows():
    gross_pnl_i = (row['卖出价格'] - row['买入价格']) * row['持仓数量']
    entry_cost_i = row['开仓市值'] * 0.0004
    exit_cost_i = row['平仓市值'] * 0.0004
    net_pnl_i = gross_pnl_i - entry_cost_i - exit_cost_i
    total_actual_pnl += net_pnl_i

print(f"\n全市场验证:")
print(f"记录累计盈亏: {total_recorded_pnl:.2f}元")
print(f"计算累计盈亏: {total_actual_pnl:.2f}元")
print(f"差异: {abs(total_recorded_pnl - total_actual_pnl):.2f}元")