trading-audit-dashboard

Creates a professional forensic trading audit dashboard from any broker's trading history export. Use this skill whenever a user uploads a trading statement, CSV export, PDF report, or any file containing trade history from brokers like Trading 212, Interactive Brokers, eToro, Binance, MetaTrader, Robinhood, or any other platform. Triggers on phrases like "analyze my trades", "audit my trading", "create a trading dashboard", "review my performance", "analyze my CFD trades", "trading report", "P&L analysis", or whenever a trading data file is uploaded and the user wants analysis, charts, or a dashboard. Also triggers when the user asks to "update the dashboard" with new data. Produces an institutional-grade dark-theme HTML dashboard with equity curve, scenario charts, behavioral forensics, Monte Carlo projections, Kelly sizing, risk-of-ruin, streak analytics, rolling period comparison, hourly P&L heatmap, and cost drag analysis.

Trading Audit Dashboard Skill v2.0

Produces a full forensic trading performance audit as a single self-contained HTML dashboard. Covers 7 phases: Executive Dashboard, Strategy Reverse-Engineering, Behavioral Forensics, Advanced Analytics (NEW), Monte Carlo Forecasting, Professional Recommendations, and JSON Export.


Step 1 — Identify Input Format and Extract Trade Data

Read the uploaded file(s). Supported formats:

  • PDF (broker statements like Trading 212, eToro, IBKR) → use pdfplumber
  • CSV → parse with pandas/csv
  • XLSX → use openpyxl or pandas
  • JSON → load directly

For PDF Statements (most common)

import pdfplumber

with pdfplumber.open('file.pdf') as pdf:
    all_text = {}
    for i, page in enumerate(pdf.pages):
        all_text[i+1] = page.extract_text() or ''

Scan pages for CFD / derivatives trade tables. Look for pages containing:

  • Keywords: executed trades, CFD, closed, realized, settlement
  • Column headers: DIRECTION, BUY/SELL, QUANTITY, PRICE, RESULT, P&L, PROFIT

Skip Invest/equity account pages — only process CFD/derivatives/futures/forex closed trades.

Key Parsing Rules

For Trading 212 format:

  • Opening entries have - in the Average Price column → skip these
  • Closing entries have a populated Average Price → include these
  • TOTAL RESULT is the last EUR/USD amount on the line (after FX Fee, Result, Div Adj, OI)
  • Sign is literal in the text: €64.25 = profit, €-32.10 = loss

For generic CSV/XLSX:

  • Look for columns: profit, pnl, realized_pnl, net_result, closed_pnl
  • Parse open_time/close_time for hold duration
  • Extract volume/lots/quantity for position size analysis
  • Extract swap / commission / spread fields if present (used by cost drag analysis)

Minimum Required Fields Per Trade

trade = {
    'date': 'YYYY-MM-DD',
    'time': 'HH:MM:SS',          # or '00:00:00' if unavailable
    'datetime': 'YYYY-MM-DD HH:MM:SS',
    'direction': 'Buy' | 'Sell',
    'instrument': 'XAUUSD',      # ticker/symbol
    'size': 2,                   # lots/units/quantity
    'total_result': 64.25,       # signed float, positive=profit
    'order_type': 'Limit',       # optional
    'swap_cost': 0.0,            # optional — overnight financing (negative = cost)
    'spread_cost': 0.0,          # optional — spread/commission drag
}

Save to /home/claude/parsed_trades.json.


Step 2 — Compute All Statistics

Run scripts/compute_stats.py on the parsed trades. If the script is unavailable, compute inline using the formulas in references/statistics.md.

The script now computes all v2.0 metrics automatically:

Core Metrics (unchanged)

  • Win rate, avg win/loss, profit factor, expectancy, net P&L, max win/loss, trades/day

Session / DOW / Size / Order Type (unchanged)

  • Asian/London/NY session stats; Mon–Fri day-of-week; position size buckets; order type comparison

Sharpe Ratio & Max Drawdown (unchanged)

  • Annualised Sharpe; max drawdown in currency and percent

Monte Carlo (unchanged)

  • 10,000 simulations × remaining months of year; P10/P50/P90 projections

v2.0 NEW Metrics

Wilson Confidence Interval on Win Rate

# Formula in references/statistics.md → 'win_rate_ci' key
# Output: lower, upper, label, note
# Always display alongside win rate — critical for small samples (< 100 trades)

Kelly Criterion

# 'kelly' key: full_kelly_pct, half_kelly_pct, note
# Recommend Half-Kelly always; Full Kelly capped at 50% display

Risk of Ruin

# 'risk_of_ruin' key: ror_pct, ror_2x_pct (at 2x lot size), note
# Ruin threshold = 50% drawdown from current equity

Drawdown Recovery Modelling

# 'dd_recovery' key: recovery_trades, recovery_days, note

Loss Streaks & Tilt Detection

# 'loss_streaks' key: max_loss_streak, tilt_detected, tilt_detail

