#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
诊断报告问题
"""

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

from trend_report_fixed import TrendTrackingStrategy

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

trades = result['trades']

print('='*70)
print('交易记录诊断')
print('='*70)

print(f"\n总交易记录数: {len(trades)}")
print(f"第一条交易: {trades[0]['date'].strftime('%Y-%m-%d')} {trades[0]['action']}")
print(f"最后一条交易: {trades[-1]['date'].strftime('%Y-%m-%d')} {trades[-1]['action']}")

print("\n前5条交易:")
for i, t in enumerate(trades[:5], 1):
    print(f"{i}. {t['date'].strftime('%Y-%m-%d')} {t['action']}")

print("\n后5条交易:")
for i, t in enumerate(trades[-5:], len(trades)-4):
    print(f"{i}. {t['date'].strftime('%Y-%m-%d')} {t['action']}")

print("\n" + "="*70)
print('检查 get_recent_trades(20) 返回的内容:')
print("="*70)

recent = strategy.get_recent_trades(20)
for i, t in enumerate(recent, 1):
    date_str = t['date'].strftime('%Y-%m-%d')
    action = t['action']
    price = t['price']
    if action == 'SELL':
        ret = t.get('return_pct', 0)
        print(f"{i:2d}. {date_str} {action:4s} @ {price:8.2f} ({ret:+.2f}%)")
    else:
        print(f"{i:2d}. {date_str} {action:4s} @ {price:8.2f}")

print("\n" + "="*70)
print('配对检查 - 最近10对交易:')
print("="*70)

# 从 recent 中配对
pair_count = 0
i = 0
while i < len(recent) - 1:
    if recent[i]['action'] == 'BUY' and recent[i+1]['action'] == 'SELL':
        pair_count += 1
        buy = recent[i]
        sell = recent[i+1]
        hold_days = (sell['date'] - buy['date']).days
        ret = sell.get('return_pct', 0)
        print(f"{pair_count}. 买 {buy['date'].strftime('%Y-%m-%d')} → 卖 {sell['date'].strftime('%Y-%m-%d')} | {ret:+.2f}% | {hold_days}天")
        i += 2
    else:
        i += 1

print(f"\n找到 {pair_count} 对完整交易")
