Module contents
Stage 1 of 9Advanced 110 min

Point-in-time data and engine architecture

Build the engine's data layer with free daily prices, dividends, and Kenneth French factors stored in Parquet. Reconstruct total returns from prices, dividends, and splits, compare historical and end-of-period universes, and define the engine's modular interfaces and tests.

After this lesson you can

  • Download and version prices, dividends, splits, and factors in Parquet with availability dates.
  • Reconstruct total returns and reconcile them with provider-adjusted prices to a fixed tolerance.
  • Quantify survivorship selection by comparing a current universe with a historical one.
  • Design data, signal, portfolio, execution, and analysis interfaces with unit tests.

Before you start

An engine needs a history that could have been known

A correct signal can produce a fictional result if the engine uses revised prices, duplicated dividends, or a universe selected using later information. We begin by building contracts and an auditable data layer. Each datum must distinguish observation date, availability time, version, and source; the execution clock determines which values can enter a decision.

A point-in-time dataset stores versions with their availability times. A query at date tt selects the latest version available by tt, not the latest version known today. A current download of a historical series does not by itself reconstruct which version was available in the past. In the lab we mark the download with its ingestion time: the snapshot is reproducible but is not presented as a complete publication history.

For example, a measurement with a January economic date may be published in February and revised in March. A February 15 signal can use the first version if it was known then, not the March revision. Asset identifier and observation date form a key, while availability time orders versions. If two different values share the same time and key, the lab rejects the conflict instead of choosing arbitrarily.

A daily close date is not a universal instant. New York closes in its local time zone, whose UTC offset changes with daylight saving. A closing quote, its publication, and a possible revision also have different clocks. Do not mix a market close with another market that had not yet closed, or fill holidays with prices that imply trades.

Free sources have limits too. In this AAPL sample, Yahoo’s historical endpoint returns closes and dividends retrospectively adjusted for splits, plus a close adjusted for distributions. Apple and the SEC document the four-for-one split that began trading adjusted on August 31, 2020. The Kenneth French library publishes factors and historical versions; its current series can be revised and does not equal every version known on each date.

Splits, dividends, and returns

For corporate action adjustment, let Pt−1P_{t-1} be the previous close per share, PtP_t the post-split close, sts_t new shares per old share, and DtD_t the dividend per post-split share. If reinvested at close and there are no other events,

Rt=st(Pt+Dt)Pt−1−1.R_t=\frac{s_t(P_t+D_t)}{P_{t-1}}-1.

A 2-for-1 split with prior close 100, later close 51, and dividend 0.50 produces 2(51+0.50)/100−1=3%2(51+0.50)/100-1=3\%. This convention changes if the dividend is expressed per old share or payments occur on another date. The provider’s adjusted close may use another reinvestment convention; reconciling returns within a tolerance locates differences but does not prove all events are complete.

Yahoo already adjusts the close retrospectively for splits in this sample. Applying the multiplier directly to that close again would count the split twice. To illustrate the formula, we reconstruct a pre-split per-share price by multiplying by later splits included in the download; this depends on knowing all splits the provider incorporated into its adjustment. It is not an original unrevised historical price archive.

Retroactive adjustments are useful for measuring returns, but change historical levels when a new event appears. A signal using only ratios within a window may be invariant to a common factor applied across that window; a rule comparing absolute price with a fixed threshold may not. Saving the received JSON and its hash permits repeating the calculation even if the provider later revises its series.

The universe visible at the end

Survivorship bias control requires historical memberships, stable identifiers, and treatment of delistings, mergers, and final payments. Retrospectively choosing index members at the end of a period can exclude businesses that left earlier. Effect size and sign depend on the strategy and data.

InteractiveA retrospective selection

Aggregate daily returns from a public third-party compilation of S&P 500 members. Blue uses historical membership at the previous close; orange retrospectively uses December 31, 2020 members. Portfolios are equally weighted and rebalanced each session, without costs.

Capital: 0.87 to 2.252015 to 2020

The source mixes providers and adjusted prices; returns without consecutive closes are excluded and missing final payments are not imputed. Retrospective selection and incomplete coverage prevent interpreting the difference as universal bias or an official index.

2015
Historical capital1.842
2020 universe capital2.254
Capital difference0.412
Compare two universes in a public third-party compilation.

The figure uses a public compilation of prices and memberships from different providers, not an official index archive. Equal-weighted portfolios use returns available in consecutive sessions from 2015 to 2020; one uses membership at the previous close and the other uses December 31, 2020 members for all past dates. Selecting the second group uses the future. Coverage varies, returns are missing without consecutive prices, and absent delisting payments are not imputed: the result measures this procedure, not the entire market’s true bias.

