Vectorize a Row by Row Pandas Moving Average Backtest
Last updated: November 29, 2026
Quick Overview
A researcher's moving-average crossover backtest loops over every date and ticker with iterrows and takes minutes on a few hundred stocks. Rewrite it in vectorized pandas without introducing lookahead bias, including transaction costs.
Balyasny
November 29, 20260
0
0 solved
A researcher's moving-average crossover backtest loops over every date and ticker with iterrows and takes minutes on a few hundred stocks. Rewrite it in vectorized pandas without introducing lookahead bias, including transaction costs.
Python and pandas are the daily tools of Balyasny's researchers and research technology engineers, and speeding up analyst code without changing its results is common work. The interviewer checks vectorization fluency, alignment and shift semantics, and whether the candidate validates equivalence.
What the Interviewer Expects
- Replace loops with rolling, shift and elementwise operations on wide DataFrames
- Lag positions by one bar so a signal formed at today's close earns tomorrow's return
- Model turnover-based transaction costs correctly, including the first trade
- Handle NaNs from warmup windows and missing prices
- Verify against the original implementation on a sample before switching
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you handle stocks that enter and leave the universe over time?
- When would you reach for numba or polars instead of pandas?
- How would you parallelize a parameter sweep over many fast and slow windows?
- How would you make the result reproducible across library versions?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
Input: wide DataFrame px indexed by date, columns tickers, of close prices. Rule: long 1 unit when the fast mean is above the slow mean, short 1 when below. Return the equal-weighted daily net retur...
High-Level Design
Every step is a column-wise array operation: pct_change for returns, rolling().mean() for the two averages, np.sign of their difference for signal, shift(1) to trade next bar, multiplication f...