Streak & Momentum Analytics

# 'streak_analytics' key: current_streak, current_streak_type,
#   overconfidence_detected, hot_10_trade_pnl, cold_10_trade_pnl

Rolling Period Comparison (30/60/90 day)

# 'rolling_periods' key: windows {30d, 60d, 90d}, trend (improving/stable/declining)

Hourly P&L Heatmap

# 'hourly_heatmap' key: heatmap[0..23], best_hour, worst_hour
# Only populated when time data available for ≥50% of trades

Multi-Instrument Matrix (when > 1 instrument detected)

# 'instrument_matrix' key: instruments{}, best_by_sharpe, worst_by_sharpe

Transaction Cost / Swap Drag

# 'cost_drag' key: total_swap_cost, total_spread_cost, total_cost_drag,
#   cost_pct_of_gross, estimated (bool), note

Step 3 — Determine Starting Equity

Look in the broker statement for:

  • Trading 212: Account value in the CFD section of the Overview
  • IBKR: Net Asset Value or Starting Cash
  • eToro: Account Balance at period start
  • MetaTrader: Balance at start of statement period
  • If unavailable: estimate as abs(net_pnl) / 0.20 or ask user

Step 4 — Generate the HTML Dashboard

Read assets/dashboard_template.html for the full visual design system.

Substitute all {{PLACEHOLDER}} values with computed statistics.

Existing Placeholders (unchanged from v1.0)

PlaceholderValue
{{TRADER_NAME}}From statement header or "Trader"
{{ACCOUNT_ID}}From statement or "N/A"
{{BROKER}}Detected broker name
{{INSTRUMENT}}Primary instrument(s) traded
{{PERIOD_START}}Earliest trade date
{{PERIOD_END}}Latest trade date
{{TRADING_DAYS}}Count of distinct trading dates
{{TOTAL_TRADES}}len(trades)
{{NET_PROFIT}}net_pnl formatted as currency
{{WIN_RATE}}e.g. "89.0%"
{{PROFIT_FACTOR}}e.g. "3.26"
{{MAX_DRAWDOWN}}e.g. "€177"
{{EXPECTANCY}}e.g. "€11.75"
{{SHARPE}}e.g. "16.12"
{{AVG_WINNER}}e.g. "€19.05"
{{AVG_LOSER}}e.g. "€47.33"
{{EQUITY_LABELS}}JS array of date strings
{{EQUITY_DATA}}JS array of running equity floats
{{STARTING_EQUITY}}Float
{{SCENARIO_*}}Bear/Base/Bull monthly projections
{{SESSION_*}}Asian/London/NY stats
{{DOW_*}}Mon–Fri stats
{{SIZE_TABLE_ROWS}}HTML table rows
{{CURRENT_EQUITY}}Starting + net_pnl
{{RETURN_PCT}}Return %

v2.0 New Placeholders

PlaceholderValue
{{WIN_RATE_CI}}e.g. "76–96% (95% CI)"
{{WIN_RATE_CI_NOTE}}Full CI note string
{{KELLY_HALF}}e.g. "12.3%"
{{KELLY_FULL}}e.g. "24.7%"
{{KELLY_NOTE}}Full Kelly recommendation text
{{ROR_PCT}}e.g. "0.23%"
{{ROR_2X_PCT}}e.g. "3.84%" (at double lot size)
{{ROR_NOTE}}Full RoR note
{{DD_RECOVERY_TRADES}}e.g. "15"
{{DD_RECOVERY_DAYS}}e.g. "3.0"
{{MAX_LOSS_STREAK}}e.g. "3"
{{TILT_DETECTED}}"Yes ⚠️" or "No ✅"
{{TILT_DETAIL}}Tilt detail string
{{CURRENT_STREAK}}e.g. "5 wins" or "2 losses"
{{HOT_10_PNL}}Best rolling 10-trade P&L
{{COLD_10_PNL}}Worst rolling 10-trade P&L
{{ROLLING_TREND}}"📈 Improving" / "📉 Declining" / "➡️ Stable"
{{ROLLING_30D_WR}}30-day win rate %
{{ROLLING_60D_WR}}60-day win rate %
{{ROLLING_90D_WR}}90-day win rate %
{{ROLLING_30D_PF}}30-day profit factor
{{HOURLY_HEATMAP_DATA}}JS array of {hour, avg_pnl, trades} for Chart.js
{{BEST_HOUR}}e.g. "09:00 UTC"
{{WORST_HOUR}}e.g. "14:00 UTC"
{{INST_MATRIX_ROWS}}HTML rows for instrument comparison table (or "N/A" if single)
{{COST_DRAG_TOTAL}}e.g. "€28.40"
{{COST_DRAG_PCT}}e.g. "4.2%" of gross
{{COST_DRAG_NOTE}}Full cost drag note
{{OVERCONFIDENCE_DETECTED}}"Yes ⚠️" or "No ✅"

New Dashboard Sections to Add