In the hash-pinned download, 1,511 sessions produce capital 1.842 for the historical universe and 2.254 for the cutoff group, starting from 1; the difference is 0.412 units of capital without costs. Daily median assets with an available return are 505 and 497 respectively. The source mixes Yahoo, Tiingo, CRSP, WIKI, and patches; we have not individually validated each delisting. These numbers are not a forecast or a claim that bias is always positive.

The membership file contains, for example, AABA and Lehman identifiers with end dates. This shows that the compilation retains some names absent from the final group, not that it fully covers every delisting and payment. Tickers can change or be reused, and a retrospective ticker is not necessarily the public identifier in force each day. Robust reconstruction requires security identifiers and joins checked against event documentation.

Engine contracts

The backtesting architecture separates data, signal, portfolio, execution, accounting, and analysis. Data answers what was known; signal produces a proposal; portfolio turns proposals into targets; execution turns orders into fills; accounting updates cash and positions; analysis summarizes results. An interface allows each piece to be replaced, but separation alone does not guarantee a correct clock.

Messages between pieces must preserve units and times. An order for ten shares, a 10% target weight, and a ten-share fill are distinct objects. Accounting must reduce cash by traded value and commission and mark the position at the chosen price. Analysis receives a curve already net of costs actually simulated by the engine; omitted costs must be declared rather than attributed to an imaginary stage.

Download p01data.py and its tests into the same working directory. You need local Python, NumPy, pandas, PyArrow, and pytest. The module contains the contracts and functions used below; tests use small doubles to check the flow and do not represent a complete engine. Subsequent lessons build the implementations.

Local laboratory: snapshots, events, and universe

The cell downloads or reuses three sources: AAPL, monthly factors, and a third-party compilation of prices and memberships. The last download is about 236 MB and is verified against a fixed SHA-256; if the provider replaces it, the code fails explicitly rather than mixing versions. You can supply existing paths through the indicated variables. The work writes its own Parquet files in the project directory.

[ ]Reconstruct and version AAPL and factorsLocal GPU
import os,sys,json
from pathlib import Path
import numpy as np,pandas as pd
libdir=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (libdir/'p01data.py').exists(): raise FileNotFoundError('Descarga p01data.py y test_p01data.py en P01_LIB_DIR')
sys.path.insert(0,str(libdir))
from p01data import (YAHOO,FRENCH,PRICES,MEMBERS,PRICE_SHA,MEMBER_SHA,
                     fetch,sha256,yahoo_aapl,total_return,french_monthly,asof_versions,compare_universes)
root=Path(os.environ.get('P01_PROJECT_DIR','p01_project')); root.mkdir(parents=True,exist_ok=True)
cache=root/'raw'; cache.mkdir(exist_ok=True)
aapl_path=Path(os.environ.get('P01_AAPL_PATH',cache/'aapl.json'))
french_path=Path(os.environ.get('P01_FRENCH_PATH',cache/'french.zip'))
raw=fetch(YAHOO,aapl_path); factors_raw=fetch(FRENCH,french_path)
bars=yahoo_aapl(raw); factors=french_monthly(factors_raw)
ret=total_return(bars.cierre_reconstruido,bars.dividendo_reconstruido,bars.split)
vendor=bars.cierre_ajustado/bars.cierre_ajustado.shift()-1
error=np.abs(ret-vendor.to_numpy()); valido=np.isfinite(error)
fraccion=float(np.mean(error[valido]<.0001)); p99=float(np.quantile(error[valido],.99)*10000)
assert fraccion>=.99
ingestion=pd.Timestamp.now(tz='UTC')
guardado=bars.reset_index().assign(disponible=ingestion,fuente='Yahoo chart',sha256=sha256(raw))
guardado.to_parquet(root/'aapl_instantanea.parquet',index=False)
factors.assign(disponible=ingestion,fuente='Kenneth French',sha256=sha256(factors_raw)).to_parquet(root/'french_mensual.parquet',index=False)
manifest={'ingestion_utc':ingestion.isoformat(),'aapl_sha256':sha256(raw),'french_sha256':sha256(factors_raw),
          'aapl_filas':len(bars),'factor_filas':len(factors),'fuentes':[YAHOO,FRENCH]}
