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 with independent . 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.
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 by the return from close to close : to hold that position during the day, it would have had to be decided at close , when the price at 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.
All four leaks share a structure: a value dated depends on something after . 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”:
| Object | What it represents | Example |
|---|---|---|
Timestamp | an instant | pd.Timestamp("2024-03-30 12:00", tz="Europe/Madrid") |
Timedelta | an absolute duration | pd.Timedelta(hours=1), pd.Timedelta("90s") |
DateOffset | a calendar offset | pd.DateOffset(months=1), pd.offsets.BDay(3) |
Period | a named interval | pd.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 contains the value from . 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.
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:
| Alias | Meaning | Alias | Meaning |
|---|---|---|---|
"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-, nanosecond | CustomBusinessDay(...) | 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.
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, with closed="left" or 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?
The figure gives three conclusions:
labeldetermines causality. Withlabel="left", the label is the interval start and almost everything in it is later. Withlabel="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.”closeddecides boundaries. Withclosed="left"the 09:05:00 tick opens the next bar; withclosed="right"it closes the previous one. Withclosed="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.- Empty bars exist. If an interval has no ticks,
resampleproduces a row withNaN(or0forsumandcount). Removing it shifts everything calculated afterward by position.
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, 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 , weighted , more than its share. They agree when is negligible. pandas accepts four equivalent parameterizations of the same :
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 has the same mean delay as an -point moving average (and, as a bonus, the same variance).
Proof
The moving average has weights for : center of mass and variance . Stationary EWMA has weights , , summing to 1 (hence no bias). Its center of mass is
which with is . Its variance is
and since , this is .
∎The theorem explains the name com, because is exactly the center of mass, and says that in stationary noise, a window and exponential with span are indistinguishable by their first two moments. Their weights’ shape separates them, noticeable only when the series changes.
After a jump, the moving average rises linearly and reaches the new level exactly 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 steps, which with is 12 versus the window’s 9. On the ramp, the theorem’s first point governs: if and weights sum to 1, the estimator is , so both lag the true line by the same distance, : slope times center of mass. The window also has its own flaw: an extreme observation produces two jumps, one on entry and another 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, ; you will implement it in an exercise.
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 NaN values. The difference is cost: the strided view copies no memory but row means perform operations, while pandas updates cumulative sums as each observation enters and leaves (with rounding-error compensation) and uses 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 : 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 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 , the simple return and log return for period are
In pandas, p.pct_change() and np.log(p).diff(). Each aggregates well in a different direction:
- Across time, log returns add. Return from to is in simple returns, computed with
(1 + R).prod() - 1orcumprod, and in log returns, withr.sum()orcumsum. This additivity makes volatility over iid periods (hence to annualize daily data) and leads time-series models to usually use log returns. - Across assets, simple returns add. A portfolio with weights has simple return exactly ; the portfolio’s log return is not .
For small returns, , so both measures nearly agree day to day. But this second-order difference accumulates: if are iid with small mean and variance , . Actual investment growth is given by the mean of log returns rather than simple returns, and the difference () is volatility drag: rising 10% and falling 10% leaves a 1% loss.
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 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 be all records available at instant .
Under this definition, each leak in the first figure is a specific violation:
| Leak | In code | Future data used |
|---|---|---|
| Execute at the same close | senal * ret | close of decides the position earning return from to |
| Centered window | rolling(5, center=True) | the next observations |
| Normalize using whole sample | (x - x.mean()) / x.std() | mean and deviation of the entire future |
| Backfill or interpolate | bfill(), interpolate() | the next observed value |
| Bars labeled by start | resample("5min").last() | through interval end |
| Reference date as use date | join quarterly GDP on its last day | the entire publication lag |
| Revised data | use current GDP series | later 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 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 and , then . (3 ⇒ 1) Define for any history through completed arbitrarily; by (3) the value does not depend on how it is completed, so . (2) is the special case of (3) with , provided is defined on truncated data; and (2 ⇒ 1) because can depend only on .
∎In practice not all 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 for twelve random and requires the same row .
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 summarizes the minute starting at , 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.
Lab: merge_asof from scratch
The definition translates directly to binary search. For each , np.searchsorted(b, a_i, side="right") returns the number of , so subtracting 1 yields , or if none; side="left" counts , 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: . For grouping by key, repeat within each group, since a subset of a sorted table remains sorted.
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 ( 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 . For a model predicting the next trade’s sign, that 9% suffices to invent an edge.
Common mistakes
Exercises
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)
More than one answer may be correct.
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?pd.merge_asof(precios, indicador, on='fecha'). What happens?ewm_irregular(x, t, halflife): the exponential mean with adjust=True where observation 's weight viewed from is , 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 (), 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 outcheck_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 (except the last), construct a copy of df where all rows after are perturbed (for example, adding noise proportional to their magnitude so NaN values remain NaN), recalculate features and compare row 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 TrueSummary
- A
Timestampidentifies an instant only with a zone.tz_localizeinterprets wall times (where daylight-saving ambiguous and nonexistent times arise);tz_converttranslates instants. Calculate in UTC.Timedeltais a duration andDateOffseta calendar rule. resampleis a groupby over intervals or . To join bars with decisions, label them by their end:closed="left", label="right". Forward-fill when upsampling; interpolation andbfilluse the future.rolling(by count or time),expanding, andewmare causal estimators except withcenter=True. An EWMA of span has the same mean delay, , and variance, , as the -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 .
- 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_asofjoins each row with the last earlier datum, by group and with tolerance, using binary search withsearchsorted. Always join by the datum’s availability instant, rather than reference time.