-- View: paper_trade_scorecard -- Aggregates paper trading performance per symbol with win rates, PnL, and -- average fill quality. Filters to paper execution mode only. -- Requirements: 10.1, 10.2, 10.3 -- Design ref: Section 9.2 (paper trading PnL scorecard) CREATE OR REPLACE VIEW lakehouse.stonks.paper_trade_scorecard AS SELECT pnl.ticker, pnl.broker_account, COUNT(DISTINCT pnl.dt) AS trading_days, SUM(pnl.realized_pnl) AS total_realized_pnl, SUM(pnl.unrealized_pnl) AS total_unrealized_pnl, SUM(pnl.net_pnl) AS total_net_pnl, SUM(pnl.fees) AS total_fees, AVG(pnl.net_pnl) AS avg_daily_pnl, -- Win rate: fraction of days with positive net PnL CAST( COUNT(CASE WHEN pnl.net_pnl > 0 THEN 1 END) AS DOUBLE ) / NULLIF(COUNT(*), 0) AS win_rate, -- Worst and best single-day PnL MIN(pnl.net_pnl) AS worst_day_pnl, MAX(pnl.net_pnl) AS best_day_pnl, -- Order counts from trade_orders COUNT(DISTINCT o.order_id) AS total_orders, COUNT(DISTINCT CASE WHEN o.status = 'filled' THEN o.order_id END) AS filled_orders, MIN(pnl.dt) AS first_trade_date, MAX(pnl.dt) AS last_trade_date FROM lakehouse.stonks.pnl_daily pnl LEFT JOIN lakehouse.stonks.trade_orders o ON pnl.ticker = o.ticker AND pnl.broker_account = o.broker_account AND pnl.dt = o.dt AND o.execution_mode = 'paper' WHERE pnl.execution_mode = 'paper' GROUP BY pnl.ticker, pnl.broker_account;