(root/'manifest.json').write_text(json.dumps(manifest,indent=2),encoding='utf8')
print('AAPL filas y transiciones:',len(bars),int(valido.sum()),'| fracción error <1 pb:',fraccion,'| p99 pb:',p99)
print('Split del 31-08-2020:',bars.loc['2020-08-31','split'],'| dividendos:',int((bars.dividendo_split>0).sum()))
print('Parquet y manifiesto:',root.resolve(),'| factores mensuales:',len(factors))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The snapshot run here has 1,006 closes and 1,005 comparable returns: all are below one basis point, the 99th percentile is approximately 0.040 bp, and the maximum 0.641 bp. This result concerns AAPL over this interval and does not prove that Yahoo or another source reconciles every asset. The calculation excludes withholding, taxes, and payment dates: it treats the ex-dividend as reinvested under the declared convention.

The ingestion date of both Parquet files is the current reading time. This avoids claiming that data from a current revision was historically available, but means we lack a complete historical series of versions. The next test illustrates how a query would change if revisions with known times had been archived.

The manifest stores response SHA-256 hashes and URLs, and the Parquet files include ingestion time and source. A hash detects byte changes; it does not verify that the provider published a revision on a particular historical date or that prices are correct. Ingestion time is a conservative bound on when this copy was known to the exercise, not the datum’s first publication date.

[ ]Versions and contract testsLocal GPU
import pytest
revisiones=pd.DataFrame({'activo':['A','A'],'fecha':['2020-01-01','2020-01-01'],
                         'disponible':['2020-01-02T00:00:00Z','2020-02-01T00:00:00Z'],'valor':[1.,2.]})
antes=asof_versions(revisiones,'2020-01-15T00:00:00Z')
despues=asof_versions(revisiones,'2020-03-01T00:00:00Z')
assert antes.iloc[0].valor==1 and despues.iloc[0].valor==2
estado=pytest.main([str(libdir/'test_p01data.py'),'-q','-p','no:cacheprovider'])
assert estado==0
print('Consulta anterior:',antes.iloc[0].valor,'| posterior:',despues.iloc[0].valor,'| pytest:',estado)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The query uses two synthetic revisions only to verify the clock; they are not historical AAPL values. Doubles for data, signal, portfolio, execution, accounting, and analysis test their minimum contracts. The next cell reproduces the figure’s comparison with complete tables: P01_UNIVERSE_ROOT can point to a directory already containing both Parquet files; otherwise verified downloads in the project cache are used.

[ ]Measure retrospective selectionLocal GPU
source_root=Path(os.environ.get('P01_UNIVERSE_ROOT',cache))
prices_path=source_root/'prices.parquet'; members_path=source_root/'membership_intervals.parquet'
fetch(PRICES,prices_path,PRICE_SHA); fetch(MEMBERS,members_path,MEMBER_SHA)
comparacion,detalle=compare_universes(prices_path,members_path)
capital=(1+comparacion[['historico','corte']]).prod()
print('Sesiones:',detalle['sesiones'],'| capital histórico/corte:',capital.to_dict())
print('Mediana de activos con retorno:',comparacion[['n_historico','n_corte']].median().to_dict())
print('Procedencia de observaciones:',detalle['fuentes'],'| miembros del corte:',detalle['miembros_corte'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Assets with missing prices are excluded that day and the remaining portfolio is renormalized, a rule using observed availability that can introduce additional bias. Delisting terminal values, taxes, costs, sizes, and historical publication of index changes are not modeled. The archive mixes conventions and sources; its binary identity is verified, not each underlying datum. An operational study needs identifiers and events checked against primary sources, a delisting registry, and reserved temporal evaluations.

Exercises

NumericTotal return
A share closes at 100 before a 2-for-1 split. After the split it closes at 51 and pays 0.50 per new share. What is total return as a percentage?
QuizWhat was known
Which store allows querying what was known on a past date, assuming all revisions were archived?
QuizA current index in the past
What bias can arise when evaluating an old strategy only on index members at the period's end?
CodeReturn with events
Implement total_return(prices,dividends,splits): return a NumPy array of the same size, NaN at the first position, and for t>0 calculate splits[t]*(prices[t]+dividends[t])/prices[t−1]−1. Split is new shares per old share and dividend is per new share.
def total_return(prices,dividends,splits):
  raise NotImplementedError()
Shift+Enter to run

What to remember

Key idea
A reproducible snapshot and a complete point-in-time archive are distinct: record source, versions, timing, and missing data before evaluating a signal.

The engine starts with contracts and tests; the figure’s result depends on a compilation and declared coverage rules. The next stage transforms signals into positions with an auditable calendar.