Objective
Raw inputs (prices, volumes, accounting numbers) are rarely good model inputs: they have different scales across assets, heavy tails, missing values and trends. This lesson gives the standard transformations, in the order they are usually applied, and the leakage trap in each one.
Returns over horizons
The basic price features are returns over several look-backs: 1 day, 5 days, 1 month, 12 months excluding the last month. Compute them from total-return (adjusted) prices, as log returns so that horizons add: the 20-day log return is log1p(ret).rolling(20).sum(). Skipping the most recent period (the "12-1" construction) separates momentum from short-term reversal, which have opposite signs.
Overlapping horizon features are strongly correlated with each other (the 20-day and 60-day returns share 20 days, so their correlation is about on i.i.d. returns). Either orthogonalise them or use non-overlapping blocks (days 1–5, 6–20, 21–60).
Volatility scaling
A 10% move means something different for a utility and for a biotech stock. Dividing by a volatility estimate puts assets on a common scale:
where is an -day return and a daily volatility estimated from data up to only, typically an exponentially weighted average of squared returns. The scaled feature is a move measured in standard deviations, so it has roughly unit variance for every asset.
Cross-sectional normalisation
For a cross-sectional model (which stocks will outperform which, on a given date), normalise within each date:
- z-score: , using the mean and standard deviation across stocks on date . This removes market-wide shifts in the level of a feature, and it uses only date- data, so it cannot leak.
- rank: map each value to its percentile on that date, then centre. Ranks are immune to outliers and to the shape of the distribution, and they discard the size of extreme values, which can be good or bad.
- Neutralise: subtract industry or beta exposure (regress the feature on industry dummies across stocks each date and keep the residual) when the signal should not be a disguised sector bet.
Outliers: winsorise before you z-score
A z-score uses the mean and standard deviation, which one extreme value distorts. Winsorising clips values to bounds: percentiles (1st and 99th) work in large cross-sections; in small ones, use a robust centre and scale such as the median times (the factor makes the MAD estimate the standard deviation for normal data). Winsorise, then z-score, and optionally clip the z-scores at .
Missing values
- Find out why it is missing. Not yet reported, not applicable (banks have no inventory), not covered by the vendor, or a data error. Each needs different handling.
- Never fill a raw feature with 0 before normalising: a missing earnings yield filled with 0 becomes a low value and a real bet.
- Neutral fill after normalising: fill missing z-scores with (the cross-sectional mean) or the industry median, and add a binary "missing" indicator so a model can learn whether missingness itself predicts anything (it often does: small, uncovered firms).
- Forward-fill only with a limit (a quarterly fundamental can carry forward for about one quarter plus a reporting lag), and never back-fill.
Worked example
horizon return, volatility scaling and cross-sectional rank
Three stocks have daily volatilities of 1%, 2% and 4%. Build a 20-day momentum feature, scale it by an EWMA volatility estimated from past data, and rank it across the three stocks on the last date. Check that scaling equalises the features' spreads.
Show solutionHide solution
import numpy as np, pandas as pd
rng = np.random.default_rng(0)
dates = pd.bdate_range("2024-01-01", periods=300)
vols = {"AAA": 0.01, "BBB": 0.02, "CCC": 0.04}
ret = pd.DataFrame({k: rng.normal(0, v, len(dates)) for k, v in vols.items()}, index=dates)
# 1. Horizon return, 20 days, ending at t (log returns add).
mom20 = np.log1p(ret).rolling(20).sum()
# 2. Volatility from data up to t: EWMA of squared returns, ~30-day half-life.
sigma = ret.pow(2).ewm(halflife=30, min_periods=60).mean().pow(0.5)
# 3. Vol-scaled momentum: a 20-day return measured in 20-day standard deviations.
mom20_s = mom20 / (sigma * np.sqrt(20))
# 4. Cross-sectional rank on each date (row-wise).
rank = mom20_s.rank(axis=1, pct=True)
last = dates[-1]
print(pd.DataFrame({"mom20": mom20.loc[last], "sigma": sigma.loc[last],
"mom20_s": mom20_s.loc[last], "rank": rank.loc[last]}).round(4))
print("sd of raw mom20: ", mom20.std().round(4).to_dict())
print("sd of scaled mom20:", mom20_s.std().round(2).to_dict())
mom20 sigma mom20_s rank
AAA -0.0760 0.0107 -1.5835 0.6667
BBB -0.1672 0.0182 -2.0523 0.3333
CCC -0.0790 0.0313 -0.5645 1.0000
sd of raw mom20: {'AAA': 0.0433, 'BBB': 0.0752, 'CCC': 0.1569}
sd of scaled mom20: {'AAA': 0.84, 'BBB': 0.89, 'CCC': 0.96}
The raw spreads differ by a factor of almost four, in line with the volatilities; after scaling they are all close to 1 (somewhat below, because 300 days of overlapping 20-day windows after the 60-day warm-up hold only about 12 independent windows, so the sample standard deviations are noisy). The ranking changes: on raw momentum CCC (−7.9%) and AAA (−7.6%) look alike, but CCC's fall is only half a standard deviation while AAA's is one and a half, so CCC ranks first after scaling.
Every input is backward-looking: rolling and ewm use rows up to , and the rank uses only row . The target (for example the next 5-day return) would be np.log1p(ret).rolling(5).sum().shift(-5), and the shift belongs on the target, never on a feature.
Worked example
winsorising a small cross-section
On one date, 12-1 momentum for eight stocks A to H is 0.12, −0.05, 0.30, 0.02, missing, −0.18, 2.40, 0.07. Compare the z-scores of the raw values, of values clipped at the 5th and 95th percentiles, and of values clipped at the median robust standard deviations. Then fill the missing value.
Show solutionHide solution
import numpy as np, pandas as pd
# One date's cross-section: raw 12-1 momentum for eight stocks (E is missing).
raw = pd.Series([0.12, -0.05, 0.30, 0.02, np.nan, -0.18, 2.40, 0.07],
index=list("ABCDEFGH"))
def zscore(x):
return (x - x.mean()) / x.std()
def pct_clip(x, lo=0.05, hi=0.95):
return x.clip(x.quantile(lo), x.quantile(hi))
def mad_clip(x, k=3.0):
med = x.median()
mad = 1.4826 * (x - med).abs().median() # robust sigma
return x.clip(med - k * mad, med + k * mad)
f = pd.DataFrame({"raw": raw})
f["z_raw"] = zscore(raw)
f["z_pct"] = zscore(pct_clip(raw))
f["z_mad"] = zscore(mad_clip(raw))
f["rank"] = raw.rank(pct=True) - 0.5 # spacing 1/7 here; NaN stays NaN
f["missing"] = raw.isna().astype(int)
f["z_final"] = f["z_mad"].fillna(0.0) # 0 = cross-sectional mean
print(f.round(3).to_string())
print("pct bounds:", raw.quantile([0.05, 0.95]).round(3).tolist())
print("mad bounds:", [round(v, 3) for v in mad_clip(raw).agg(["min", "max"])])
raw z_raw z_pct z_mad rank missing z_final
A 0.12 -0.292 -0.269 -0.024 0.214 0 -0.024
B -0.05 -0.480 -0.525 -0.685 -0.214 0 -0.685
C 0.30 -0.092 0.002 0.675 0.357 0 0.675
D 0.02 -0.402 -0.420 -0.413 -0.071 0 -0.413
E NaN NaN NaN NaN NaN 1 0.000
F -0.18 -0.624 -0.662 -1.190 -0.357 0 -1.190
G 2.40 2.237 2.218 1.855 0.500 0 1.855
H 0.07 -0.347 -0.344 -0.219 0.071 0 -0.219
pct bounds: [-0.141, 1.77]
mad bounds: [-0.18, 0.604]
Raw z-scores. G's 240% return inflates both the mean and the standard deviation, so every other stock is squashed into a z-score between −0.62 and −0.09: C (+30%) gets a negative score, and the feature is in effect "is it G or not".
Percentile clipping with seven values barely helps: the interpolated 95th percentile is 1.77, so G is still an outlier. Percentile bounds need hundreds of names.
Robust clipping. The median is 0.07; the absolute deviations from it have median 0.12, so the robust sigma is and the bounds are , i.e. . Only G is clipped, to 0.604 (the printed minimum, −0.18, is just F's unclipped value). Now C scores +0.68, and the scores spread out sensibly. The rank column gets the same ordering with no tuning at all.
Missing. E's z-score is filled with 0, the cross-sectional mean, so the model takes no position on it, and the missing column records the fact. Filling the raw value with 0 instead (and re-running the same robust clip and z-score) gives E a z-score of −0.45, below D's, a real bet based on nothing.
Normalising over time without leaking
Time-series normalisation (how high is this spread or this valuation relative to its own history?) must use only the past: an expanding or rolling mean and standard deviation, not the full-sample ones. Full-sample statistics feel harmless, but the sample mean contains the future path, and a series below its full-sample mean must, on average, rise later to reach it.
import numpy as np, pandas as pd
rng = np.random.default_rng(3)
pnl = {"full": [], "expanding": []}
for _ in range(1000): # 1000 random walks: no edge
x = pd.Series(rng.normal(0, 1, 1000)).cumsum() # e.g. a spread level
nxt = x.diff().shift(-1) # next change
z_full = (x - x.mean()) / x.std() # uses the whole sample
m = x.expanding(min_periods=60)
z_exp = (x - m.mean()) / m.std() # uses data up to t only
for name, z in [("full", z_full), ("expanding", z_exp)]:
pnl[name].append((-z * nxt).mean()) # mean-reversion: hold -z
for name, p in pnl.items():
p = np.array(p)
print(f"{name:9s} mean P&L per step {p.mean():+.4f} t = {p.mean() / p.std(ddof=1) * np.sqrt(len(p)):+.1f}")
full mean P&L per step +0.0489 t = +57.4
expanding mean P&L per step +0.0007 t = +0.5
On random walks, which by construction cannot be predicted, the full-sample z-score produces a mean-reversion "edge" with a t-statistic of 57. The expanding z-score correctly finds nothing. The same applies to every fitted transformation: winsorising bounds, PCA loadings, scalers in a scikit-learn pipeline. Fit them inside each training window and apply them forward, never on the whole dataset first.
Cross-sectional normalisation on date does not have this problem, because it uses only the date- cross-section. Pooling all dates into one z-score does, and it also lets a market-wide trend in the feature dominate.
Knowledge check
Book-to-price is missing for 15% of stocks on a date. You fill the missing raw values with 0 and then z-score cross-sectionally. What is the effect?
Knowledge check
A researcher z-scores a valuation spread using its mean and standard deviation over 2000 to 2024, then backtests 'buy when z < −1' over the same period. Why is the backtest optimistic even if every trade uses only the lagged z-score?
Knowledge check
In a cross-section of 3,000 stocks, why might you prefer cross-sectional ranks to z-scores of a raw accounting ratio?
Key takeaways
- Build horizon returns from adjusted log prices; skip the last month for momentum; mind the overlap between horizons.
- Scale by volatility estimated from the past: .
- Normalise within each date: winsorise (robustly in small cross-sections), then z-score, or rank.
- Missing values: fill after normalising, with a neutral value and a missing indicator; forward-fill with a limit; never fill raw values with 0 or back-fill.
- Any statistic fitted over the whole sample (means, scales, clip bounds, PCA, scalers) leaks; fit within training windows only. Shifts go on the target, not the features.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).