Objective
Research coding rounds test whether you can turn a research idea into correct pandas or numpy code quickly, and whether you know the handful of places where research code silently goes wrong: alignment in time, missing data, cross-sectional versus time-series operations, and costs. Interviewers care more about correctness and a test than about speed or cleverness.
Habits that score well
- State the timing convention first. "signal[t] is known at the close of day t; returns[t] is the return from t − 1 to t." Most bugs are violations of a convention nobody wrote down.
- Write a test for look-ahead. Change the future and check that past outputs do not move.
- Vectorise across one axis consciously. Cross-sectional operations are
axis=1orgroupby("date"); time-series operations areshift,rollinganddiffalong the index. - Handle missing data explicitly and say what you chose.
- Print a sanity number: a turnover, a hit rate, a value you can check by hand.
The solutions below were run with Python 3, pandas 3.1 and numpy; the outputs shown are what they print.
Worked example
Exercise 1, a rolling z-score without look-ahead
Write rolling_zscore(x, window) that returns, for each , the z-score of relative to the mean and sample standard deviation of the previous window values . The output must be NaN until a full window of history exists. Show it on [10, 11, 9, 12, 10, 14, 8] with window 3, and write a test that it uses no future data.
Show solutionHide solution
The common mistake is x.rolling(window).mean(), whose window ends at and therefore includes itself: the statistic is then shrunk towards zero, and when the series is a return used to trade at , it is look-ahead. Shifting by one first makes the window end at .
import pandas as pd
def rolling_zscore(x: pd.Series, window: int) -> pd.Series:
"""z_t = (x_t - mean of the previous window values) / their std."""
past = x.shift(1).rolling(window, min_periods=window)
return (x - past.mean()) / past.std(ddof=1)
x = pd.Series([10.0, 11.0, 9.0, 12.0, 10.0, 14.0, 8.0])
print(rolling_zscore(x, 3).round(3).tolist())
# Test: changing the future must not change the past.
y = x.copy()
y.iloc[5:] = [100.0, -100.0]
z_x, z_y = rolling_zscore(x, 3), rolling_zscore(y, 3)
print(z_x.iloc[:5].equals(z_y.iloc[:5]))
Output:
[nan, nan, nan, 2.0, -0.436, 2.4, -2.0]
True
Check by hand. At the previous values are : mean 10, sample standard deviation 1, so . At they are : mean 12, standard deviation 2, so .
Follow-ups to expect. A zero standard deviation gives inf; decide whether to return NaN instead. For an exponentially weighted version, use x.shift(1).ewm(halflife=h).mean(); the same shift rule applies.
Worked example
Exercise 2, rank IC by date
You have a long DataFrame with columns date, ticker, signal and fwd_ret (the return over the next period, already aligned). Compute the Spearman rank information coefficient (IC) for each date, then the mean IC, the IC information ratio (mean over standard deviation) and a t-statistic. Some signals are missing. Test on simulated data with 250 dates, 200 stocks and a true linear correlation of about 0.05.
Show solutionHide solution
Drop rows missing either field before ranking, so both columns are ranked on the same set of stocks. Then compute one correlation per date: the IC is a cross-sectional statistic, and averaging per-date ICs weights every date equally.
import numpy as np
import pandas as pd
def ic_by_date(df: pd.DataFrame) -> pd.Series:
"""Spearman rank IC between signal and forward return, one value per date."""
clean = df.dropna(subset=["signal", "fwd_ret"]) # rank only rows that have both
return clean.groupby("date").apply(
lambda g: g["signal"].corr(g["fwd_ret"], method="spearman"), include_groups=False
)
def ic_summary(ic: pd.Series) -> dict:
ic = ic.dropna()
ir = ic.mean() / ic.std(ddof=1)
return {"mean_ic": ic.mean(), "ic_ir": ir, "t_stat": ir * np.sqrt(len(ic)), "n_dates": len(ic)}
rng = np.random.default_rng(7)
dates = pd.bdate_range("2024-01-01", periods=250)
n_stocks = 200
signal = rng.standard_normal((len(dates), n_stocks))
fwd_ret = 0.05 * signal + rng.standard_normal((len(dates), n_stocks))
df = pd.DataFrame({
"date": np.repeat(dates, n_stocks),
"ticker": np.tile(np.arange(n_stocks), len(dates)),
"signal": signal.ravel(),
"fwd_ret": fwd_ret.ravel(),
})
df.loc[df.sample(frac=0.02, random_state=0).index, "signal"] = np.nan # missing data
summary = ic_summary(ic_by_date(df))
print(f"mean IC {summary['mean_ic']:.3f}, IC IR {summary['ic_ir']:.3f}, t {summary['t_stat']:.2f}, dates {summary['n_dates']}")
Output:
mean IC 0.049, IC IR 0.648, t 10.24, dates 250
Sanity check. The true Pearson correlation is , and for normal data the Spearman correlation is , so 0.049 is within sampling error. With 200 stocks, the per-date IC has a standard deviation of about , so the IC IR should be near and the t-statistic near , consistent with the output.
The follow-up interviewers ask. "The forward return is 5 days but you compute the IC daily. Is the t-statistic right?" No: consecutive ICs share four of five return days, so they are autocorrelated. If the IC autocorrelations are roughly , the variance of the mean IC is inflated by , and the naive t-statistic is too large by . Use Newey–West errors or every fifth date.
Worked example
Exercise 3, a vectorised backtest with costs
Given wide DataFrames signal and returns (dates by assets), build a dollar-neutral portfolio with gross exposure 1 from the cross-sectionally demeaned signal, trade at each close on that day's signal, and charge 5 bp per unit of turnover. Report gross and net annualised Sharpe ratios and mean daily turnover. Then show what happens if you forget the one-day lag.
Show solutionHide solution
The key line is weights.shift(1): the position held over day was decided at the close of day . Turnover is the sum of absolute weight changes; the first day's turnover is the initial position.
import numpy as np
import pandas as pd
def backtest(signal: pd.DataFrame, returns: pd.DataFrame, cost_bps: float = 5.0) -> pd.DataFrame:
"""signal[t] is known at the close of day t; returns[t] is the close-to-close return into day t."""
demeaned = signal.sub(signal.mean(axis=1), axis=0)
weights = demeaned.div(demeaned.abs().sum(axis=1), axis=0).fillna(0.0) # dollar-neutral, gross 1
held = weights.shift(1).fillna(0.0) # trade at t's close, earn t+1's return
gross = (held * returns).sum(axis=1)
turnover = held.diff().abs().sum(axis=1)
turnover.iloc[0] = held.iloc[0].abs().sum()
net = gross - turnover * cost_bps / 1e4
return pd.DataFrame({"gross": gross, "net": net, "turnover": turnover})
def sharpe(pnl: pd.Series) -> float:
return pnl.mean() / pnl.std(ddof=1) * np.sqrt(252)
rng = np.random.default_rng(11)
T, N = 1000, 50
idx = pd.bdate_range("2020-01-01", periods=T)
alpha = pd.DataFrame(rng.standard_normal((T, N)), index=idx) # known at close of t
noise = rng.standard_normal((T, N)) * 0.02
returns = pd.DataFrame(0.0005 * alpha.shift(1).fillna(0.0).values + noise, index=idx)
res = backtest(alpha, returns)
print(f"gross Sharpe {sharpe(res['gross']):.2f}, net Sharpe {sharpe(res['net']):.2f}, "
f"mean daily turnover {res['turnover'].mean():.2f}")
# Look-ahead check: using today's returns with today's signal (no shift) on pure noise.
fake = pd.DataFrame(noise, index=idx)
w = fake.sub(fake.mean(axis=1), axis=0)
w = w.div(w.abs().sum(axis=1), axis=0)
print(f"look-ahead Sharpe on noise {sharpe((w * fake).sum(axis=1)):.1f}")
Output:
gross Sharpe 2.06, net Sharpe -1.11, mean daily turnover 1.41
look-ahead Sharpe on noise 148.4
Reading the output.
- Turnover 1.41 is checkable. The signal is redrawn independently every day, so yesterday's and today's weight vectors are unrelated; the expected for two independent vectors of gross 1 is close to .
- Costs dominate. At 5 bp per unit, 1.41 of daily turnover costs about 7 bp a day, more than the signal's gross edge, so a gross Sharpe of 2 becomes negative. A fast signal needs either a slower trading rule (smooth the signal, trade only large changes) or lower costs.
- Look-ahead is unmistakable. Without the shift, weighting today's returns by themselves gives a Sharpe ratio above 100 on pure noise. A Sharpe above 5 in a daily equity backtest is a reason to look for this bug first.
Follow-ups to expect. Add a volatility scaling per asset; cap position sizes; handle assets that enter and leave the universe (NaN returns must not be filled with zero before ranking); compute maximum drawdown of the cumulative net PnL.
Knowledge check
signal[t] uses the close of day t, and returns[t] is the close-to-close return from t − 1 to t. Which expression gives the daily PnL without look-ahead?
Knowledge check
You compute a 20-day z-score with (x - x.rolling(20).mean()) / x.rolling(20).std() and trade on it at the same close. What is wrong?
Knowledge check
A strategy has daily turnover of 0.8 of gross exposure and you pay 4 bp per unit of turnover. Roughly how much does it cost per year (252 days), as a fraction of gross exposure?
Key takeaways
- Write the timing convention down before coding;
shift(1)between decision and return is the most important line in a backtest. - Shift before
rollingorewmwhen the statistic must use only past data, and test by perturbing the future. - The IC is cross-sectional: drop missing pairs, rank within each date, average per-date values; adjust its t-statistic for overlapping forward returns.
- Report turnover and net-of-cost results; a fast signal with a gross Sharpe of 2 can lose money.
- Print a number you can check by hand, and treat implausibly high Sharpe ratios as bugs until proven otherwise.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).