Module contents
Lesson 10 of 24Core 75 min

Time series with pandas

pandas tools for time-indexed data: DatetimeIndex, time zones, frequencies and calendars, resample, rolling and exponential windows, shifts, and alignment of asynchronous series. The focus is temporal correctness: no value may use future information, the foundation of quantitative work and honest validation with temporal data.

After this lesson you can

  • Build and manipulate time indexes with time zones, frequencies, and business-day calendars.
  • Change frequency with resample, choosing each interval's label and closure correctly.
  • Calculate rolling, expanding, and exponential statistics and simple and logarithmic returns.
  • Detect and avoid future-information leakage with shift, causal windows, and expanding statistics.
  • Align series from different sources and frequencies with merge_asof without introducing bias.

Before you start

Motivation: the spectacular strategy that was just a forgotten shift

Simulate ten years of daily prices as a pure random walk: each day price is multiplied by eεte^{\varepsilon_t} with independent εt∼N(0,0.012)\varepsilon_t \sim \Normal(0, 0.01^2). By construction there is nothing to predict: no rule using only the past can win on average. Now apply the classic technical-analysis rule, long if price is above its 20-day average and short if below, and measure its Sharpe ratio.

[ ]A strategy that is too goodBrowser
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
dias = pd.bdate_range("2015-01-01", periods=2520)                # diez años de días hábiles
precio = pd.Series(100 * np.exp(np.cumsum(rng.normal(0, 0.01, len(dias)))), index=dias)
ret = precio.pct_change()                                        # retorno del día t: de t-1 a t

senal = np.sign(precio - precio.rolling(20).mean())              # +1 encima de su media, -1 debajo

def sharpe(pnl):
    pnl = pnl.dropna()
    return np.sqrt(252) * pnl.mean() / pnl.std()

print("sin shift:", round(sharpe(senal * ret), 2), "  capital final x", round((1 + senal * ret).prod()))
print("con shift:", round(sharpe(senal.shift(1) * ret), 2), "  capital final x", round((1 + senal.shift(1) * ret).prod(), 2))

Without shift, Sharpe is 5.1 and capital multiplies more than 1700-fold in ten years: better than any fund in history. With shift(1), it is 0.35, noise (repeating with 300 seeds gives mean 0.02 and deviation 0.32). The difference is one call. senal * ret multiplies the signal calculated using the close on day tt by the return from close t−1t - 1 to close tt: to hold that position during the day, it would have had to be decided at close t−1t - 1, when the price at tt did not yet exist. Since the signal checks whether price is above its average and today’s return is exactly what just pushed it up or down, signal and return are correlated by construction.

This is the costliest and most frequent error in temporal data work, and almost never so visible. The next figure reproduces four real variants of the same leakage in a strategy that cannot win without leakage.

InteractiveThe signal that saw the future
Price (random walk) · bands: missing days708090100Cumulative return (log, %)−20−100102030Data used by the position earning day 145 return−9−8−7−6−5−4−3−2−1τ+1+2+3+4+5+6+7+8+9decision (close τ−1)future
  • strategy with leaks
  • same strategy without leaks
  • gap price, ffill
  • data known at decision time
  • future data
Alignment errors
Annualized Sharpe (this market)2.49
Mean Sharpe over 40 markets2.90
No leaks, this market−0.91
Correct days55.0 %
Future data used on day 1451
Price follows a random walk: no causal rule can win on average. The red curve’s advantage over the gray curve comes from data unavailable at decision time.
Prices simulated as a random walk, with streaks of missing days (hatched bands). The strategy combines trend (slope of a 5-day moving average) and value (price distance from its mean in standard deviations). Start with execution at the same close and compare with the gray curve, the same strategy without leakage. Then try each leak separately: which produce spectacular curves and which only a ‘credible’ Sharpe? The lower strip marks, for the chosen day, data used by the position earning that day's return; red marks data not yet available at decision time. Enabling backward fill moves the strip to the first missing day, where it acts.

All four leaks share a structure: a value dated tt depends on something after tt. That idea organizes this lesson. pandas offers excellent tools for time-indexed data (timezone-aware instant indexes, calendars, frequency changes, rolling windows, as-of joins), and almost all have a parameter whose default or misuse puts the future into the past. Learn each tool with the question “what did I know at the instant on this label?” in mind, and finish with two automatic tests detecting leakage without reasoning case by case.

Time in pandas: instants, durations, and periods

pandas distinguishes three objects that everyday language calls “time”:

ObjectWhat it representsExample
Timestampan instantpd.Timestamp("2024-03-30 12:00", tz="Europe/Madrid")
Timedeltaan absolute durationpd.Timedelta(hours=1), pd.Timedelta("90s")
DateOffseta calendar offsetpd.DateOffset(months=1), pd.offsets.BDay(3)
Perioda named intervalpd.Period("2024-03", freq="M"), March 1 through 31

A Timestamp is a 64-bit integer counting units (the resolution: seconds, milliseconds, microseconds, or nanoseconds) since January 1, 1970 UTC, plus an optional time zone. Resolution is part of the type, datetime64[us] or datetime64[ns], and limits range: at nanosecond resolution, 64 bits cover only 1677 to 2262, more than enough for prices but not geological dates. A Timedelta is a difference between instants, always the same number of seconds. A DateOffset is a calendar rule: “one month later” takes January 31 to February 29 (in 2024) and January 15 to February 15, different numbers of seconds. A Period is natural for data referring to an interval: March CPI does not occur at an instant, it describes a whole month, and its end_time is the last nanosecond of March. Confusing the period a datum describes with its publication instant is a common leak.

Label alignment makes shift safe: s.shift(1) moves values one position into the future while retaining the index, so row tt contains the value from t−1t - 1. If multiplied by another series with the same index, pandas matches by date and preserves the lag. If instead you shift the index (s.shift(1, freq="D") changes labels, not values) or convert to a NumPy array before operating, alignment disappears and an off-by-one error passes silently.

Time zones and daylight saving time

A Timestamp without a zone is naive: it says “12:00 on March 30,” but not where, so it does not identify an instant. One with a zone is aware and does. The two basic operations do opposite things:

  • tz_localize(zona) interprets a naive time as wall time in that zone. It does not change clock numbers; it adds missing information.
  • tz_convert(zona) translates an already-aware instant to wall time in another zone. It does not change the instant; it changes clock numbers.

