Skip to content
LeetQuant
QR07 Financial Data and Feature Engineering

QR07 · Financial Data and Feature Engineering · Lesson 1 of 5

Financial Datasets and Their Quirks

What prices, bars, ticks, quotes, fundamentals and alternative data actually record, the errors each one carries (survivorship, stale prices, bad ticks, bid-ask bounce), and when to use log or simple returns.

16 min

Objective

A research interview often starts with "here is some data, what would you check before using it?". You should be able to say what each common dataset records, which errors it carries by construction, how those errors bias a statistic in a known direction, and which kind of return to compute.

What the common datasets record

DatasetOne row isTypical traps
Daily pricesOpen, high, low, close, volume per instrument per dayClose is an auction price on some venues and a last trade on others; unadjusted for splits and dividends
BarsOHLCV over a fixed interval (1 min, 5 min) or a fixed volumeEmpty bars in quiet periods; the bar's timestamp may mark its start or its end
Trades (ticks)One execution: time, price, size, venue, condition codesOdd lots, late reports, cancelled and corrected prints, off-exchange trades
QuotesA change in the best bid or askFar more rows than trades; crossed or locked quotes; quote stuffing
FundamentalsA reported accounting number for a fiscal periodReleased weeks after the period ends; later restated (lesson 4)
Alternative dataCard spending, web traffic, satellite counts, textShort history, changing panel of users, vendor backfill

Bars vs ticks. Bars are a lossy summary: they keep four prices and a volume and throw away the order of events inside the interval. Time bars are uneven in information (a 1-minute bar at the open holds far more trading than one at 12:30). Volume or dollar bars sample every fixed amount of trading instead, which makes returns closer to identically distributed. Whatever the bar, find out whether a bar labelled 10:00 covers 09:59 to 10:00 or 10:00 to 10:01: getting this wrong shifts every feature by one bar, which is a look-ahead of one period.

Quotes vs trades. A trade price is either at the bid (a seller hit it) or at the ask (a buyer lifted it). Even if the mid-price never moves, trade prices bounce between bid and ask, so consecutive trade-to-trade returns are negatively autocorrelated. Roll's model makes this exact: with spread ss and trades equally likely at either side, independent of each other and of the mid,

Cov⁡(Δpt,Δpt−1)=−s24,s=2−Cov⁡(Δpt,Δpt−1).\operatorname{Cov}(\Delta p_t, \Delta p_{t-1}) = -\frac{s^2}{4}, \qquad s = 2\sqrt{-\operatorname{Cov}(\Delta p_t, \Delta p_{t-1})} .

Use the quote mid-price when you want the "true" price path; use trades when you want what was actually paid.

Three errors with a known direction

  1. Survivorship. A universe of today's listed names drops everything that went bankrupt or was acquired. Average returns are biased upward, most for strategies that buy recent losers. The fix is a point-in-time universe with delisted names and their final returns (lessons 3 and 4).
  2. Stale prices. An illiquid asset that does not trade on a day reports the previous close, giving a zero return followed by a catch-up. Contemporaneous correlations and betas are biased towards zero, and the asset appears to lag the market. Sums over lags (Dimson betas) undo most of the bias. Month-end marks on private assets show the same effect: smoothed returns understate volatility and correlation.
  3. Bad ticks. A print at 5.011 in a stock trading at 50.10 (a misplaced decimal), a fat-finger trade, a zero price. One such tick creates a −90%-90\% return followed by a +900%+900\% one and can dominate a variance estimate. Filter against a robust trailing reference such as the median of the previous few prints, not against the mean, which the bad tick itself contaminates.

Worked example

a trailing-median bad-tick filter

Minute prints for a stock are 50.10, 50.12, 50.08, 5.011, 50.15, 50.11, 50.20. Flag any print more than 5% away from the median of the previous five prints. Why trailing rather than centred?

Show solution
import pandas as pd

px = pd.Series([50.10, 50.12, 50.08, 5.011, 50.15, 50.11, 50.20],
               index=pd.date_range("2024-03-04 10:00", periods=7, freq="min"))
# Reference = median of the previous 5 prints (trailing, so usable live)
ref = px.rolling(5, min_periods=1).median().shift(1)
dev = (px / ref - 1).abs()
print(pd.DataFrame({"px": px, "ref": ref, "dev": dev.round(4)}))
print(px[dev > 0.05])

Output:

                         px    ref     dev
2024-03-04 10:00:00  50.100    NaN     NaN
2024-03-04 10:01:00  50.120  50.10  0.0004
2024-03-04 10:02:00  50.080  50.11  0.0006
2024-03-04 10:03:00   5.011  50.10  0.9000
2024-03-04 10:04:00  50.150  50.09  0.0012
2024-03-04 10:05:00  50.110  50.10  0.0002
2024-03-04 10:06:00  50.200  50.11  0.0018
2024-03-04 10:03:00    5.011
Freq: min, dtype: float64

Only the 10:03 print is flagged. Note that the reference at 10:04 is still 50.09 even though the bad print is inside its window: the median ignores one outlier among five, while a trailing mean would have dropped to about 38.8 and flagged the good print at 10:04 as well (it is 29% above that mean).

A centred window (prints before and after) cleans historical data slightly better, because it can tell a bad tick from a genuine jump that persists. But it uses future prints, so a backtest built on centred-cleaned data has quietly used information the live system will not have. If you clean offline with a centred filter, measure how often the live trailing filter would have disagreed.

Log or simple returns

For a price PtP_t (with dividends handled as in lesson 3):

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) .

