Skip to content
LeetQuant
QR01 Python for Quantitative Research

QR01 · Python for Quantitative Research · Lesson 2 of 5

pandas for Time Series

DatetimeIndex slicing, resampling, rolling and ewm windows and their min_periods behaviour, shift and pct_change without look-ahead, per-ticker groupby, merge_asof for as-of joins, and missing data.

19 min

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 tt uses only information available at tt. 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 n−1n - 1 before it (right-aligned). Edge behaviour depends on min_periods:

  • Integer window: min_periods defaults to the window length, so the first n−1n - 1 results are NaN. Setting min_periods=1 fills 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 (t−3 days,t](t - 3\text{ days}, t] and min_periods defaults 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=True uses future rows. It is fine for plotting and is look-ahead in a signal.
  • Any NaN inside an integer window makes the result NaN unless the count of valid values reaches min_periods.

s.ewm(...) gives exponentially weighted statistics, parametrised by exactly one of span (α=2/(span+1)\alpha = 2/(\text{span} + 1)), halflife (α=1−2−1/h\alpha = 1 - 2^{-1/h}), com or alpha. The adjust flag changes the early values:

  • adjust=True (default) divides by the sum of the weights actually used: yt=∑i=0t(1−α)ixt−i/∑i=0t(1−α)iy_t = \sum_{i=0}^{t} (1-\alpha)^i x_{t-i} \big/ \sum_{i=0}^{t} (1-\alpha)^i.
  • adjust=False is the recursion y0=x0y_0 = x_0, yt=αxt+(1−α)yt−1y_t = \alpha x_t + (1 - \alpha) y_{t-1}, which is what a live system computes tick by tick.

With span=3 (α=0.5\alpha = 0.5) on 100, 101, 103: adjust=True gives 100, (101+0.5⋅100)/1.5=100.6667(101 + 0.5 \cdot 100)/1.5 = 100.6667, (103+0.5⋅101+0.25⋅100)/1.75=102.0(103 + 0.5 \cdot 101 + 0.25 \cdot 100)/1.75 = 102.0; 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 tt is the one from t−1t - 1). s.pct_change() is s / s.shift(1) - 1, the return ending at tt. The basic backtest identity is:

pnlt=positiont−1×rt,\text{pnl}_t = \text{position}_{t-1} \times r_t ,

because a position chosen with information up to the close of t−1t - 1 earns the return from t−1t - 1 to tt. 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 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 sign⁡(rt) rt=∣rt∣\operatorname{sign}(r_t)\, r_t = |r_t|: the strategy is paid the absolute value of every return. For r∼N(0,σ2)r \sim N(0, \sigma^2), E∣r∣=σ2/π≈0.798σ\mathbb{E}|r| = \sigma\sqrt{2/\pi} \approx 0.798\sigma and sd⁡∣r∣=σ1−2/π≈0.603σ\operatorname{sd}|r| = \sigma\sqrt{1 - 2/\pi} \approx 0.603\sigma, so the daily Sharpe is about 1.3241.324 and the annualised one is 1.324252≈211.324\sqrt{252} \approx 21. 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 YY years is roughly 1/Y1/\sqrt{Y}, here 1/1000/252≈0.51/\sqrt{1000/252} \approx 0.5.

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-NaN series is 0.0, not NaN. Use min_count=1 if that matters.
  • Label alignment creates NaN: adding series indexed [x, y] and [y, z] gives NaN at x and z. Check .isna().sum() after every join.
  • ffill is causal (uses the past); cap it with limit= so a delisted stock does not carry a stale price for months. bfill and interpolate use 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"] = 1 never modifies df (it warns). Use df.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 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=False skips 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 NaN rather 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's label and closed.
  • Integer rolling windows need window observations by default; time windows are calendar spans with min_periods=1. center=True is look-ahead.
  • ewm: one of span, halflife, com or alpha; adjust=False is 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_asof with direction="backward", by= and tolerance= gives causal as-of joins.
  • Reductions skip NaN (an all-NaN sum is 0); ffill with a limit is causal, bfill is not; use .loc for assignment under Copy-on-Write.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).