Calling tz_convert on naive data is an error (pandas does not know what to convert from), and calling tz_localize on data actually in UTC silently shifts them one or two hours. Daylight saving time complicates tz_localize on two nights each year. In Madrid, on March 31, 2024 clocks jumped from 02:00 to 03:00: times between 02:00 and 02:59 do not exist. On October 27, 2024 they went back from 03:00 to 02:00: those same times exist twice, once in summer time (UTC+2) and once in winter time (UTC+1), and naive wall time cannot tell which.

[ ]Instants, durations, and daylight saving timeBrowser
import tzdata  # en el navegador carga la base de datos de zonas horarias; en tu máquina no hace falta
import pandas as pd

t = pd.Timestamp("2024-03-30 12:00")              # ingenua: no dice en qué zona
print(t, "| tz:", t.tz, "| resolución:", t.unit)
madrid = t.tz_localize("Europe/Madrid")           # misma hora de pared, ahora es un instante
print(madrid, "->", madrid.tz_convert("UTC"))     # mismo instante, otra hora de pared

# el 31 de marzo de 2024 dura 23 horas en Madrid
print("Timedelta(days=1): ", madrid + pd.Timedelta(days=1))    # duración absoluta
print("DateOffset(days=1):", madrid + pd.DateOffset(days=1))   # día de calendario

# la hora que no existe y la que existe dos veces
for s in ["2024-03-31 02:30", "2024-10-27 02:30"]:
    try:
        pd.Timestamp(s).tz_localize("Europe/Madrid")
    except Exception as e:
        print(f"{s}: {type(e).__name__}: {str(e)[:58]}...")
otono = pd.Timestamp("2024-10-27 02:30")
print(otono.tz_localize("Europe/Madrid", ambiguous=True), "(la primera, horario de verano)")
print(otono.tz_localize("Europe/Madrid", ambiguous=False), "(la segunda, horario de invierno)")

# en UTC no hay huecos ni repeticiones: convertir siempre funciona
utc = pd.date_range("2024-10-27 00:00", periods=4, freq="h", tz="UTC")
print(utc.tz_convert("Europe/Madrid").strftime("%H:%M %Z").tolist())

Notice both additions: Timedelta(days=1) adds exactly 24 hours and lands at 13:00 because that day had only 23; DateOffset(days=1) respects the calendar and lands at 12:00. Neither is universally correct: counting position exposure hours calls for the first, scheduling a daily task for the second. On the last line, four consecutive UTC hours read in Madrid as 02:00, 02:00, 03:00, and 04:00. Thus the rule of thumb is store and calculate in UTC and convert to local time only for display or defining sessions (an exchange opens at 09:00 local time, whose UTC instant changes twice yearly). For naive local data containing the October night, tz_localize(..., ambiguous="infer") infers which 02:30 is which if timestamps are ordered and the repeated hour appears twice; otherwise pass a Boolean array or mark rows NaT and decide manually.

Frequencies, business days, and calendars

A frequency is a DateOffset with a short name. The most used:

AliasMeaningAliasMeaning
"s", "min", "h"second, minute, hour"W-FRI"weeks ending Friday
"D"calendar day"ME", "MS"month end, start
"B"business day (Monday to Friday)"QE", "YE"quarter end, year end
"ms", "us", "ns"milli-, micro-, nanosecondCustomBusinessDay(...)business days with custom holidays

Anchored offsets (month end, Friday, quarter end) do not add a fixed amount: they advance to the next anchor. Timestamp("2024-01-15") + MonthEnd(1) is January 31, and Timestamp("2024-01-31") + MonthEnd(1) is February 29. Business days "B" know only weekends; for a particular market’s holidays, construct a calendar.

[ ]Frequencies, calendars, and gapsBrowser
import pandas as pd
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, GoodFriday, EasterMonday
from pandas.tseries.offsets import CustomBusinessDay

pd.set_option("display.width", 120)
print(pd.date_range("2024-01-29", periods=3, freq="ME").strftime("%d %b").tolist())   # fin de mes
print(pd.date_range("2024-01-29", periods=3, freq="MS").strftime("%d %b").tolist())   # inicio de mes
print(pd.date_range("2024-01-01", periods=3, freq="W-FRI").strftime("%a %d").tolist())
# un offset anclado avanza hasta el siguiente ancla, no suma una cantidad fija
print(pd.Timestamp("2024-01-15") + pd.offsets.MonthEnd(1), pd.Timestamp("2024-01-31") + pd.offsets.MonthEnd(1))

class CalendarioTARGET(AbstractHolidayCalendar):     # días de cierre del sistema de pagos del euro
    rules = [Holiday("Año Nuevo", month=1, day=1), GoodFriday, EasterMonday,
             Holiday("Día del Trabajo", month=5, day=1),
             Holiday("Navidad", month=12, day=25), Holiday("San Esteban", month=12, day=26)]

sesion = CustomBusinessDay(calendar=CalendarioTARGET())
print(pd.date_range("2024-03-25", "2024-04-05", freq=sesion).strftime("%a %d").tolist())
print("días hábiles en 2024:", len(pd.date_range("2024-01-01", "2024-12-31", freq="B")),
      "  con festivos TARGET:", len(pd.date_range("2024-01-01", "2024-12-31", freq=sesion)))