After the existing Behavioral Forensics section, add these new panels:

Panel: Advanced Analytics — Kelly & Risk of Ruin

<!-- Show Kelly Half / Full, RoR at current + 2x sizing, DD recovery estimate -->

Panel: Rolling Performance Trend

<!-- 3-column table: 30d / 60d / 90d with WR%, PF, Net P&L, trend badge -->

Panel: Hourly P&L Heatmap (only if time data available)

<!-- Chart.js horizontal bar chart of avg P&L by hour, 0–23 UTC -->
<!-- Highlight best/worst hour in green/red -->

Panel: Streak & Momentum

<!-- Current streak badge, hot/cold 10-trade windows, tilt status, overconfidence flag -->

Panel: Multi-Instrument Matrix (only if > 1 instrument)

<!-- Table: Instrument | Trades | WR% | PF | Net P&L | Sharpe Proxy -->
<!-- Badge: Best and Worst by Sharpe -->

Panel: Transaction Cost Drag

<!-- Swap cost + spread cost + total drag + % of gross profit -->
<!-- Note if estimated vs actual -->

Step 5 — Vulnerability Scorecard Logic (unchanged)

Rate each dimension with 🟢/🟡/🔴 using these rules:

Dimension🟢 Green🟡 Yellow🔴 Red
Stop-Loss DisciplineMax loss < 3× avg lossMax loss 3–5× avg lossMax loss > 5× avg loss
Position SizingAll sizes positiveOne size bucket negativeMultiple size buckets negative
Over-TradingWorst day WR > 85%Worst day WR 80–85%Worst day WR < 80%
Profit FactorPF > 3.0PF 1.5–3.0PF < 1.5
Win Rate ReliabilityWR > 88% rollingWR 82–88%WR < 82%

v2.0 addition: Display Wilson CI below win rate in scorecard with tooltip.


Step 6 — Recommendation Engine (v2.0 expanded)

The recommendation engine now checks up to 7 conditions (capped at 5 output recommendations):

  1. Worst position size → eliminate / cap
  2. Kelly Criterion → display Half-Kelly optimal sizing (NEW)
  3. Streak / tilt circuit-breaker → rules for 2-loss break + post-win size reset (NEW)
  4. Max loss hard stop → hard monetary SL at 2× avg loss
  5. Session reallocation → migrate volume from worst to best session
  6. Rolling trend warning → reduce size 50% if declining trend detected (NEW)
  7. Order type gap → limit-only entries if market orders underperform

Frame recommendations as:

  • Title: Italic, specific action
  • Body: Quantified evidence + specific rule to implement
  • Impact: Estimated annual P&L improvement

Step 7 — Output

Save completed dashboard HTML to /mnt/user-data/outputs/trading_audit_dashboard.html.

NEW v2.0: Also save stats JSON to /mnt/user-data/outputs/trading_audit_stats.json (enables downstream use with morning-note, financial-model, and future incremental updates).

Use present_files tool to deliver both files.

Then provide a concise text summary (5–8 lines) covering:

  • Total trades, win rate (with CI), profit factor
  • Net P&L and return %
  • The single most critical finding (biggest leak)
  • Year-end base case projection
  • Kelly sizing recommendation

Broker Detection Guide

BrokerDetection Signal
Trading 212"Trading 212" or "Activity statement" + "CFD account"
IBKR"Interactive Brokers" or "IB"
eToro"eToro" in header
MetaTraderColumns "Order", "Symbol", "Type", "Open Time"
Binance"Binance" or crypto instrument names
Saxo"Saxo Bank"
CMC Markets"CMC Markets"
Generic CSVNo broker detected → use column mapping heuristics

Error Handling

  • No CFD trades found: Inform user and ask if they want Invest/equity account analyzed instead
  • Missing time data: Default to 00:00:00, skip session + hourly heatmap, note limitation
  • Single instrument: Skip instrument matrix, expand single-instrument analysis
  • < 20 trades: Warn small sample; still produce dashboard with CI caveat prominently shown
  • Missing starting equity: Estimate or prompt user; note assumption in dashboard footer
  • No swap/spread data: Use estimated cost drag (0.20/trade); mark as estimated

Quality Checklist Before Delivering

  • All {{PLACEHOLDER}} values replaced (no raw placeholders in output)
  • Equity curve runs from first to last trading day
  • Scenario chart starts at current equity, projects remaining months
  • Win rate CI displayed alongside headline WR
  • Kelly Half recommendation shown in sizing panel
  • Risk of Ruin shown at current + 2x sizing
  • Rolling period table populated (or "Insufficient history" if < 30 days of data)
  • Hourly heatmap shown only if time data available
  • Instrument matrix shown only if > 1 instrument
  • Cost drag panel shows "estimated" flag when applicable
  • Streak analytics panel shows current streak + hot/cold windows
  • Recommendations are specific and quantified, not generic
  • JSON stats file saved alongside HTML
  • Dashboard footer shows trade count, date range, and "v2.0" label