skills/psh355q-ui/szdi57465yt/report-writer-agent

report-writer-agent

SKILL.md

Report Writer Agent - 자동 리포트 생성기

Role

일일/주간/월간 거래 성과, 방어 실적, Agent 정확도, 헌법 준수율을 자동으로 분석하여 마크다운 리포트를 생성합니다.

Core Capabilities

1. Report Types

Daily Report

  • 오늘의 거래 요약
  • 승/패 거래
  • 주요 Signal 성과

Weekly Report

  • 주간 수익률
  • Agent별 정확도
  • Shadow Trade 방어 실적
  • Top Performers

Monthly Report

  • 월간 총정산
  • 목표 대비 실적
  • Sharpe Ratio, Max Drawdown
  • 헌법 준수율
  • AI 자기 개선 제안

2. Performance Metrics

# Trading Performance
total_trades: int
winning_trades: int
losing_trades: int
win_rate: float  # winning_trades / total_trades
average_return: float
sharpe_ratio: float
max_drawdown: float

# Defensive Performance
total_rejections: int
defensive_wins: int  # 거부한 제안이 실제 손실이었던 경우
defensive_win_rate: float
avoided_loss_usd: float

# Agent Accuracy
agent_accuracies: Dict[str, float]  # {agent_name: accuracy}
best_performing_agent: str
worst_performing_agent: str

# Constitutional Compliance
total_proposals: int
constitutional_violations: int
compliance_rate: float  # (total - violations) / total

3. Report Generation

def generate_daily_report(date: str) -> str:
    """Generate daily markdown report"""
    
    # Fetch data
    signals = get_signals_for_date(date)
    shadows = get_shadow_trades_for_date(date)
    
    # Calculate metrics
    metrics = calculate_metrics(signals, shadows)
    
    # Generate markdown
    report = format_report(metrics, template='daily')
    
    return report

Output Format

Daily Report Example

# 일일 거래 리포트 - 2025-12-21

## 📊 거래 요약

- **총 Signal 수**: 5개
- **실행된 거래**: 3개
- **거부된 제안**: 2개 (헌법 위반)

## 🎯 Signal 성과

| Signal ID | Ticker | Action | Source | Status | Return |
|-----------|--------|--------|--------|--------|--------|
| SIG-001 | AAPL | BUY | war_room | EXECUTED | +2.3% |
| SIG-002 | NVDA | BUY | deep_reasoning | EXECUTED | +5.1% |
| SIG-003 | TSLA | SELL | manual_analysis | EXECUTED | +1.5% |
| SIG-004 | XYZ | BUY | news_analysis | REJECTED | - |
| SIG-005 | ABC | BUY | ceo_analysis | REJECTED | - |

**일일 수익률**: +3.0%

## 🛡️ 방어 실적

### Shadow Trades (거부된 제안 추적)

| Ticker | Rejected Reason | Virtual P&L | Result |
|--------|----------------|-------------|--------|
| XYZ | 포지션 20% 초과 | -$1,200 | DEFENSIVE_WIN ✅ |
| ABC | Stop Loss 미설정 | +$300 | MISSED_OPPORTUNITY |

**방어 성공**: 1건  
**회피한 손실**: $1,200

## 📈 Agent 성과

| Agent | Signals | Accuracy | Contribution |
|-------|---------|----------|--------------|
| War Room | 1 | 100% | Excellent |
| Deep Reasoning | 1 | 100% | Excellent |
| Manual Analysis | 1 | 100% | Good |

## ⚖️ 헌법 준수

- **총 제안**: 5개
- **위반 건수**: 2개
- **준수율**: 60%
- **주요 위반**: Article 4 (포지션 한도)

## 💡 인사이트

1. 모든 실행된 거래가 수익 (Win Rate 100%)
2. Shadow Trade 방어 성공으로 $1,200 손실 회피
3. 헌법 제4조 위반 주의 필요

---
Generated by Report Writer Agent v1.0

Weekly Report Example

# 주간 거래 리포트 - Week 51, 2025

## 📊 주간 요약

- **기간**: 2025-12-15 ~ 2025-12-21
- **총 Signal**: 23개
- **실행 거래**: 15개
- **거부 제안**: 8개

## 🎯 성과 지표

| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| 주간 수익률 | +4.5% | +2% | ✅ 초과 달성 |
| Win Rate | 73% | >55% ||
| Sharpe Ratio | 1.45 | >1.0 ||
| Max Drawdown | -3.2% | <-5% ||

## 🏆 Top Performers

### Best Signals
1. **NVDA** (deep_reasoning): +12.5%
2. **AAPL** (war_room): +8.3%
3. **MSFT** (ceo_analysis): +5.7%

### Worst Signals
1. **XYZ** (news_analysis): -2.1%
2. **ABC** (manual_analysis): -1.5%

## 🛡️ 방어 실적

- **총 거부**: 8건
- **Defensive Wins**: 6건 (75%)
- **회피한 손실**: $5,400
- **Missed Opportunities**: 2건 (+$800)

**순 방어 가치**: $4,600

