Skip to content

SQL for each trader's top-earning strategy last week

Question

A fund of 35 traders runs four strategy types: 'momentum', 'trend', 'mean reversion' and 'stat arb'. Tables:

  • traders: key trader_id, name fields first_name and last_name, plus email, age and the hire timestamp joined_company_dt.
  • trade_results: key trade_id, the owning trader_id, the timestamp trade_execution_dt, an integer profit and the strategy label.

Restrict to trades from the past 7 days. Only consider (trader, strategy) combinations with at least 5 trades in that window. For each trader, report the strategy that earned the most total profit; if strategies tie on profit, take the one the trader used first. Output full_name, strategy and total_profit, sorted by profit descending and then name ascending.

Short answer

Aggregate per (trader, strategy), filter, rank within trader. Group last-week trades by trader and strategy, computing SUM(profit), MIN(trade_execution_dt) and COUNT(*), keeping HAVING COUNT(*) >= 5. Rank with ROW_NUMBER() OVER (PARTITION BY trader_id ORDER BY total_profit DESC, first_dt ASC), keep row 1, join traders for first_name || ' ' || last_name, and order by profit then name.

Adapted from OpenQuant; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question

Start with a free lesson: Probability Fundamentals is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.

Read it free