# huecos: una serie diaria a la que le faltan días
s = pd.Series([1.0, 2.0, 4.0], index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"]))
print("frecuencia inferida:", s.index.inferred_freq)
print(pd.DataFrame({"asfreq": s.asfreq("D"), "ffill": s.asfreq("D").ffill(), "bfill": s.asfreq("D").bfill()}))

The calendar skips Good Friday (March 29) and Easter Monday (April 1) in 2024, leaving 256 sessions instead of 262. When annualizing volatility or counting days to expiry, that 2% matters.

The last table shows the problem of gaps. A series with missing days has no frequency (inferred_freq is None) and most positional operations, such as shift(1) or rolling(5), count rows, not time: the day preceding January 5 becomes January 2. asfreq("D") makes gaps explicit as NaN, after which filling must be decided. ffill repeats the last known value and is causal: January 3 uses only January 2 information. bfill copies January 5’s value into January 3 and 4, days when that value did not yet exist. Backfilling is almost always leakage; the reasonable exception is data actually known before its timestamp (a scheduled-event calendar, for example).

resample: from ticks to bars

Market data arrives as ticks: one record per trade or quote change at irregular instants. Almost all models work with bars: summaries over regular intervals, such as each minute’s open, high, low, and close (OHLC) and traded volume. Moving from one frequency to another is resampling, handled by resample in pandas.

This is literally split-apply-combine where the group key is the interval index, k(t)=⌊(t−o)/Δ⌋k(t) = \lfloor (t - o)/\Delta \rfloor with closed="left" or ⌈(t−o)/Δ⌉−1\lceil (t - o)/\Delta \rceil - 1 with closed="right"; thus resample supports everything groupby supports (agg, apply, transform). The default origin is midnight of the first day (origin="start_day"), so 5-minute bars begin at :00, :05, :10.

Defaults depend on frequency: closed="left" and label="left" for almost all, and "right" for both parameters for those ending at a period-end anchor ("ME", "QE", "YE", "W"). A daily bar labeled with its date (the midnight it starts) or a five-minute bar labeled 09:00 contains, by default, what happened after its label. The causality question is simple: are all observations in a bar at or before its label?

InteractiveWhich bar contains this tick?
ticks.resample("5min", closed="left", label="left").ohlc()
[)[)[)[)[)08:5509:0009:0509:1009:1509:2009:0009:0509:1009:15
timestampnopenhighlowclosecomplete at
09:004100.00100.0599.98100.0409:05 (later)
09:054100.10100.25100.10100.2509:10 (later)
09:103100.30100.30100.18100.1809:15 (later)
09:154100.15100.33100.15100.2909:20 (later)
  • tick, colored by its bar
  • tick after its bar timestamp
  • bar timestamp
Resample parameters
closed: which edge belongs to the interval
label: which edge names the bar
Ticks after their bar timestamp11 of 15
Ticks exactly at the timestamp4
Tick at 09:05:00: interval → timestamp[09:05, 09:10) → 09:05
With label="left" each bar carries its start time: the 09:00 row contains prices through 09:04:59. Joining it to data or decisions at 09:00 uses five minutes of future data.
Fifteen ticks between 09:00 and 09:20, four exactly on grid boundaries (09:00:00, 09:05:00, 09:10:00, and 09:15:00). Each tick takes the color of its resample-assigned bar, and the arrow below the axis marks that bar's output label. Ticks circled red occur after their bar label. Explore all four combinations: which leave any red ticks? Which bar receives the 09:05:00 tick in each case?

The figure gives three conclusions:

  1. label determines causality. With label="left", the label is the interval start and almost everything in it is later. With label="right", the label is the end and nothing is later. pandas’ convention is not “incorrect” (labeling a period by its start is natural in descriptive statistics), but once bars are joined with signals, orders, or other series by timestamp, the label means “this was known at this time.”
  2. closed decides boundaries. With closed="left" the 09:05:00 tick opens the next bar; with closed="right" it closes the previous one. With closed="right", label="right" the 09:05 bar includes the exact 09:05:00 tick: causal (nothing later than its label), but no decision taken “at 09:05” could have processed that tick. closed="left", label="right" is the safer convention: every bar contains only ticks strictly before its label.
  3. Empty bars exist. If an interval has no ticks, resample produces a row with NaN (or 0 for sum and count). Removing it shifts everything calculated afterward by position.
[ ]OHLC bars, volume, and VWAPBrowser
import numpy as np
import pandas as pd

hora = ["09:00:00", "09:01:12", "09:02:40", "09:04:58", "09:05:00",
        "09:06:31", "09:08:05", "09:09:59", "09:10:00"]
ticks = pd.Series([100.00, 100.05, 99.98, 100.04, 100.10, 100.20, 100.16, 100.25, 100.30],
                  index=pd.to_datetime(["2024-01-02 " + h for h in hora]))

for closed in ["left", "right"]:
    for label in ["left", "right"]:
        b = ticks.resample("5min", closed=closed, label=label).agg(["count", "last"])
        filas = "  ".join(f"{t:%H:%M}: n={int(n)}, close={c:.2f}" for t, n, c in b.itertuples())
        print(f"closed={closed:5s} label={label:5s} | {filas}")

volumen = pd.Series([3, 1, 4, 1, 5, 9, 2, 6, 5], index=ticks.index) * 100
r = dict(rule="5min", closed="left", label="right")
barras = ticks.resample(**r).ohlc()
barras["volumen"] = volumen.resample(**r).sum()
barras["vwap"] = (ticks * volumen).resample(**r).sum() / barras["volumen"]
print(barras.round(3))

# de mensual a diario: rellenar hacia delante frente a interpolar
mensual = pd.Series([1.0, 3.0, 2.0], index=pd.to_datetime(["2024-01-31", "2024-02-29", "2024-03-31"]))
diario = mensual.resample("D")
print(pd.DataFrame({"ffill": diario.ffill(), "interpolate": diario.interpolate()}).loc["2024-02-14":"2024-02-16"])

VWAP (volume-weighted average price, ∑ipivi/∑ivi\sum_i p_i v_i / \sum_i v_i over the bar’s ticks) is the quotient of two sum resamplings, since weighted mean is not a standard aggregation. The last table shows upsampling, monthly to daily. ffill repeats January’s value through February, what was actually known. interpolate draws a line between January 31 and February 29, so on February 14 it is already nearly 2, halfway to a value (3) not known until month end. Interpolation is another leak, hard to see on a chart because the interpolated series “looks” more correct.

Rolling, expanding, and exponential windows

Once on a grid, almost every temporal feature is a statistic over a past window: the mean of the last 20 sessions, volatility of the last hour, maximum since the start. pandas offers three families.

The two exponential versions differ only initially: adjust=True distributes weight among existing observations, and adjust=False starts from y1=x1y_1 = x_1, weighted (1−α)i−1(1-\alpha)^{i-1}, more than its share. They agree when (1−α)i(1 - \alpha)^i is negligible. pandas accepts four equivalent parameterizations of the same α\alpha:

α=11+com=2span+1=1−2−1/halflife.\alpha = \frac{1}{1 + \text{com}} = \frac{2}{\text{span} + 1} = 1 - 2^{-1/\text{halflife}}.

The halflife is the number of steps over which a weight halves. The name com (center of mass) is no accident: it is the weights’ mean delay, as the next result proves. span is chosen so an EWMA of span nn has the same mean delay as an nn-point moving average (and, as a bonus, the same variance).

Proof

The moving average has weights wk=1/nw_k = 1/n for k=0,…,n−1k = 0, \dots, n-1: center of mass 1n∑k=0n−1k=n−12\frac1n\sum_{k=0}^{n-1} k = \frac{n-1}{2} and variance ∑kwk2σ2=σ2/n\sum_k w_k^2\sigma^2 = \sigma^2/n. Stationary EWMA has weights wk=α(1−α)kw_k = \alpha(1-\alpha)^k, k≥0k \ge 0, summing to 1 (hence no bias). Its center of mass is

∑k≥0k α(1−α)k=α(1−α)∑k≥1k(1−α)k−1=α(1−α)α2=1−αα,\sum_{k\ge0} k\,\alpha(1-\alpha)^k = \alpha(1-\alpha)\sum_{k\ge1} k(1-\alpha)^{k-1} = \frac{\alpha(1-\alpha)}{\alpha^2} = \frac{1-\alpha}{\alpha},

which with α=2/(n+1)\alpha = 2/(n+1) is (n−1)/(n+1)2/(n+1)=n−12\frac{(n-1)/(n+1)}{2/(n+1)} = \frac{n-1}{2}. Its variance is

σ2∑k≥0α2(1−α)2k=σ2α21−(1−α)2=σ2α2−α,\sigma^2\sum_{k\ge0}\alpha^2(1-\alpha)^{2k} = \frac{\sigma^2\alpha^2}{1 - (1-\alpha)^2} = \frac{\sigma^2\alpha}{2 - \alpha},

and since 2−α=2nn+12 - \alpha = \frac{2n}{n+1}, this is σ2⋅2n+1⋅n+12n=σ2n\sigma^2 \cdot \frac{2}{n+1}\cdot\frac{n+1}{2n} = \frac{\sigma^2}{n}.

∎

The theorem explains the name com, because com=(1−α)/α\text{com} = (1-\alpha)/\alpha is exactly the center of mass, and says that in stationary noise, a window and exponential with span nn are indistinguishable by their first two moments. Their weights’ shape separates them, noticeable only when the series changes.

InteractiveFixed window versus exponential memory
rolling(10).mean() versus ewm(span = 10).mean()012jumprampWeight of each observation at t = 68
  • data
  • true level
  • rolling(10)
  • ewm
  • center of mass of weights
rolling
10
ewm
EWMA α\alpha0.182
Mean lag (center of mass), rolling · ewm4.5 · 4.5
Theoretical noise standard deviation0.079 · 0.079
Measured on 6000 pure-noise points0.080 · 0.080
Steps to 90% of jump, no noise9 · 12
Steps to cross 0.9, with noise11 · 12
Same mean lag and variance: the difference is the shape of the weights. The window forgets abruptly after nn steps; EWMA reacts sooner to the jump but retains a tail that never quite vanishes.
Data with noise deviation 0.25 on a level that jumps at t=60t = 60 and ramps upward from t=110t = 110. Orange is the nn-point moving average; aqua is EWMA. Below on the same axis is each estimator's weight for each observation at the marked instant, with its center of mass (triangles). With ‘span =n= n’ enabled, centers of mass and deviations match: compare responses to the jump. Place the instant just after the jump and inspect the weights. Disable the adjustment and try short and long halflives: what do you gain and lose?

After a jump, the moving average rises linearly and reaches the new level exactly nn steps later, when the last old observation leaves the window. EWMA rises faster initially (more weight on recent values), but approaches the new level geometrically and never fully reaches it: to reach 90% it needs ⌈ln⁡0.1/ln⁡(1−α)⌉\lceil \ln 0.1 / \ln(1-\alpha) \rceil steps, which with n=10n = 10 is 12 versus the window’s 9. On the ramp, the theorem’s first point governs: if xt=a+btx_t = a + bt and weights sum to 1, the estimator is ∑kwk (a+b(t−k))=a+b (t−∑kk wk)\sum_k w_k\,(a + b(t - k)) = a + b\,(t - \sum_k k\,w_k), so both lag the true line by the same distance, b (n−1)/2b\,(n-1)/2: slope times center of mass. The window also has its own flaw: an extreme observation produces two jumps, one on entry and another nn steps later on exit, even if nothing happened then. EWMA forgets smoothly and has no such ghost effect.

Time windows are right for irregular data: rolling("5min") always looks at five minutes, while rolling(5) looks at five ticks, which may be two seconds or an hour. For exponential weighting with irregular timestamps, ewm(halflife="10min", times=s.index) decays each weight by elapsed time, wij=2−(ti−tj)/hw_{ij} = 2^{-(t_i - t_j)/h}; you will implement it in an exercise.

[ ]Inside rolling, expanding, and ewmBrowser
import numpy as np
import pandas as pd
from numpy.lib.stride_tricks import sliding_window_view

pd.set_option("display.width", 120)
rng = np.random.default_rng(0)
x = rng.normal(size=1_000)
n = 20
a = pd.Series(x).rolling(n).mean().to_numpy()
b = sliding_window_view(x, n).mean(axis=1)            # fila i = x[i : i + n]
print("NaN iniciales:", np.isnan(a).sum(), "| iguales:", np.allclose(a[n - 1:], b))

# ventanas por número de observaciones y por tiempo, sobre datos irregulares
t = pd.to_datetime(["2024-01-02 " + h for h in ["09:00", "09:02", "09:05", "09:06", "09:20"]])
s = pd.Series([1.0, 10.0, 100.0, 1000.0, 10000.0], index=t)
print(pd.DataFrame({"x": s, "rolling(2)": s.rolling(2).sum(), "rolling('5min')": s.rolling("5min").sum(),
                    "n": s.rolling("5min").count(), "expanding": s.expanding().sum()}))

# adjust=True frente a adjust=False, escritos a mano
y = pd.Series([1.0, 0.0, 0.0, 4.0])
alfa = 0.5
w = (1 - alfa) ** np.arange(len(y))[::-1]               # pesos de y_0 ... y_3 vistos desde t = 3
print("adjust=True :", y.ewm(alpha=alfa).mean().iloc[-1], (w * y).sum() / w.sum())
m = y.iloc[0]
for v in y.iloc[1:]:
    m = alfa * v + (1 - alfa) * m
print("adjust=False:", y.ewm(alpha=alfa, adjust=False).mean().iloc[-1], m)

# span = n: misma varianza que la media móvil de n (el teorema, comprobado)
ruido = pd.Series(rng.normal(size=200_000))
for n in [5, 20, 60]:
    sd_roll = ruido.rolling(n).mean().std()
    sd_ewm = ruido.ewm(span=n, adjust=False).mean().iloc[1_000:].std()
    print(f"n = {n:2d}: sqrt(n)·sd rolling = {sd_roll * np.sqrt(n):.3f}   sqrt(n)·sd ewm(span=n) = {sd_ewm * np.sqrt(n):.3f}")

The first line connects to the ndarray lesson: rolling(n).mean() gives the same numbers as row means of the sliding-window view, aligned at each window’s end and preceded by n−1n - 1 NaN values. The difference is cost: the strided view copies no memory but row means perform O(Nn)\bigO(Nn) operations, while pandas updates cumulative sums as each observation enters and leaves (with rounding-error compensation) and uses O(N)\bigO(N) for means, variances, and sums. For statistics without cheap updates (median, quantiles), cost grows with the window again.

The time-window table shows the half-open interval (t−w,t](t - w, t]: at 09:05 the five-minute window contains 09:02 and 09:05 but not 09:00, and at 09:20 only its own observation. Windows are estimators with their own bias-variance tradeoff: a long window reduces noise as 1/n1/n but responds late to changes. This is the same tradeoff as the bias-variance decomposition, reappearing in time series when choosing a window to estimate volatility (volatility forecasting).

Simple and logarithmic returns

With prices PtP_t, the simple return and log return for period tt are

Rt=PtPt−1−1,rt=ln⁡PtPt−1=ln⁡(1+Rt).R_t = \frac{P_t}{P_{t-1}} - 1, \qquad r_t = \ln\frac{P_t}{P_{t-1}} = \ln(1 + R_t).

In pandas, p.pct_change() and np.log(p).diff(). Each aggregates well in a different direction:

  • Across time, log returns add. Return from 00 to TT is ∏t(1+Rt)−1\prod_t(1 + R_t) - 1 in simple returns, computed with (1 + R).prod() - 1 or cumprod, and ∑trt\sum_t r_t in log returns, with r.sum() or cumsum. This additivity makes volatility over TT iid periods σT\sigma\sqrt{T} (hence 252\sqrt{252} to annualize daily data) and leads time-series models to usually use log returns.
  • Across assets, simple returns add. A portfolio with weights waw_a has simple return exactly ∑awaRa,t\sum_a w_a R_{a,t}; the portfolio’s log return is not ∑awara,t\sum_a w_a r_{a,t}.

For small returns, r=ln⁡(1+R)=R−R2/2+O(R3)r = \ln(1 + R) = R - R^2/2 + \bigO(R^3), so both measures nearly agree day to day. But this second-order difference accumulates: if RtR_t are iid with small mean μ\mu and variance σ2\sigma^2, E[rt]≈μ−σ2/2\E[r_t] \approx \mu - \sigma^2/2. Actual investment growth is given by the mean of log returns rather than simple returns, and the difference (σ2/2\sigma^2/2) is volatility drag: rising 10% and falling 10% leaves a 1% loss.

[ ]Returns: aggregation across time and assetsBrowser
import numpy as np
import pandas as pd

p = pd.Series([100.0, 110.0, 99.0])
R = p.pct_change()                 # simples: P_t / P_{t-1} - 1
r = np.log(p).diff()               # logarítmicos: log(P_t / P_{t-1})
print("simples:", R.round(5).tolist(), "  log:", r.round(5).tolist())
print("acumulado simple:", (1 + R).prod() - 1, "  log:", r.sum(), "  exp(log) - 1:", np.exp(r.sum()) - 1)

# entre activos se agregan los simples, no los logarítmicos
pesos = np.array([0.5, 0.5])
R_activos = np.array([0.50, -0.40])
print("cartera:", pesos @ R_activos, "  promediando log:", np.exp(pesos @ np.log1p(R_activos)) - 1)

# arrastre de la volatilidad: media aritmética frente a crecimiento real
rng = np.random.default_rng(1)
R = pd.Series(rng.normal(0.0005, 0.02, 252 * 40))
print(f"media simple diaria: {R.mean():.6f}  media log: {np.log1p(R).mean():.6f}  "
      f"media - sigma²/2: {R.mean() - R.var() / 2:.6f}")

With 40 simulated years of daily returns with mean 0.05% and volatility 2%, the mean log return is less than a third of the simple mean, and approximation μ−σ2/2\mu - \sigma^2/2 reproduces it to the sixth digit. Two pandas details: the first return is always NaN (no previous price), and pct_change no longer fills gaps itself (fill_method=None in pandas 3; earlier versions silently forward-filled, deprecated in 2.1). A price NaN produces two NaN returns, that day and the next, which is honest. Returns also have empirical regularities (heavy tails, volatility clustering) studied as stylized facts of returns.

Future leakage

You now have the pieces to state the problem precisely. Every datum has two times: the instant it describes and the instant it is available to you. A closing price refers to the close and is available an instant later; first-quarter GDP refers to January through March and is published weeks later (and revised afterward). Let It\mathcal{I}_t be all records available at instant tt.

Under this definition, each leak in the first figure is a specific violation:

LeakIn codeFuture data used
Execute at the same closesenal * retclose of tt decides the position earning return from t−1t - 1 to tt
Centered windowrolling(5, center=True)the next ⌊(n−1)/2⌋\lfloor (n-1)/2 \rfloor observations
Normalize using whole sample(x - x.mean()) / x.std()mean and deviation of the entire future
Backfill or interpolatebfill(), interpolate()the next observed value
Bars labeled by startresample("5min").last()through interval end
Reference date as use datejoin quarterly GDP on its last daythe entire publication lag
Revised datause current GDP serieslater revisions

Leaks are not equally visible. In the opening figure with 40 simulated markets, executing at the same close or using a centered average gives mean Sharpes of 2.9 and 4.1: no experienced analyst believes them. Global normalization raises mean Sharpe by about 0.7 points over the clean strategy, backfill by about 0.3, improvements anyone might accept as modest but real (and in one market buried in Sharpe’s own ±0.7\pm 0.7 noise). Large leaks invite disbelief; small ones require tests. Global normalization is also the temporal version of a general machine-learning error: fitting any transformation (scaling, imputation, feature selection) on data later used for evaluation, data leakage. Its correct version is expanding, x.expanding(min_periods).mean(), or fitted only on the training segment.

Two tests requiring no case-by-case reasoning

Reviewing every line for leaks does not scale. The causality definition suggests two mechanical metamorphic tests: they do not compare with a correct value (unknown), but require a relation between two runs.

Proof

(1 ⇒ 3) If f(D)t=gt(D≤t)f(D)_t = g_t(D_{\le t}) and D≤t′=D≤tD'_{\le t} = D_{\le t}, then f(D′)t=gt(D≤t′)=gt(D≤t)=f(D)tf(D')_t = g_t(D'_{\le t}) = g_t(D_{\le t}) = f(D)_t. (3 ⇒ 1) Define gt(E)=f(E)tg_t(E) = f(E)_t for any history EE through tt completed arbitrarily; by (3) the value does not depend on how it is completed, so f(D)t=gt(D≤t)f(D)_t = g_t(D_{\le t}). (2) is the special case of (3) with D′=D≤tD' = D_{\le t}, provided ff is defined on truncated data; and (2 ⇒ 1) because f(D≤t)tf(D_{\le t})_t can depend only on D≤tD_{\le t}.

∎

In practice not all D′D' can be tested, so the tests are necessary conditions: a random perturbation may miss exactly what the feature uses from the future (if leakage acts only on missing days, perturb around a gap). But they are cheap and run on every code change like any test. In the next lab you use truncation on a complete bar pipeline; in the exercises you write the perturbation version.

Lab: from ticks to bars without cheating

A synthetic market session: Poisson tick arrivals (one every 4 seconds on average) between 09:00 and 17:30, random-walk prices, and volumes in lots of 100. The pipeline builds one-minute bars with OHLC, volume, tick count, and VWAP, then three features: a 15-bar moving mean, exponential volatility with 10-bar halflife, and expanding volume z-score. The test recalculates everything using ticks known at time TT for twelve random TT and requires the same row TT.

[ ]From ticks to bars without cheatingBrowser
import numpy as np
import pandas as pd

pd.set_option("display.width", 120)
rng = np.random.default_rng(42)
inicio, dur = pd.Timestamp("2024-03-04 09:00"), 8.5 * 3600         # sesión de 09:00 a 17:30
seg = np.cumsum(rng.exponential(4.0, size=int(dur / 4 * 1.2)))      # llegadas de Poisson, una cada 4 s
seg = seg[seg < dur]
ticks = pd.DataFrame({"precio": 50 * np.exp(np.cumsum(rng.normal(0, 3e-4, len(seg)))),
                      "volumen": rng.integers(1, 20, len(seg)) * 100},
                     index=inicio + pd.to_timedelta(seg, unit="s"))
print(len(ticks), "ticks")

def barras(ticks, freq="1min", label="right"):
    r = dict(rule=freq, closed="left", label=label)
    b = ticks["precio"].resample(**r).ohlc()
    b["volumen"] = ticks["volumen"].resample(**r).sum()
    b["n"] = ticks["precio"].resample(**r).count()
    b["vwap"] = (ticks["precio"] * ticks["volumen"]).resample(**r).sum() / b["volumen"]
    return b

def caracteristicas(b):
    f = pd.DataFrame(index=b.index)
    close = b["close"].ffill()                          # una barra sin ticks hereda el último cierre conocido
    ret = np.log(close).diff()
    f["sma_15"] = close.rolling(15).mean()
    f["vol_ewm"] = ret.ewm(halflife=10, min_periods=10).std()
    f["z_volumen"] = (b["volumen"] - b["volumen"].expanding(30).mean()) / b["volumen"].expanding(30).std()
    return f

B = barras(ticks)
print(B.head(3).round(4))
print(caracteristicas(B).dropna().head(3).round(5))

def comprobar_sin_futuro(hacer_barras, n_cortes=12, seed=0):
    """Recalcula todo con los ticks conocidos a la hora T y exige la misma fila T."""
    g = np.random.default_rng(seed)
    completo = caracteristicas(hacer_barras(ticks))
    for i in g.choice(np.arange(40, len(completo) - 1), n_cortes, replace=False):
        T = completo.index[i]
        conocido = ticks[ticks.index <= T]
        parcial = caracteristicas(hacer_barras(conocido)).reindex(completo.index)
        a, b = completo.loc[T].to_numpy(), parcial.loc[T].to_numpy()
        assert np.allclose(a, b, equal_nan=True), f"fuga en la fila {T:%H:%M}: {a.round(4)} frente a {b.round(4)}"

comprobar_sin_futuro(barras)
print("label='right': ninguna fila cambia al quitar el futuro")
try:
    comprobar_sin_futuro(lambda tk: barras(tk, label="left"))
except AssertionError as e:
    print("label='left':", e)

With label="right" all twelve rows match. With label="left" the test fails immediately: the row labeled time TT summarizes the minute starting at TT, and with ticks known then the row cannot even be calculated (it is NaN), while the full pipeline gave it values. Two design details make the test meaningful. First, compare complete feature rows, not just bars: a causal feature over leaking bars inherits the leak. Second, recalculate from ticks, the rawest source, so nothing in the pipeline lies outside the test.

merge_asof: joining asynchronous series

The last piece is combining sources that do not share timestamps: trades and quotes of the same asset, intraday prices and an indicator published once daily, features from different providers. An exact join (merge by equal date) almost never finds a match; for each left row we want the last right-side datum available at that moment.

pd.merge_asof(left, right, on="t", by="activo", tolerance=..., direction="backward") requires both tables sorted by on. Only direction="backward" is causal; forward and nearest are useful for evaluation (what was the price 5 seconds after my order?) and cause leakage if used to build features. Tolerance prevents another silent error: without it, a 16:00 trade could receive a 09:00 quote if the asset stopped trading, and stale data enter the model as current.

The important subtlety is which column is used as on. If quotes carry exchange time but reach your system 250 ms later, joining on exchange time assigns some trades quotes you had not yet received at trade time. This is the same leak as joining first-quarter GDP dated March 31 when it was not published until late April. Always join by availability instant: add an arrival or publication time column (if only the reference period is known, add a conservative publication lag) and use it as on.

Interactivemerge_asof step by step
pd.merge_asof(trades, quotes, on="t_bolsa", direction="backward")
quotes (right): exchange time ○ → arrival time ●trades (left)10.0010.0210.0510.0110.0310.08NaN10.0210.0210.0510.0110.0310.080 s5 s10 s15 s20 s25 s30 s
  • trade (assigned bid below)
  • quote
  • valid join
  • join using future information
merge_asof
direction
Arrival delay
0.75
Trades with a quote6 of 7
Use a quote not yet received2
Mean age of quote used3.55 s
A backward join by exchange time: quotes arrive late and some trades use one not yet in your system. Join by arrival time.
Above, six quotes: the hollow circle is exchange time and filled circle their arrival time in your system. Below, seven trades, each with the bid assigned by the join. Initially it joins backward by exchange time with 0.75 s delay: two matches are red even though direction is backward. Enable ‘Join by arrival time’ and observe which quote the trade at t=4t = 4 now receives. Then try forward and nearest, disable allow_exact_matches, and add tolerance: which trades have no match and why is that correct?

Lab: merge_asof from scratch

The definition translates directly to binary search. For each aia_i, np.searchsorted(b, a_i, side="right") returns the number of bj≤aib_j \le a_i, so subtracting 1 yields j∗(i)j^*(i), or −1-1 if none; side="left" counts bj<aib_j < a_i, corresponding to allow_exact_matches=False. This is the same tool as indirect sorting and searching sorted arrays, vectorized across all left rows at once: O(mlog⁡k)\bigO(m \log k). For grouping by key, repeat within each group, since a subset of a sorted table remains sorted.

[ ]merge_asof from scratchBrowser
import numpy as np
import pandas as pd

def asof_indices(t_left, t_right, tolerance=None, allow_exact_matches=True):
    """Para cada t de t_left, índice de la última fila de t_right con t_right <= t (o < t); -1 si no hay."""
    lado = "right" if allow_exact_matches else "left"
    j = np.searchsorted(t_right, t_left, side=lado) - 1
    ok = j >= 0
    if tolerance is not None:
        ok &= (t_left - t_right[np.maximum(j, 0)]) <= tolerance
    return np.where(ok, j, -1)

def merge_asof_np(left, right, on, by=None, tolerance=None, allow_exact_matches=True):
    """Unión as-of hacia atrás. left y right ordenados por `on`; columnas de right numéricas."""
    cols = [c for c in right.columns if c not in (on, by)]
    out = {c: np.full(len(left), np.nan) for c in cols}
    if by is None:
        grupos = [(np.arange(len(left)), np.arange(len(right)))]
    else:
        filas_r = right.groupby(by, sort=False).indices          # clave -> posiciones (en orden)
        grupos = [(li, filas_r[k]) for k, li in left.groupby(by, sort=False).indices.items() if k in filas_r]
    tl_all, tr_all = left[on].to_numpy(), right[on].to_numpy()
    for li, ri in grupos:
        j = asof_indices(tl_all[li], tr_all[ri], tolerance, allow_exact_matches)
        hit = j >= 0
        for c in cols:
            out[c][li[hit]] = right[c].to_numpy(dtype=float)[ri[j[hit]]]
    res = left.copy()
    for c in cols:
        res[c] = out[c]
    return res

# datos sintéticos: tres activos, cotizaciones y operaciones en instantes irregulares durante una hora
rng = np.random.default_rng(5)
inicio = pd.Timestamp("2024-03-04 09:00")
def instantes(n, dur_s=3600):
    return inicio + pd.to_timedelta(np.sort(rng.uniform(0, dur_s, n)), unit="s")
quotes = pd.DataFrame({"t": instantes(4000), "sym": rng.choice(["AAA", "BBB", "CCC"], 4000)})
quotes["mid"] = 50 + rng.normal(0, 0.01, len(quotes)).cumsum()
quotes["spread"] = rng.choice([0.01, 0.02, 0.03], len(quotes))
trades = pd.DataFrame({"t": instantes(2000), "sym": rng.choice(["AAA", "BBB", "CCC"], 2000)})
trades["qty"] = rng.integers(1, 10, len(trades)) * 100

for kw in [dict(), dict(tolerance=pd.Timedelta("2s")), dict(allow_exact_matches=False)]:
    ref = pd.merge_asof(trades, quotes, on="t", by="sym", **kw)
    mio = merge_asof_np(trades, quotes, on="t", by="sym",
                        tolerance=kw.get("tolerance"), allow_exact_matches=kw.get("allow_exact_matches", True))
    iguales = all(np.allclose(ref[c], mio[c], equal_nan=True) for c in ["mid", "spread"])
    print(f"{str(kw):45s} iguales: {iguales}   sin cotización: {mio['mid'].isna().sum()}")

# aplicación: las cotizaciones llegan a tu sistema 250 ms después de su hora de bolsa
quotes["llegada_s"] = (quotes["t"] - inicio).dt.total_seconds() + 0.25
t_trade_s = (trades["t"] - inicio).dt.total_seconds().to_numpy()
por_bolsa = merge_asof_np(trades, quotes, on="t", by="sym")
print("unión por hora de bolsa:   usa una cotización aún no recibida en",
      f"{np.mean(por_bolsa['llegada_s'].to_numpy() > t_trade_s):.1%} de las operaciones")
q_llegada = quotes.assign(t=inicio + pd.to_timedelta(quotes["llegada_s"], unit="s"))
por_llegada = merge_asof_np(trades, q_llegada, on="t", by="sym")
print("unión por hora de llegada: usa una cotización aún no recibida en",
      f"{np.mean(por_llegada['llegada_s'].to_numpy() > t_trade_s):.1%} de las operaciones")

All three variants match pandas, including inclusive tolerance (ai−bj∗≤τa_i - b_{j^*} \le \tau is accepted). With 2 seconds’ tolerance, nearly half the trades have no quote: with about 1300 quotes per asset per hour, mean quote gap is nearly 3 seconds. The application quantifies the figure’s leakage: with only 250 ms latency, almost 9 in 100 trades (8.6%) would have used a quote not yet received. This is expected: with mean gap 2.7 s between quotes for an asset, probability the last arrived in the preceding 250 ms is 1−e−0.25/2.7≈0.091 - e^{-0.25/2.7} \approx 0.09. For a model predicting the next trade’s sign, that 9% suffices to invent an edge.

Common mistakes

Exercises

NumericCumulative log return
A price goes from 100 to 110 and then 99. What is the cumulative log return over both periods?
NumericHow much noise passes through an EWMA
A series is white noise with standard deviation 1. Apply ewm(halflife=10, adjust=False).mean() and examine it far from startup. What is the result's standard deviation?

The next four snippets calculate a daily position from pandas series with a business-day index: precio, ret = precio.pct_change(), and, in C, a fundamentales table with one row per quarter dated the last day of the quarter described by the data (companies publish results four to six weeks later).

# A
z = (precio - precio.rolling(60).mean()) / precio.rolling(60).std()
posicion_A = np.sign(z).shift(1)

# B
vol = ret.rolling(20, center=True).std()
posicion_B = (0.10 / vol).clip(upper=3).shift(1)

# C
beneficio = fundamentales["beneficio"].reindex(precio.index, method="ffill")
posicion_C = np.sign(beneficio.pct_change(63)).shift(1)

# D
media, desv = ret.expanding(250).mean(), ret.expanding(250).std()
posicion_D = ((ret - media) / desv).clip(-2, 2).shift(1)
QuizWhich see the future?
Which snippets use information unavailable when taking the position? Select all with leakage.

More than one answer may be correct.

QuizLocal times on an October night
You have sorted naive Madrid local times (no zone), recorded every 30 minutes and including the night of October 27, 2024. You want UTC. What is correct?
QuizBars usable at their timestamp
You will build 5-minute bars with resample and join them to orders sent at the exact time of each label. Which combination guarantees each bar contains only ticks strictly before its label?
QuizThe macro datum and its date
A monthly indicator is dated on the last day of its reference month and published about 15 days later. You join it to daily prices with pd.merge_asof(precios, indicador, on='fecha'). What happens?
CodeEWMA with irregular timestamps
Implement ewm_irregular(x, t, halflife): the exponential mean with adjust=True where observation jj's weight viewed from ii is 2−(ti−tj)/h2^{-(t_i - t_j)/h}, where t gives increasing instants in seconds and halflife is the halflife in seconds. It must match pd.Series(x).ewm(halflife=pd.Timedelta(seconds=h), times=...).mean(), traverse the data once (O(n)\bigO(n)), and not overflow even when the series spans millions of halflives.
import numpy as np

def ewm_irregular(x, t, halflife):
  """EWMA (adjust=True) con decaimiento según el tiempo transcurrido entre observaciones."""
  x = np.asarray(x, dtype=float)
  t = np.asarray(t, dtype=float)
  out = np.zeros_like(x)
  # tu código: mantén un numerador y un denominador y hazlos decaer con el tiempo transcurrido
  return out
Shift+Enter to run
CodeA perturbation-based leakage detector
Implement check_no_lookahead(feature_fn, df, seed=0). df is a numeric DataFrame with a sorted time index (possibly containing NaN) and feature_fn(df) returns a Series or DataFrame with the same index. For each row ii (except the last), construct a copy of df where all rows after ii are perturbed (for example, adding noise proportional to their magnitude so NaN values remain NaN), recalculate features and compare row ii with the original (np.allclose with equal_nan=True). Return False as soon as any row changes and True if none change. Do not modify the input df.
import numpy as np
import pandas as pd

def check_no_lookahead(feature_fn, df, seed=0):
  """True si ninguna fila de feature_fn(df) cambia al perturbar los datos posteriores a ella."""
  rng = np.random.default_rng(seed)
  base = feature_fn(df.copy())
  # tu código: para cada fila i, perturba df.iloc[i + 1:], recalcula y compara la fila i
  return True
Shift+Enter to run

Summary

Key idea
Each time-series value carries an implicit question: was this known at the instant on its label? Almost every pandas time tool has a parameter that can silently answer “no,” so build with causal conventions and check with tests perturbing or removing the future.
  • A Timestamp identifies an instant only with a zone. tz_localize interprets wall times (where daylight-saving ambiguous and nonexistent times arise); tz_convert translates instants. Calculate in UTC. Timedelta is a duration and DateOffset a calendar rule.
  • resample is a groupby over intervals [bk,bk+1)[b_k, b_{k+1}) or (bk,bk+1](b_k, b_{k+1}]. To join bars with decisions, label them by their end: closed="left", label="right". Forward-fill when upsampling; interpolation and bfill use the future.
  • rolling (by count or time), expanding, and ewm are causal estimators except with center=True. An EWMA of span nn has the same mean delay, (n−1)/2(n - 1)/2, and variance, σ2/n\sigma^2/n, as the nn-point moving average; they differ in response to changes.
  • Log returns add across time; simple returns across assets. Mean log return is mean simple return minus drag σ2/2\sigma^2/2.
  • A feature is causal if truncating or perturbing the future does not change it: this equivalence provides automatic tests detecting large and small leaks.
  • Backward merge_asof joins each row with the last earlier datum, by group and with tolerance, using binary search with searchsorted. Always join by the datum’s availability instant, rather than reference time.