## 🤖 Agent 정확도

| Agent | Signals | Win Rate | Avg Return | Rank |
|-------|---------|----------|------------|------|
| Deep Reasoning | 5 | 80% | +6.2% | 1 |
| War Room | 6 | 83% | +5.1% | 2 |
| CEO Analysis | 3 | 67% | +3.8% | 3 |
| Manual Analysis | 4 | 50% | +2.0% | 4 |
| News Analysis | 5 | 60% | +1.5% | 5 |

## ⚖️ 헌법 준수

- **총 제안**: 23개
- **위반 건수**: 8개
- **준수율**: 65%

**위반 내역**:
- Article 4 (Risk Management): 6건
- Article 2 (Explainability): 2건

## 💰 자본 보존

- **시작 자본**: $100,000
- **종료 자본**: $104,500
- **자본 보존율**: 104.5%
- **헌법이 방어한 손실**: $5,400 (5.4%)

## 📝 권장 사항

1. **Article 4 위반 감소**: Risk Agent 가중치 증대
2. **News Analysis 정확도 개선**: 신뢰도 낮은 소스 필터링
3. **Deep Reasoning 활용 확대**: 가장 높은 승률

---
Generated on 2025-12-21

Decision Framework

Step 1: Determine Report Type
  - Daily: 당일 데이터
  - Weekly: 최근 7일
  - Monthly: 최근 30일

Step 2: Fetch Data
  - trading_signals
  - shadow_trades
  - proposals
  - agent_votes

Step 3: Calculate Metrics
  - Performance: Win rate, returns, Sharpe
  - Defensive: Shadow trades, avoided loss
  - Agent: Individual accuracy
  - Constitutional: Violation rate

Step 4: Generate Insights
  - Best/worst performers
  - Trend analysis
  - Recommendations

Step 5: Format as Markdown
  - Tables for data
  - Alerts for important findings
  - Charts (optional, via mermaid)

Step 6: Distribute
  - Save to file
  - Send to Telegram
  - Display on dashboard

Guidelines

Do's ✅

  • 객관적 데이터: 숫자로 말하기
  • 실행 가능한 인사이트: 구체적 개선 방안 제시
  • 시각적 구성: 표, 그래프 활용
  • 트렌드 강조: 개선/악화 추세 표시

Don'ts ❌

  • 과도한 칭찬/비난 금지 (객관성 유지)
  • 데이터 조작 절대 금지
  • 불필요한 복잡성 지양
  • 결론 없는 나열 금지

Integration

Data Sources

from backend.database.models import TradingSignal, ShadowTrade, Proposal
from sqlalchemy import func
from datetime import datetime, timedelta

def get_weekly_performance(start_date: datetime) -> Dict:
    """Get weekly performance metrics"""
    
    end_date = start_date + timedelta(days=7)
    
    # Fetch signals
    signals = db.query(TradingSignal).filter(
        TradingSignal.created_at >= start_date,
        TradingSignal.created_at < end_date
    ).all()
    
    # Calculate metrics
    total_signals = len(signals)
    executed = [s for s in signals if s.status == 'EXECUTED']
    
    returns = [s.actual_return for s in executed if s.actual_return is not None]
    win_rate = sum(1 for r in returns if r > 0) / len(returns) if returns else 0
    
    avg_return = sum(returns) / len(returns) if returns else 0
    
    # Shadow trades
    shadows = db.query(ShadowTrade).filter(
        ShadowTrade.created_at >= start_date,
        ShadowTrade.created_at < end_date
    ).all()
    
    defensive_wins = sum(1 for s in shadows if s.status == 'DEFENSIVE_WIN')
    
    return {
        'total_signals': total_signals,
        'executed': len(executed),
        'win_rate': win_rate,
        'avg_return': avg_return,
        'defensive_wins': defensive_wins,
        'shadows': len(shadows)
    }

Report Distribution

from backend.notifications.telegram_commander_bot import TelegramCommanderBot

async def send_daily_report(report_markdown: str):
    """Send report via Telegram"""
    
    telegram = TelegramCommanderBot()
    
    await telegram.send_message(
        chat_id=os.getenv('TELEGRAM_COMMANDER_CHAT_ID'),
        text=report_markdown,
        parse_mode='Markdown'
    )

Performance Metrics

  • Report Generation Time: 목표 < 5초
  • Data Accuracy: 100% (DB에서 직접 계산)
  • Delivery Success: > 99% (Telegram)
  • User Satisfaction: 리포트 유용성 피드백

Mermaid Charts Example

## 주간 수익률 추이

```mermaid
line chart
    title "Daily P&L - Week 51"
    x-axis [Mon, Tue, Wed, Thu, Fri]
    y-axis "Return %" -2 --> 6
    line [1.2, 2.5, -0.8, 3.1, 4.5]

## Version History

- **v1.0** (2025-12-21): Initial release with daily/weekly/monthly reports
Weekly Installs
5
First Seen
3 days ago
Installed on
trae3
claude-code3
windsurf2
opencode2
cursor2
codex2