Point-in-Time Market Data Pipeline for Backtesting
Medium · System Design · Data Engineer · Technical Screen
Prompt
Your team maintains the historical market-data platform for a systematic equities desk that ingests daily end-of-day feeds from several external data providers. Quantitative researchers have noticed that re-running the exact same historical simulation after a weekend ingestion job often produces noticeably different return series and Sharpe ratios. Architect a point-in-time data pipeline and debugging workflow that eliminates look-ahead leakage and makes every historical simulation strictly reproducible.
Your design must satisfy the following requirements and operational constraints:
- Strict as-of visibility: When a simulation evaluates a trading decision on a historical timestamp, it must only observe market records, corporate events, and mappings that had physically arrived in the platform by that moment.
- Historical instrument resolution: Upstream providers identify listings using different symbols (such as exchange tickers and SEDOLs) that change across renames, delistings, ticker recycling, mergers, and spin-offs. Map external symbols deterministically onto a permanent internal instrument identifier across time.
- Retroactive restatements & lineage: Providers periodically revise past records—for instance,
Feed Alphamay deliver a restatement in August changing symbolKLM's2026-05-12closing price from78.40to79.15. Store and trace every historical revision without corrupting earlier as-of views. - Fast post-refresh root-cause attribution: When a researcher's simulation metrics shift between Friday evening and Monday morning, provide a systematic way to isolate whether the discrepancy stems from strategy/engine code changes, upstream data restatements, or pipeline cleaning rule updates.
- Scale, latency, and stale quotes: Support daily updates across roughly
50,000global equities with fast multi-year historical reads while prioritizing point-in-time accuracy above raw query speed, and explicitly handle stale quotes where a provider repeats the prior session's close during an exchange holiday or feed outage.
Scope & Expectations
- Bitemporal storage & ingestion architecture: Define how raw files, versioned records, valid dates, and system-receipt timestamps are modeled so historical queries never leak future revisions or split adjustments.
- Time-aware security master & corporate-action lineage: Show how external tickers and SEDOLs resolve to internal identifiers across symbol reuse, delistings, mergers, and spin-offs.
- Data quality gates & staleness handling: Explain how holiday repeats, missing feeds, and upstream outlier spikes are detected and quarantined before reaching researchers.
- Reproducibility & regression attribution: Detail how snapshots, run metadata, and diff tooling pinpoint the exact source of a Monday-morning backtest discrepancy.
Step-by-step walkthrough
Clarify requirements and define point-in-time correctness
When researchers complain that their backtest (a historical simulation of a trading strategy) changes its Sharpe ratio (annualized average excess return divided by return volatility—a measure of risk-adjusted return) after a weekend data refresh, two distinct bugs are hiding underneath:
- Look-ahead bias: A simulated trading decision on
2015-03-10accidentally reads information nobody physically had on2015-03-10—such as a vendor price correction delivered three months later, a stock split from 2020 baked into 2015 price levels, or a stock list built from companies that survived until today (survivorship bias). This makes backtests look artificially profitable. - Irreproducibility: Re-running the exact same strategy on Monday morning yields different numbers from Friday evening because raw vendor rows, identifier mappings, or cleaning rules were overwritten in place, leaving no way to reproduce Friday's run or pinpoint what moved.
Settle the core time vocabulary up front, because every table and query depends on three distinct clocks:
valid time The market date a fact describes (e.g., trade_date = 2026-05-12 for a closing price). knowledge time When our pipeline physically received and published that version (known_from in UTC)— stamped by OUR clock, never trusting the provider's claimed timestamp. decision time The simulated UTC instant when the strategy places trades (e.g., 2026-05-13 09:30 ET). THE IRON RULE A decision at time t on calendar date D may ONLY read rows with: known_from <= t AND trade_date <= DScope assumptions from clarifying questions: - Universe & feeds: Daily end-of-day prices, volumes, corporate actions, and security identifiers for ~50,000 active global equities across 3 vendors, spanning 20 years of history (intraday tick data is out of scope). - Publish cadence: Three scheduled publish runs per day—shortly after the Asia-Pacific, Europe, and Americas market closes—holding back corrupted batches rather than publishing bad numbers. - Query latency vs. safety: Correctness is the top priority (point-in-time is the mandatory default; non-point-in-time exploratory reads require an explicit opt-out flag and watermark), while loading 10 years of daily data for 3,000 stocks should take seconds.
- Look-ahead bias: A simulated trading decision on
Back-of-the-envelope numbers: why keeping every version is cheap
1. Historical Data Volume (20 Years) Active securities: ~50,000/day (plus delisted historical names) Trading days: ~252 days/year * 20 years = ~5,000 days Security-days per vendor: 50,000 * 5,000 = ~250,000,000 rows Raw rows across 3 vendors: ~750,000,000 rows Uncompressed size: ~20 numeric fields * 8 B = ~160 B/row -> ~120 GB raw (~40 GB golden) Compressed Parquet storage: 3x-5x columnar compression -> ~25-40 GB raw, ~8-15 GB golden! 2. Daily Ingestion & Version Overhead New daily rows: 50,000 * 3 vendors = 150,000 rows/day (~25 MB/day) Historical corrections: ~0.1%-1% of rows (~150-1,500 rows/day) + occasional bulk restatements Cost of immutable versions: If 1% of security-days are ever revised, keeping EVERY version forever adds ~1% storage (~150 MB over 20 years—practically free!) 3. Typical Backtest Scan Size 10 years * 3,000 stocks * 10 float64 fields = ~75.6M floats = ~605 MB in RAM (loads in < 3 s) 10 years * 50,000 stocks * 10 fields = ~1.26B floats = ~10.1 GB (column-pruned scan)Headline takeaway: 15 GB of golden columnar data fits on a laptop. Scale is not the bottleneck here—bitemporal modeling, deterministic identifier lineage, and reproducible snapshotting are where the engineering lives.
Research data API and the backtest run manifest
Researchers never query mutable raw vendor tables directly. Every read goes through a single library whose defaults enforce point-in-time safety:
panel = data.get_panel( fields=["close", "volume"], universe="global_liquid_3000", # universe membership is evaluated point-in-time too! start="2015-01-01", end="2024-12-31", mode="point_in_time", # default; "snapshot" sees corrections up to cutoff snapshot_id="snap-2026-08-17T02:00Z", # pins physical bytes; defaults to latest published decision_time="09:30 America/New_York", # converted per date to exact UTC timestamp t adjust="as_of_decision", # applies only splits/dividends known by time t fill="none", # or "ffill_max_3d", which also returns is_filled mask )Supporting lineage and debugging calls:
resolve(vendor, id_type, id_value, on_date, known_at) -> permanent security_id (or UNMAPPED) versions(security_id, field, trade_date) -> full version chain + file SHA-256 + reason diff(snapshot_a, snapshot_b, universe, start, end) -> exact cell-level differences between runsEvery backtest execution automatically writes an immutable run manifest to the run registry so Friday's and Monday's runs can be compared mechanically:
run_id: r-81723 code_commit: 3f9c2e1 (+ container image digest + Python lockfile SHA-256) config_hash: sha256 of strategy hyperparameters methodology: golden_rules=v7, adjustments=v3, universe_rules=v2 snapshot_id: snap-2026-08-17T02:00Z (knowledge cutoff + physical Iceberg table snapshot IDs) mode & seed: point_in_time @ 09:30 America/New_York, random_seed=42 outputs: daily per-security PnL, positions, Sharpe, total return, turnoverBitemporal, append-only data model
A bitemporal data model tracks two time dimensions on every record: valid time (
trade_date, when the event happened in the market) and transaction / knowledge time (known_from, when our system recorded it). Every table is strictly append-only: an upstream correction inserts a new row rather than updating the old one.file_receipts file_id, vendor, s3_uri, sha256, received_at, row_count, status (ACCEPTED | QUARANTINED) raw_vendor_prices vendor, vendor_key (raw ticker/SEDOL), trade_date, open, high, low, close, volume, vendor_last_trade_date, vendor_pub_time, received_at, file_id, row_hash security_master security_id (opaque permanent surrogate ID, never reused), issuer_id, primary_exchange, currency, first_trade_date, last_trade_date, delisting_reason, known_from identifier_map vendor, id_type (VENDOR_ID | SEDOL | ISIN | TICKER), id_value, exchange, security_id, valid_from, valid_to (exclusive), known_from corporate_actions action_id, security_id, action_type (SPLIT | CASH_DIV | MERGER | SPINOFF | DELIST), announce_date, ex_date, ratio, cash_amount, target_security_id, known_from golden_prices security_id, trade_date, open, high, low, close, volume, last_trade_date, is_stale, is_deleted, source_vendor, source_row_hash, rule_version, revision_reason, known_from, knowledge_source (CAPTURED | VENDOR_PIT | MODELED) -- UNIQUE KEY: (security_id, trade_date, rule_version, known_from) snapshots snapshot_id, cutoff_utc, iceberg_table_versions_json, quality_report_id, statusHere is how a retroactive restatement from
Feed Alphaarriving in August for a May trade date is stored without corrupting past backtests:security_id trade_date close rule_version known_from revision_reason ----------- ---------- ----- ------------ -------------------- ------------------------------------ S0000842 2026-05-12 78.40 v7 2026-05-13 02:00 UTC Initial Americas close publish S0000842 2026-05-12 79.15 v7 2026-08-16 02:00 UTC Feed Alpha restatement file F-90412- A simulated trade decision on
2026-06-01filtersknown_from <= 2026-06-01and gets78.40. - A simulated trade decision on
2026-08-20filtersknown_from <= 2026-08-20and gets79.15. - Deterministic
known_fromon derived rows: Each golden row'sknown_fromis set to the first scheduled regional publish timestamp at or aftermax(received_at, known_from)across all raw price, identifier-map, and corporate-action inputs used to build it. Replaying the raw layer inreceived_atorder next year reproduces the exact same versions andknown_fromtimestamps!
- A simulated trade decision on
High-level architecture
Feed Alpha Feed Beta Feed Gamma (daily closes, corrections, restatements) \ | / v v v +----------------------------------------------+ | Immutable Landing Zone (S3 / GCS) | raw files stored forever + SHA-256 + received_at +----------------------+-----------------------+ | v +----------------------------------------------+ +------------------------------------+ | Ingest & Quality Gate |---->| Quarantine & 3-State Circuit | | schema, exchange calendar, stale & outlier | | Breaker (pages data on-call) | +----------------------+-----------------------+ +------------------------------------+ | v +----------------------------------+ +----------------------------------------+ | Append-Only Raw Layer | | Versioned Security Master | | (raw_vendor_prices per vendor) | | (identifier_map + corporate_actions) | +-----------------+----------------+ +-------------------+--------------------+ | | +--------------------+---------------------+ v +---------------------------------------------------------------------------------+ | Deterministic Golden Builder (pinned rule_version, e.g. v7) | | resolves IDs as-of trade_date, picks best fresh vendor, emits changed keys only | +--------------------------------------+------------------------------------------+ | v +----------------------------------------------+ +------------------------------------+ | Bitemporal Golden Lakehouse |---->| Snapshot Publisher (APAC/EMEA/AMER)| | Parquet + Apache Iceberg (immutable time | | runs Golden-Set strategies before | | travel snapshots, partitioned by trade_month)| | promoting new snapshot_id | +----------------------+-----------------------+ +------------------------------------+ | v +---------------------------------------------------------------------------------+ | Research Data API (as-of sweep, read-time split adjust, explicit fill, diff) | +----------------------+----------------------------------------------------------+ | v +----------------------------------+ +----------------------------------------+ | Backtest Runner (Docker + seed) |---->| Run Registry (manifests, PnL, diffs) | +----------------------------------+ +----------------------------------------+Deep dive 1: guaranteeing point-in-time integrity end to end
1. The exact as-of SQL query (and why every predicate matters): To read prices known at UTC timestamp
:kon simulated calendar date:sim_date, rank versions per(security_id, trade_date)within a singlerule_versionand exclude tombstones (is_deleted = TRUE, marker rows recording that a vendor withdrew an erroneous row):SELECT security_id, trade_date, close, volume, is_stale FROM ( SELECT security_id, trade_date, close, volume, is_stale, is_deleted, ROW_NUMBER() OVER ( PARTITION BY security_id, trade_date ORDER BY known_from DESC ) AS rn FROM golden_prices WHERE trade_date BETWEEN :start_date AND :sim_date AND rule_version = :rule_version AND known_from <= :k ) ranked WHERE rn = 1 AND NOT is_deleted;Notice three critical guards: (a) the unique constraint
(security_id, trade_date, rule_version, known_from)makesORDER BY known_from DESC100% tie-free; (b) filteringrule_version = :rule_versionprevents v7 and v8 cleaning rules from silently mixing; and (c) both ingest validation (trade_date <= market_date_at_publish) andtrade_date <= :sim_dateblock corrupt future-dated vendor rows.2. Fast O(versions + days) sweep instead of 2,520 separate queries: Running the SQL query above once for each of 2,520 trading days in a 10-year backtest would rescan the table 2,520 times. Because only ~1% of rows are ever revised, load all versions in
[start_date, end_date]withknown_from <= snapshot.cutoff_utconce, sorted byknown_from, and advance a single pointer alongside simulated decision times:def run_point_in_time(versions, decision_schedule, on_decision): """Stream versions into a live panel without ever peeking past decision_utc. versions: list of (known_from_utc, security_id, trade_date, value) sorted by known_from_utc; value is None when a tombstone withdraws a previously published row. decision_schedule: list of (decision_utc, sim_date) pairs in chronological order. """ # panel maps (security_id, trade_date) -> value currently known at decision_utc panel = {} version_idx = 0 num_versions = len(versions) for decision_utc, sim_date in decision_schedule: # Reveal only versions physically published at or before this decision instant while version_idx < num_versions and versions[version_idx][0] <= decision_utc: known_from_utc, security_id, trade_date, value = versions[version_idx] if trade_date <= sim_date: if value is None: # Tombstone: remove withdrawn row so it disappears just like SQL `NOT is_deleted` panel.pop((security_id, trade_date), None) else: panel[(security_id, trade_date)] = value version_idx += 1 on_decision(decision_utc, panel)3. Four subtle look-ahead traps this architecture closes: - Same-day close leakage across time zones: Comparing dates (
trade_date <= D) lets a strategy deciding at the09:30 ETUS open on dateDillegally readD's16:00 ETUS close! Comparing UTC timestamps fixes this automatically: Tokyo's close onDpublishes in the APAC run (~08:00 UTC), before09:30 ET(14:30 UTC), so it is visible; New York's close onDpublishes at02:00 UTConD+1, so it is hidden at09:30 ETonD. - Future split adjustments: Pre-dividing 2015 prices by a 4:1 split from 2020 turns a$16stock in 2015 into$4, corrupting any"price >= $5"universe filter! Store unadjusted prices ingolden_pricesand apply cumulative split/dividend factors at read time using onlycorporate_actionswithex_date <= sim_date AND known_from <= decision_utc. - Survivorship bias in universes: Compute"top 3,000 by 20-day dollar volume"at eachdecision_utcusing data known then, keeping subsequently delisted stocks (and their final delisting return!) in historical panels. - Bootstrapping 20-year history before live capture started: Files loaded on day 1 of the platform havereceived_at = launch_day. Buy vendor point-in-time archives where available (knowledge_source = VENDOR_PIT); where only restated history exists, modelknown_from = market_close + typical_vendor_delay, tag rowsMODELED, and stamp any run touchingMODELEDrows as"approximate PIT pre-capture"in its manifest.Deep dive 2: identifier resolution, corporate actions, and data lineage
External symbols change constantly: tickers (exchange symbols like
KLM) are renamed and reassigned to new companies years later; SEDOLs (7-character UK-issued listing identifiers) and ISINs (12-character international security identifiers) can change after mergers or redomiciliations.Deterministic effective-dated
identifier_map: Assign every listing an immutable internal surrogatesecurity_id(S0000842) and store every external code inidentifier_mapwith[valid_from, valid_to)andknown_from. Enforce non-overlapping intervals per(vendor, id_type, id_value, exchange)on write:vendor id_type id_value exchange security_id valid_from valid_to known_from event ------ ------- -------- -------- ----------- ---------- ---------- -------------------- -------------------- ALPHA TICKER KLM XNYS S0000842 2001-03-05 9999-12-31 2010-01-05 02:00 UTC Initial load ALPHA TICKER KLM XNYS S0000842 2001-03-05 2014-09-01 2014-09-02 02:00 UTC S0000842 delisted ALPHA TICKER KLM XNYS S0094510 2017-04-03 9999-12-31 2017-04-01 02:00 UTC New IPO reuses KLM! ALPHA TICKER KLMA XNAS S0000915 2011-01-10 2020-06-15 2020-06-15 02:00 UTC Renamed KLMA -> KLMB ALPHA TICKER KLMB XNAS S0000915 2020-06-15 9999-12-31 2020-06-15 02:00 UTC Continuous S0000915!- Resolution hierarchy: Match
valid_from <= trade_date < valid_to(using mappings withknown_from <= decision_utc) in decreasing specificity:vendor permanent ID -> SEDOL -> ISIN + exchange + currency -> TICKER + exchange. - Never guess unmapped rows: If a new symbol arrives before its mapping or two providers disagree, park the row in an
unmapped_queuefor a data steward. Once mapped, the golden row receivesknown_from= next publish run, truthfully reflecting when our system could identify it. - Corporate actions: Ticker renames keep the same
security_idseamlessly; splits adjust historical share ratios at read time; mergers recordlast_trade_dateplus cash/acquirer-stock conversion terms so simulated positions convert cleanly instead of freezing at a stale last price; spin-offs create a new childsecurity_idand distribute shares onex_date; delistings book the liquidation/OTC settlement price rather than vanishing silently.
End-to-end lineage of a retroactive correction vs. a methodology change: 1.
Feed Alpha's restatement file lands in S3 ->file_receiptslogsfile_id = F-90412,sha256,received_at. 2. Ingest appends the new row toraw_vendor_priceswithrow_hash(the original May row remains untouched). 3. Golden builder (rule_version = v7) sees a changed value on(S0000842, 2026-05-12)and appends a new row togolden_priceswithknown_from = 2026-08-16 02:00 UTC,source_row_hash, andrevision_reason. Every value traces back viagolden_prices -> source_row_hash -> raw_vendor_prices -> file_id (sha256). 4. Methodology changes (v7 -> v8): Changing vendor priority or staleness logic is a new formula, not a new market fact. Buildrule_version = v8alongsidev7(computingknown_fromdeterministically from raw input timestamps) so researchers opt intov8explicitly without breakingv7reproducibility.- Resolution hierarchy: Match
Deep dive 3: weekend regression isolation, stale data, and the circuit breaker
1. Isolating why Monday's Sharpe differs from Friday's (
R_frivs.R_mon): First, make single-manifest execution 100% deterministic (pinned Docker image,random_seed, sorted floating-point reductions, zero wall-clock/latestreads, and immutable Apache Iceberg snapshots—table metadata pointers to immutable Parquet files). Notice an important insight: inpoint_in_timemode, a normal weekend vendor correction stampedknown_from = Sundaycannot alter simulated trades prior to Sunday! So if Monday's run over2015–2024moved, one of three things changed in the manifest, isolated in minutes via single-factor counterfactual re-runs:Step 1: Diff manifests (R_fri vs R_mon) -> check code_commit, methodology (v7->v8), snapshot_id, mode. Step 2: If multiple changed, run 3 fast (~2 min) single-factor counterfactuals from R_fri: - R_code = R_fri with ONLY new code_commit -> isolates strategy/engine code bug - R_meth = R_fri with ONLY new rule_version -> isolates cleaning/adjustment rule change - R_data = R_fri with ONLY new snapshot_id -> isolates historical backfill / mapping edit Step 3: If R_data moved, run `diff(snap_fri, snap_mon)` scoped to the strategy's universe & dates, and join cell diffs against `(PnL_mon - PnL_fri)` per (security_id, trade_date) to rank the exact securities, dates, and vendor file_ids driving 90%+ of the Sharpe delta! (If dozens of backfill files landed, binary-search across file_ids in ~log2(N) staging views.)Pair this with automated Golden Sets in CI: PRs run reference strategies against a frozen snapshot (isolating code diffs), while every publish run executes pinned code against the candidate snapshot (isolating data diffs).
2. Handling stale holiday / missing-feed prices: Vendors often repeat yesterday's close when an exchange is on holiday or a local feed drops. If untreated, backtests execute simulated trades on closed markets and underestimate volatility/beta (inflating Sharpe!). - Cross-check every row against versioned exchange calendars: drop rows reported on closed holidays. - Flag a row on an open market day with
is_stale = TRUE(recordinglast_trade_date) ifopen == high == low == close == prev_close AND volume == 0orvendor_last_trade_date < trade_date. - IfFeed Alphais stale on an open day whileFeed Betahas fresh volume, the golden builder selectsFeed Beta; if> 30%of an open exchange is stale, quarantine that provider's market batch as a broken feed. - Never forward-fill in storage; researchers explicitly requestfill="none"orfill="ffill_max_3d"(which returns anis_filledboolean mask so the simulator never trades on a filled price).3. Three-state pipeline Circuit Breaker: - Closed (normal): Row-level anomalies (
price <= 0,low > high, unannounced> 25%or> 10 sigmareturn spikes,> 50 bpsliquid cross-vendor disagreement) quarantine individual rows and alert stewards while clean rows publish. - Open (tripped): Batch anomalies (> 0.5%of universe failing outlier checks, row count> 5%off exchange-calendar expectation, or a restatement touching> 1%of history) block snapshot promotion, keep researchers on the last goodsnapshot_id, and page data on-call. - Half-open (recovery): After vendor resend or steward sign-off, build a staging snapshot, run the Golden Set strategies, and promote to production only if Sharpe/PnL shifts are within tolerance or explicitly signed off.Storage layout, scaling, and trade-off summary
Store
golden_pricesas Parquet files managed by Apache Iceberg (or Delta Lake) on object storage, partitioned bytrade_monthand sorted within partitions by(security_id, trade_date, known_from). A 10-year scan prunes all other months immediately; each publish run also incrementally updates a materialized "latest-as-of-cutoff" Parquet view (rewriting only touched monthly partitions while sharing unchanged files across snapshots) so exploratory snapshot reads stay fast, and researchers query lock-free in parallel via DuckDB, Polars, or Spark.Decision Chosen Design What We Trade Away ------------------------ -------------------------------------- -------------------------------------- Knowledge clock Our receipt/publish UTC (known_from) Pre-launch history needs VENDOR_PIT or labeled MODELED timestamps Updates & corrections Append-only bitemporal rows (~1% cost) As-of window/sweep logic on reads Corporate adjustments Computed at read time as of decision Slight read CPU vs pre-adjusted series Methodology updates Immutable rule_version (v7, v8) Storage for parallel golden versions Stale vendor prices Flagged + vendor fallback; never filled Researchers choose explicit fill policy Corrupt vendor batches 3-state circuit breaker + Golden Sets Fresh snapshot waits during incidents Regression debugging Run manifests + 1-factor counterfactuals A few minutes of counterfactual compute
Intuition & how it works
Think of building a quantitative backtest pipeline like running an audited historical weather-forecasting contest where contestants simulate what they would have predicted on 2015-03-10:
- To keep the contest honest, a contestant making a call at
09:30 AMon2015-03-10may only read weather newspapers physically delivered to the newsstand at or before09:30 AMon2015-03-10. If a newspaper prints a typo on Tuesday (78.4°) and publishes an erratum a quarter later (79.1°), you do not go back with an eraser and alter Tuesday's newspaper—you keep Tuesday's original newspaper in the archive and file the erratum under the date it actually arrived! - In database terms, that two-date filing cabinet is a bitemporal data model: every price, identifier mapping, and corporate action stores both its valid time (
trade_date, the market day the price describes) and its knowledge / transaction time (known_from, the UTC timestamp when our pipeline physically received and published that version). - To guarantee Monday's run matches Friday's run byte for byte, every backtest also pins an immutable snapshot (an Apache Iceberg or Delta Lake table version pointing to immutable Parquet columnar files) alongside a run manifest recording exact code commit, cleaning methodology version, and random seed.
Naive pipelines fail because they treat historical market data like a standard CRUD application: they overwrite past rows when a provider sends a price restatement, pre-adjust all historical prices for stock splits up to today, and join external feeds on mutable ticker strings (like KLM). Overwriting a months-old price injects look-ahead bias (letting simulated past trades act on future corrections) and destroys Friday's state so nobody can reproduce Friday's Sharpe ratio (annualized average excess return divided by return volatility). Meanwhile, joining on ticker strings silently stitches a delisted 2014 company's prices onto a brand-new 2017 IPO that reused the same ticker, and forward-filling missing holiday prices lets simulated strategies trade at phantom prices that never existed!
Mini concrete walkthrough
Suppose internal security S0000842 traded under ticker KLM on 2026-05-12, and let's trace four events:
- Initial capture (
2026-05-13 02:00 UTC):Feed AlphadeliversKLMclose =78.40fortrade_date = 2026-05-12. Ingest logs the raw file's SHA-256, resolves(ALPHA, TICKER, 'KLM', 2026-05-12)via the effective-datedidentifier_mapto permanent surrogateS0000842, and appends(S0000842, 2026-05-12, close=78.40, rule_version='v7', known_from='2026-05-13 02:00Z')togolden_prices. - Retroactive August restatement (
2026-08-16 02:00 UTC): Over a weekend,Feed Alphasends restatement fileF-90412revising2026-05-12to79.15. Instead of overwriting78.40, the pipeline appends a second row(S0000842, 2026-05-12, close=79.15, rule_version='v7', known_from='2026-08-16 02:00Z')linked back toF-90412. - Point-in-time backtest read: When a strategy simulates
2026-06-01 09:30 ET, the reader filtersknown_from <= 2026-06-01 13:30Z, so79.15is invisible and the strategy sees78.40—the exact number a live trader had on June 1! Simulated decisions after2026-08-16 02:00Zsee79.15. - Monday regression check: If a researcher asks why Friday's run (
R_fri) and Monday's run (R_mon) differ, the runner diffs their manifests (code_commit,rule_version,snapshot_id), runs single-factor counterfactuals swapping one input at a time, and joinsdiff(snap_fri, snap_mon)against daily per-security PnL deltas to attribute the exact Sharpe shift toF-90412in minutes.
Key trade-offs
- Our ingestion clock vs. vendor-provided timestamps for
known_from: Stampingknown_fromwith our own receipt/publish UTC clock guarantees provable point-in-time truth going forward, at the trade-off that 20-year history loaded on day one lacks live capture receipts and must either come from a paid vendor point-in-time archive (VENDOR_PIT) or use modeled publication delays explicitly labeledMODELEDin run manifests. - Append-only bitemporal rows vs. in-place updates: Keeping every version forever costs only ~1% extra storage (~150 MB over 20 years) and requires a window/sweep filter on reads, in exchange for completely eliminating silent look-ahead leaks and preserving full version lineage.
- Bitemporal
known_from+ physical table snapshots (snapshot_id) vs. either alone:known_fromprevents simulated past decisions from seeing future revisions, while pinning an immutable Iceberg/Delta physicalsnapshot_idguarantees identical bytes even if historical archives or identifier mappings are backfilled later—requiring modest object-storage retention for referenced Parquet files. - Read-time corporate-action adjustment vs. pre-adjusted price series: Storing unadjusted prices and applying only corporate actions (splits, dividends) with
ex_date <= sim_date AND known_from <= decision_utcat query time adds lightweight multiplication on read, but avoids corrupting historical price-level filters (price >= $5) with future stock splits. - Flagging stale prices vs. forward-filling in storage: Marking zero-volume or repeated holiday prices with
is_stale = TRUE(and falling back to a fresh vendor when available) forces researchers to pick an explicitfillpolicy in the API, preventing silent trading on closed exchanges and artificial volatility suppression. - Circuit breaker holding snapshots vs. immediate publishing: Tripping a circuit breaker (an automated gate that halts snapshot promotion when batch outlier or row-count thresholds breach) can delay fresh daily data by a few hours during vendor incidents, trading brief staleness to protect dozens of researchers from corrupted backtests.
Common mistakes
- Trusting the vendor's
as_oforpublish_timecolumn asknown_from: Vendors routinely backfill historical restatements with the original trade date's timestamp, reintroducing look-ahead bias unless you enforce your own receipt clock. - Overwriting historical rows on provider corrections: Updating
78.40to79.15in place alters historical return series retroactively and makes prior research runs impossible to reproduce. - Filtering by date (
trade_date <= D) instead of UTC timestamps (known_from <= decision_utc): Date-only filters allow a morning09:30 ETstrategy on dateDto peek atD's16:00 ETmarket close before it happens! - Joining vendor data on
tickerwithout effective date ranges: Reused tickers merge unrelated companies across delistings, and ticker renames split one company into two broken histories. - Building historical universes from today's index constituents (survivorship bias) or dropping delisted stocks without their final delisting return: Omitting bankruptcies makes mediocre strategies appear to beat the market.
- Pre-adjusting all historical prices for splits up through today: Dividing 2015 prices by a 2020 split leaks future corporate performance into past share-price filters.
- Forward-filling missing or holiday prices inside golden tables: Stored forward-fills erase the distinction between real market liquidity and carried-forward numbers.
- Debugging Sharpe shifts manually without manifests or Golden Sets: Without pinning code, config,
rule_version, random seeds, andsnapshot_idtogether, you cannot separate a Python bug from a weekend vendor restatement.
Follow-up questions
- Suppose an upstream provider retroactively alters a historical analyst earnings forecast—how should your schema store that update, and does your point-in-time visibility filter need to change? The core
known_from <= decision_utcvisibility rule stays completely unchanged—in fact, retroactive forecast edits are the textbook reasonknown_frommust always be our receipt timestamp rather than the provider's claimed timestamp! Analyst forecasts carry three time dimensions instead of two:fiscal_period(which reporting period is being estimated, such as2027-Q1),analyst_est_timestamp(when the analyst originally issued the forecast), and ourknown_from(when our platform ingested that version). If an analyst publishes a brand-new estimate, it lands as a new observation; if the provider retroactively fixes a typo in last month's record and backdatesanalyst_est_timestampto last month, we append a new row stamped with today'sknown_from(keepinganalyst_est_timestampstrictly as descriptive metadata), and any derived consensus mean/median recomputes deterministically withknown_fromderived from its inputs so historical simulations still see last month's consensus exactly as it stood then. - Before onboarding an additional historical market-data provider into research production, what validation checks would you run to catch hidden look-ahead or survivorship bias? First, audit how
known_fromis populated on the provider's bulk historical archive: unless they supply true point-in-time delivery logs with original capture timestamps, bulk history only reflects what the provider knows today and cannot be taggedCAPTURED. Second, compare the candidate archive against the live raw versions we already recorded from incumbent providers over recent years—if the candidate's "initial" numbers systematically match subsequent restatements or omit delisted bankruptcies, their history contains look-ahead or survivorship bias and must be restricted tosnapshot-only exploratory reads. Third, ingest the new feed in shadow mode for 1–3 months to measure actual file arrival times against claimed timestamps, exchange holiday calendars, and symbol mappings. Finally, over several months of live capture, compare strategy signals computed on the backfilled archive against live-captured rows to test for backfill bias (an unnatural drop-off in signal Sharpe right at the live-capture boundary). - How would you design an automated pipeline circuit breaker that catches anomalous price spikes or broken daily feeds before they pollute researcher backtests? Model the circuit breaker as a three-state gate sitting between ingest validation and the Snapshot Publisher. In the Closed (normal) state, row-level checks (
price <= 0,low > high, unannounced single-day returns exceedingmax(25%, 10 * 60d_vol)without a matching corporate action, or> 50 bpsdivergence across providers on liquid equities) quarantine individual rows and notify a data steward while clean rows publish on schedule. Whenever batch-level anomalies breach safety limits—such as> 0.5%of instruments failing outlier rules, row counts deviating> 5%from open-exchange calendar expectations,> 30%stale prices on an open market, or a restatement altering> 1%of historical rows—the breaker trips Open, halting newsnapshot_idpromotion so researchers stay on the last verified immutable snapshot while paging on-call. Once the provider resends or a steward signs off on an override, the breaker enters Half-Open, materializing a staging snapshot, running pinned Golden Set reference strategies against it, and promoting the snapshot only if Sharpe and PnL diffs fall within expected bounds.
Follow-up questions
- Suppose an upstream provider retroactively alters a historical analyst earnings forecast—how should your schema store that update, and does your point-in-time visibility filter need to change?
- Before onboarding an additional historical market-data provider into research production, what validation checks would you run to catch hidden look-ahead or survivorship bias?
- How would you design an automated pipeline circuit breaker that catches anomalous price spikes or broken daily feeds before they pollute researcher backtests?
Similar questions
- Incremental Pipeline for Rolling Market Metrics
- Data Model for Time-Versioned Trading Restrictions
- Design a Governed Market Data Catalog and Point-in-Time Access Layer
- p-Value Interpretation and Cointegration Testing for Price Series
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor