Objective
pandas adds labels to NumPy arrays: every value has an index entry, and operations align on labels before computing. For time series that is both the benefit (two series with different trading calendars combine correctly) and the hazard (a misplaced label quietly moves information across time). The aim of this lesson is to write signal and backtest code where every value at time uses only information available at . The examples ran on pandas 3.1.
DatetimeIndex
Put timestamps in the index, sorted, and most time-series operations become one-liners:
import numpy as np
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="B") # business days
s = pd.Series([100, 101, 103, 102, 105, 107, 106, 108, 110, 109], index=idx, dtype=float)
s["2024-01-08":"2024-01-10"] # label slicing is inclusive of both ends
s.loc["2024-01"] # partial-string indexing: all of January
Keep timestamps timezone-aware (tz_localize, tz_convert) when mixing venues; a naive New York close and a naive London close one hour apart look identical and are not.
Resampling
resample groups by time buckets and then aggregates, like a groupby on time:
print(s.resample("W-FRI").last())
# 2024-01-05 105.0
# 2024-01-12 109.0
print(s.resample("W-FRI").ohlc())
# open high low close
# 2024-01-05 100.0 105.0 100.0 105.0
# 2024-01-12 107.0 110.0 106.0 109.0
The label of each bucket matters. Weekly buckets ending Friday are labelled with the Friday, so the 2024-01-05 bar contains information up to that Friday's close. That is safe. But for many frequencies the default label is the bucket's left edge (e.g. hourly or 5-minute bars, label="left"), so a bar stamped 10:00 contains prices up to 10:05. Joining that bar to a 10:00 event leaks five minutes of the future. Check label and closed for every resample in a pipeline, and prefer right-labelled bars for signals.
Rolling and ewm windows
s.rolling(n) covers the current row and the before it (right-aligned). Edge behaviour depends on min_periods:
- Integer window:
min_periodsdefaults to the window length, so the first results areNaN. Settingmin_periods=1fills them with means of fewer points, which are noisier and should not be treated like full-window values. - Time window (
rolling("3D")): the window is a calendar span andmin_periodsdefaults to 1. On a Monday, "3D" contains only Monday, because Saturday and Sunday have no rows:s.rolling("3D").count()reads 1, 2, 3, 3, 3 and then 1 on 2024-01-08. Use an integer window for "last 3 trading days". center=Trueuses future rows. It is fine for plotting and is look-ahead in a signal.- Any
NaNinside an integer window makes the resultNaNunless the count of valid values reachesmin_periods.
s.ewm(...) gives exponentially weighted statistics, parametrised by exactly one of span (), halflife (), com or alpha. The adjust flag changes the early values:
adjust=True(default) divides by the sum of the weights actually used: .adjust=Falseis the recursion , , which is what a live system computes tick by tick.
With span=3 () on 100, 101, 103: adjust=True gives 100, , ; adjust=False gives 100, 100.5, 101.75. The two converge as the weight on the starting value decays, but a backtest using one and a production system using the other will disagree for the first several half-lives. ewm also accepts min_periods to blank the unreliable start.
shift, pct_change and look-ahead
s.shift(1) moves values one row later (the value at is the one from ). s.pct_change() is s / s.shift(1) - 1, the return ending at . The basic backtest identity is:
because a position chosen with information up to the close of earns the return from to . In pandas: pnl = signal.shift(1) * ret. Forgetting the shift multiplies today's position by the return that produced it.
Other common leaks: normalising with full-sample statistics ((x - x.mean()) / x.std() uses the future; use rolling or expanding statistics), bfill, center=True, survivor-only universes, and fundamentals stamped by period end rather than publication date.
On missing prices: in pandas 3, pct_change no longer forward-fills, so a NaN price gives NaN returns on both sides of it ([1.0, NaN, 3.0] gives [NaN, NaN, NaN]). If you ffill() first you get [NaN, 0.0, 2.0]: a fake zero and then a two-day move on one day. Decide deliberately which you want.
Worked example
a Sharpe ratio of 20 from pure noise
Simulate 1,000 days of independent normal returns (no predictability exists) and test the rule "long after an up day, short after a down day". Compute the annualised Sharpe ratio with and without the shift. Explain the number you get without it.
Show solutionHide solution
rng = np.random.default_rng(7)
idx = pd.bdate_range("2020-01-01", periods=1000)
ret = pd.Series(rng.normal(0, 0.01, len(idx)), index=idx)
price = 100 * (1 + ret).cumprod()
signal = np.sign(price.pct_change()) # +1 after an up day, -1 after a down day
def sharpe(pnl):
pnl = pnl.dropna()
return np.sqrt(252) * pnl.mean() / pnl.std()
wrong = signal * ret # today's position earns today's return
right = signal.shift(1) * ret # yesterday's position earns today's return
print(f"wrong: {sharpe(wrong):.1f} right: {sharpe(right):.2f}")
# wrong: 20.3 right: 0.38
Without the shift, signal * ret is : the strategy is paid the absolute value of every return. For , and , so the daily Sharpe is about and the annualised one is . The simulated 20.3 matches.
With the shift, the strategy has no edge and the 0.38 is noise: the standard error of an annualised Sharpe ratio estimated over years is roughly , here .
The diagnostic habit: any daily strategy with a Sharpe ratio above about 3 should be treated as a bug until proven otherwise, and the first place to look is alignment between positions and returns.
groupby on panel data
Panel data usually arrives long: one row per (date, ticker). Any operation across time must then be done within each ticker:
df = pd.DataFrame({
"date": pd.to_datetime(["2024-01-02", "2024-01-03", "2024-01-04"] * 2),
"ticker": ["AAA"] * 3 + ["BBB"] * 3,
"close": [10.0, 11.0, 12.0, 50.0, 49.0, 51.0],
})
df["ret_bad"] = df["close"].pct_change() # row 3: 50/12 - 1 = 3.1667
df["ret"] = df.groupby("ticker")["close"].pct_change() # row 3: NaN, as it should be
The ungrouped version computes a "return" from AAA's last close to BBB's first, a 317% move that will dominate any statistic. The same applies to shift, rolling, ewm and diff. Remember the three groupby shapes: agg returns one row per group, transform returns a result aligned to the original rows (e.g. transform("mean") broadcasts each ticker's mean back), and apply is the slow general fallback. Cross-sectional operations (rank, z-score across stocks each day) group by date instead.
The alternative is the wide layout (df.pivot(index="date", columns="ticker", values="close")): then wide.pct_change() works per column automatically and cross-sectional operations become axis=1.
Missing data
- Arithmetic propagates
NaN; reductions skip it (skipna=True).pd.Series([1, None, None, None, 5.0]).mean()is 3.0 over the two valid values, and the sum of an all-NaNseries is 0.0, notNaN. Usemin_count=1if that matters. - Label alignment creates
NaN: adding series indexed[x, y]and[y, z]givesNaNatxandz. Check.isna().sum()after every join. ffillis causal (uses the past); cap it withlimit=so a delisted stock does not carry a stale price for months.bfillandinterpolateuse the future and do not belong in signal code.- In pandas 3 Copy-on-Write is always on: chained assignment such as
df[df.x > 0]["y"] = 1never modifiesdf(it warns). Usedf.loc[mask, "y"] = 1.
Worked example
matching trades to the prevailing quote with merge_asof
You have trades and quotes for two tickers with millisecond timestamps. Attach to each trade the most recent quote for the same ticker strictly before the trade, and ignore quotes more than 2 seconds old.
trades = pd.DataFrame({
"time": pd.to_datetime(["2024-01-02 09:30:00.150", "2024-01-02 09:30:00.400",
"2024-01-02 09:30:01.000", "2024-01-02 09:30:05.000"]),
"ticker": ["AAA", "AAA", "BBB", "AAA"],
"price": [10.02, 10.01, 49.98, 10.05],
})
quotes = pd.DataFrame({
"time": pd.to_datetime(["2024-01-02 09:30:00.100", "2024-01-02 09:30:00.400",
"2024-01-02 09:30:00.900", "2024-01-02 09:30:01.200"]),
"ticker": ["AAA", "AAA", "BBB", "AAA"],
"bid": [10.00, 10.01, 49.97, 10.03],
"ask": [10.02, 10.03, 49.99, 10.05],
})
Show solutionHide solution
An exact join on time would match almost nothing. merge_asof matches each left row to the nearest right row by key, in a chosen direction. Both frames must be sorted by the on column.
out = pd.merge_asof(
trades, quotes, on="time", by="ticker",
direction="backward", # only quotes at or before the trade...
allow_exact_matches=False, # ...strictly before it
tolerance=pd.Timedelta("2s"), # and no older than 2 seconds
)
# time ticker price bid ask
# 0 09:30:00.150 AAA 10.02 10.00 10.02
# 1 09:30:00.400 AAA 10.01 10.00 10.02
# 2 09:30:01.000 BBB 49.98 49.97 49.99
# 3 09:30:05.000 AAA 10.05 NaN NaN
(Times shown as clock times.) Row by row:
- The 00.150 AAA trade gets the 00.100 quote.
- The 00.400 AAA trade has a quote at exactly 00.400, but
allow_exact_matches=Falseskips it, so it also gets the 00.100 quote. With identical timestamps you usually cannot tell whether the quote update came before or after the trade, and the conservative choice avoids attaching a quote that may have been caused by the trade itself. by="ticker"makes the BBB trade use the 00.900 BBB quote, not the more recent AAA one.- The 05.000 AAA trade's last AAA quote is at 01.200, 3.8 seconds old, beyond the tolerance, so it gets
NaNrather than a stale quote.
The same tool attaches the latest available fundamental, the latest index level or the prevailing signal to any event stream, and direction="backward" is what keeps the join causal.
Knowledge check
A daily series has 300 rows. How many leading NaNs does s.rolling(20).mean() produce, and how many does s.rolling(20, min_periods=5).mean() produce?
Knowledge check
signal is computed from closing prices up to and including day t, and ret is the close-to-close return ending on day t. Which line gives a causal daily PnL?
Knowledge check
A long DataFrame has columns date, ticker, close, sorted by ticker then date. What goes wrong with df['close'].rolling(5).std()?
Knowledge check
s.ewm(span=3).mean() and s.ewm(span=3, adjust=False).mean() are applied to 100, 101, 103. What is each value on the third row?
Key takeaways
- Index by sorted, timezone-aware timestamps; label slices are inclusive. Check each
resample'slabelandclosed. - Integer rolling windows need
windowobservations by default; time windows are calendar spans withmin_periods=1.center=Trueis look-ahead. ewm: one of span, halflife, com or alpha;adjust=Falseis the live recursion, and it differs from the default early on.- PnL is
position.shift(1) * ret. A daily Sharpe ratio above about 3 is a bug until proven otherwise. - On long panels, every time-series operation goes through
groupby("ticker"). merge_asofwithdirection="backward",by=andtolerance=gives causal as-of joins.- Reductions skip
NaN(an all-NaNsum is 0);ffillwith a limit is causal,bfillis not; use.locfor assignment under Copy-on-Write.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).