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: keytrader_id, name fieldsfirst_nameandlast_name, plusemail,ageand the hire timestampjoined_company_dt.trade_results: keytrade_id, the owningtrader_id, the timestamptrade_execution_dt, an integerprofitand thestrategylabel.
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 solutionLessons behind this question
- Transforms and Moment Generating Functions
- Derivation — From Binomial Trees to Black-Scholes in the Continuous Limit
- The Black-Scholes Formula Derived via Change of Measure
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