import pandas as pd

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

print("正确计算应有的资金流动:")
print("=" * 80)

# 正确的计算逻辑
initial_capital = 1000000
current_capital = initial_capital

print(f"初始资金: {initial_capital:,.2f}元")

for i in range(min(5, len(df))):
    row = df.iloc[i]
    
    # 开仓
    entry_value = row['开仓市值']
    entry_cost = entry_value * 0.0004
    capital_after_entry = current_capital - entry_value - entry_cost
    
    # 平仓
    exit_value = row['平仓市值']
    exit_cost = exit_value * 0.0004
    gross_pnl = (row['卖出价格'] - row['买入价格']) * row['持仓数量']
    net_pnl = gross_pnl - entry_cost - exit_cost
    
    capital_after_exit = capital_after_entry + exit_value - exit_cost
    
    print(f"\n交易#{i+1}:")
    print(f"  交易前资金: {current_capital:,.2f}元")
    print(f"  开仓: 买{entry_value:,.2f}元, 成本{entry_cost:.2f}元")
    print(f"  开仓后资金: {capital_after_entry:,.2f}元")
    print(f"  平仓: 卖{exit_value:,.2f}元, 成本{exit_cost:.2f}元")
    print(f"  毛盈亏: {gross_pnl:,.2f}元")
    print(f"  净盈亏: {net_pnl:,.2f}元")
    print(f"  平仓后资金: {capital_after_exit:,.2f}元")
    print(f"  记录盈亏: {row['盈亏金额']:,.2f}元")
    print(f"  盈亏差异: {net_pnl - row['盈亏金额']:.2f}元")
    
    current_capital = capital_after_exit

print(f"\n验证计算:")
print(f"5笔交易后计算资金: {current_capital:,.2f}元")
print(f"5笔交易后记录资金: {df.iloc[4]['平仓时总资金']:,.2f}元")
print(f"差异: {current_capital - df.iloc[4]['平仓时总资金']:.2f}元")

# 问题是我们的代码在开仓时扣除了成本，但在平仓时又计算了包含开仓成本的盈亏
print(f"\n结论:")
print(f"当前代码逻辑: 开仓时扣除成本，平仓时盈亏计算又包含了成本")
print(f"正确逻辑应该: 开仓时扣除成本，平仓时盈亏只计算价差和卖出成本")