#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查交易明细准确性
"""

import pandas as pd
import sys
sys.path.insert(0, '/root/.openclaw/workspace/cat-fly')

from trend_report_multi import TrendTrackingStrategy

strategy = TrendTrackingStrategy()
strategy.load_and_merge_data()
strategy.calculate_indicators()
result = strategy.backtest()

print("="*60)
print("📋 交易明细核对")
print("="*60)

print(f"\n总交易记录数: {len(result['trades'])}")
print(f"买入次数: {len([t for t in result['trades'] if t['action'] == 'BUY'])}")
print(f"卖出次数: {len([t for t in result['trades'] if t['action'] == 'SELL'])}")

print("\n" + "-"*60)
print("最近20条交易记录:")
print("-"*60)

for i, trade in enumerate(result['trades'][-20:], 1):
    date_str = trade['date'].strftime('%Y-%m-%d') if hasattr(trade['date'], 'strftime') else str(trade['date'])
    if trade['action'] == 'BUY':
        print(f"{i:2d}. {date_str} BUY  @ {trade['price']:8.2f}  资产: {trade['capital']:12,.0f}")
    else:
        pnl = trade.get('pnl', 0)
        ret = trade.get('return_pct', 0)
        print(f"{i:2d}. {date_str} SELL @ {trade['price']:8.2f}  盈亏: {ret:+6.2f}%  资产: {trade['capital']:12,.0f}")

# 检查是否有同一天买卖的情况
print("\n" + "-"*60)
print("检查异常交易:")
print("-"*60)

for i in range(len(result['trades']) - 1):
    t1 = result['trades'][i]
    t2 = result['trades'][i+1]
    
    if t1['action'] == 'BUY' and t2['action'] == 'SELL':
        hold_days = (t2['date'] - t1['date']).days
        if hold_days < 0:
            print(f"❌ 日期错误: 卖出日期早于买入日期!")
            print(f"   买入: {t1['date']}, 卖出: {t2['date']}")
        elif hold_days == 0:
            print(f"⚠️  T+0交易: {t1['date'].strftime('%Y-%m-%d')}")

print("\n检查完成!")