The rule of thumb that settles most questions:

  • Log returns add over time. The return from 00 to TT is ∑trt\sum_t r_t. Rolling-window sums, horizon returns and time-series models are natural in logs.
  • Simple returns add across assets. A portfolio with weights wiw_i earns Rp=∑iwiRiR_p = \sum_i w_i R_i exactly; the weighted average of log returns is not the portfolio's log return.

The two agree to first order: r=R−R2/2+…r = R - R^2/2 + \dots, so for a daily move of 1% the gap is about 0.5 basis points, while for a 50% move it is large. If rr is normal with mean μ\mu and variance σ2\sigma^2, the expected gross simple return is E[1+R]=eμ+σ2/2\mathbb{E}[1+R] = e^{\mu + \sigma^2/2}, so a positive expected simple return is compatible with a negative expected log return.

import numpy as np, pandas as pd

prices = pd.Series([100.0, 150.0, 100.0])
simple = prices.pct_change().dropna()
logr = np.log(prices).diff().dropna()
print(simple.round(4).tolist(), round(simple.mean(), 4))
print(logr.round(4).tolist(), round(logr.sum(), 4))
[0.5, -0.3333] 0.0833
[0.4055, -0.4055] 0.0

The price ends where it started, yet the arithmetic mean of simple returns is +8.33%+8.33\% per period. The log returns sum to zero, which is the correct compounded answer. Across assets the error runs the other way: a 50/50 portfolio of one stock that rose 50% and one that fell 50% returned exactly 00, but the average of their log returns is (0.4055−0.6931)/2=−0.1438(0.4055 - 0.6931)/2 = -0.1438, which would claim a −13.4%-13.4\% return.

Worked example

how stale prices bias correlation

Stocks A and B have true daily returns with correlation ρ=0.8\rho = 0.8 and equal volatility. A trades every day. B fails to trade on a random 40% of days (independently each day), and on those days its recorded close is the previous one. What correlation do you measure between the recorded daily returns on the same day, and between A yesterday and B today?

Show solution

Let p=0.4p = 0.4 be the no-trade probability. On a day B trades, its recorded return is the sum of all true returns since its last trade. On a day it does not trade, its recorded return is 00.

Variance of B is unchanged. Every true return shows up in exactly one recorded return. Given a trade, the number of days accumulated is geometric with mean 1/(1−p)1/(1-p), so E[recorded2]=(1−p)⋅11−pσ2=σ2\mathbb{E}[\text{recorded}^2] = (1-p)\cdot\frac{1}{1-p}\sigma^2 = \sigma^2.

Same-day covariance. A's return today appears in B's recorded return today only if B trades today, probability 1−p1-p. So the same-day correlation is (1−p)ρ=0.6×0.8=0.48(1-p)\rho = 0.6 \times 0.8 = 0.48.

Lag-one covariance. A's return yesterday appears in B's recorded return today only if B did not trade yesterday and does trade today: probability p(1−p)=0.24p(1-p) = 0.24. Correlation 0.24×0.8=0.1920.24 \times 0.8 = 0.192.

In general lag kk carries (1−p)pkρ(1-p)p^k\rho, and the sum over all lags is ρ\rho. That is why summing betas over a few lags recovers the true exposure. A simulation agrees:

import numpy as np, pandas as pd

rng = np.random.default_rng(7)
n = 20_000
true = pd.DataFrame(rng.normal(0, 0.01, size=(n, 1)) + rng.normal(0, 0.005, size=(n, 2)),
                    columns=["A", "B"])          # common factor + noise
logp = true.cumsum()
# B does not trade on 40% of days: its recorded close is yesterday's.
stale = rng.random(n) < 0.4
logp_obs = logp.copy()
logp_obs.loc[stale, "B"] = np.nan
logp_obs["B"] = logp_obs["B"].ffill()
obs = logp_obs.diff().dropna()

print("true  corr:", round(true["A"].corr(true["B"]), 3))
print("obs   corr:", round(obs["A"].corr(obs["B"]), 3))
print("lag   corr:", round(obs["A"].shift(1).corr(obs["B"]), 3))
print("true sd B :", round(true["B"].std(), 5), " obs sd B:", round(obs["B"].std(), 5))
print("zero-return days in B:", round((obs["B"] == 0).mean(), 3))
true  corr: 0.798
obs   corr: 0.483
lag   corr: 0.189
true sd B : 0.01108  obs sd B: 0.01109
zero-return days in B: 0.397

The interview point: a run of exact-zero returns is a data-quality signal, and any lead-lag "signal" from a liquid asset to an illiquid one should first be explained by stale prices before it is called alpha.

Knowledge check

You hold 30% in stock X and 70% in stock Y for one day. Which calculation gives the portfolio's return exactly?

Knowledge check

The mid-price of a stock is constant, but trade prices alternate randomly between bid and ask. The autocovariance of consecutive trade-price changes is −0.0009-0.0009 (prices in dollars). Under Roll's model, what is the bid-ask spread?

Knowledge check

You regress the daily returns of a thinly traded small-cap index on same-day S&P 500 returns. Compared with its true market beta, the estimated beta is most likely:

Key takeaways

  • Know what one row means: a bar's timestamp convention, a trade's condition codes, a fundamental's release date.
  • Trade prices bounce between bid and ask; use mids for price paths. Roll: s=2−Cov⁡s = 2\sqrt{-\operatorname{Cov}}.
  • Survivorship biases returns up; stale prices bias correlations and betas towards zero and create fake lead-lag; bad ticks blow up variances.
  • Clean with robust, trailing references (medians), or know that a centred filter has used the future.
  • Log returns add over time; simple returns add across assets.

Practice problems

Finished reading?

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