Vectorized engine and a first strategy
Implement a vectorized engine over date-by-asset panels: signal, explicitly lagged positions, returns, turnover, and linear costs. Validate with a shift test for lookahead and reproduce cross-sectional momentum as a reference strategy.
After this lesson you can
- Define and document the timing convention between signal, position, and return.
- Implement the vectorized engine with turnover and linear costs using NumPy and pandas.
- Write a test that truncates or perturbs the future and checks that the past does not change.
- Reproduce a 12-1 momentum strategy and compare its shape with the literature.
Before you start
From the close to the next open
A signal calculated after observing today’s close cannot trade retroactively at that price. We establish this clock: the target weight is calculated at close ; idealized execution is assumed at open ; the position earns the return from that open to open . Orders are known before the open, although fixing an exact weight at an as-yet unknown price requires an idealization that an event-driven engine must revisit.
The signal, position, and return pipeline uses one row per date and one column per asset. If returns are labeled by the initial open date, that row’s position is the previous row’s signal. Portfolio gain is the sum of position times return; cost is charged on traded notional under a declared convention.
For example, Monday’s close allows calculation of . That target takes effect at Tuesday’s open and captures the move from Tuesday’s open to Wednesday’s open. Tuesday’s return row is multiplied by Monday’s weight. It does not earn Monday-to-Tuesday movement: part occurred before assumed execution. If a table labeled returns by their ending date, shifts would need adaptation; applying SHIFT mechanically without defining labels does not solve the problem.
The open is a reference price, not a promise of execution. An order sent before the auction may not fill at the displayed price, and determining shares that produce exactly the desired weight requires knowing prices and capital at execution. Here these details are abstracted to isolate the calculation. The clock must also account for holidays, suspended assets, and data arriving after the close: an observation’s economic date is not necessarily its availability date.
A vectorized engine calculates these operations over entire panels. The result is auditable if dates and columns match, missing values have explicit treatment, and code does not turn future information into a signal. Vectorization is a computation method, not a guarantee of causality.
Here the synthetic rule sells when the latest return was positive and buys when negative. Removing the lag applies a position opposite to the sign of the same return and loses by construction before costs. Leakage does not always inflate a curve: it depends on the rule’s direction. A same-sign signal would mechanically gain from contemporaneous return, but would be a different strategy.
Weights, turnover, and costs
With target weight and open-to-open return , the engine uses position and
Turnover is the sum of absolute weight changes, including purchases and sales, implicitly divided by capital. Changing from to produces turnover . This approximation ignores weight drift between rebalances, partial fills, impact, and short borrowing. It should not be confused with share-based accounting.
At a cost of 5 basis points, one unit of turnover subtracts of capital, or 0.05%. Changing from a long position of 0.5 to a short position of −0.5 implies one unit of turnover in that asset: both the existing position and new short must be sold. Some publications divide turnover by two or quote costs per leg. Check each convention before comparing results.
The initial position starts at zero and incurs entry cost. The engine does not automatically liquidate at the sample end: to charge liquidation, add a zero-weight target and a subsequent row allowing execution. It also does not reconstruct exact share quantities after each price move. The product of represents a portfolio rebalanced to those weights with initial capital one; negative return with short positions is not necessarily an equal-sized loss in a real margin account.
The lookahead shift test changes the cutoff observation and all subsequent ones. A position that must exist before that observation is known must remain unchanged through and including the cutoff. The test also runs a deliberately unlagged version that must fail. It tests one particular perturbation and does not by itself detect historical revisions, late-published data, or every leaked normalization.
The metamorphic test does not need to know a strategy’s correct profit: it checks a relationship that should hold when inputs are transformed. For another strategy, fix a cutoff and alter only information that should not yet be available. Earlier positions must remain unchanged. Repeat at several cutoffs with different perturbations; one transformation may accidentally leave a future-using signal unchanged. The unlagged negative control shows the check can detect at least the designed failure.
Cross-sectional momentum ranks assets by previous performance, buys winners, and sells losers. Jegadeesh and Titman study strategies in this family. A 12-1 convention uses approximately 252 sessions of history and omits the most recent 21, reducing exposure to very short-term reversal effects without guaranteeing their elimination.
For each asset, calculate the close 21 sessions ago divided by the close 252 sessions ago, minus one. On each date, rank finite values for eligible assets, buy the top decile, and sell the bottom, with 0.5 exposure on each side. With ten eligible assets there is one name per side; below ten, the portfolio stays flat. Ties are resolved by column order, a reproducible decision that can also affect results. The ranking is cross-sectional: a company can be among the winners with a negative individual return if others fell more.
The previous lesson’s historical sample is a third-party compilation with retrospectively adjusted prices and reconstructed memberships. It does not contain every version available on each date. The following experiment is a descriptive backtest on that snapshot, not a complete point-in-time test. We also compare the monthly factor published by Kenneth French, constructed differently from our portfolio.
Local laboratory: vectorization and momentum
Download p01vector.py and its tests into the project directory, together with p01data.py from the previous lesson. You need local Python with NumPy, pandas, PyArrow, and pytest. The price and membership tables from p01-l01 are verified by hash and reused without downloading again if present in P01_UNIVERSE_ROOT.
import os,sys
from pathlib import Path
import numpy as np,pandas as pd,pytest
libdir=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (libdir/'p01vector.py').exists(): raise FileNotFoundError('Descarga p01vector.py y test_p01vector.py en P01_LIB_DIR')
sys.path.insert(0,str(libdir))
from p01data import PRICES,MEMBERS,PRICE_SHA,MEMBER_SHA,fetch
from p01vector import backtest,momentum_weights,past_unchanged,load_panel
r=pd.DataFrame({'A':[.01,-.02,.03,-.04,.05,-.06,.07]})
señal=lambda x:-x
assert past_unchanged(señal,r,3,lag=1)
assert not past_unchanged(señal,r,3,lag=0)
estado=pytest.main([str(libdir/'test_p01vector.py'),'-q','-p','no:cacheprovider'])
assert estado==0
print('Con retardo: pasa | sin retardo: fuga detectada | pytest:',estado)npm run lab and open the connection link.The test changes the return at the cutoff date and later rows; the position for that date should have been determined from the previous row. We compare positions, not performance on the altered date, which naturally changes. The engine rejects missing returns and misaligned panels: the next cell explicitly replaces some returns with zero and counts affected positions.
root=Path(os.environ.get('P01_UNIVERSE_ROOT',Path('p01_project')/'raw'))
prices=root/'prices.parquet'; members=root/'membership_intervals.parquet'
fetch(PRICES,prices,PRICE_SHA); fetch(MEMBERS,members,MEMBER_SHA)
close,open_adj,eligible=load_panel(prices,members,start='2006-01-01',end='2010-01-05')
weights=momentum_weights(close,eligible,lookback=252,skip=21)
retornos=open_adj.shift(-1)/open_adj-1
faltan=~np.isfinite(retornos.to_numpy())
net,turn,pos=backtest(weights,retornos.where(np.isfinite(retornos),0.),cost_bps=5)
test=(net.index>='2008-01-01') & (net.index<='2009-12-31')
crash=(net.index>='2009-03-01') & (net.index<='2009-05-31')
missing_held=int(((pos.to_numpy()!=0)&faltan)[test].sum())
print('Panel:',close.shape,'| sesiones de evaluación:',int(test.sum()))
print('Capital 2008 a 2009:',float((1+net[test]).prod()),
'| marzo a mayo 2009:',float((1+net[crash]).prod()-1))
print('Rotación diaria media:',float(turn[test].mean()),
'| posiciones con retorno faltante:',missing_held,
'| posiciones totales:',int((pos.to_numpy()[test]!=0).sum()))npm run lab and open the connection link.Gross weight is 0.5 long and 0.5 short; it is rebalanced daily, with 5 bp per total notional changed. Adjusted open is calculated by multiplying each provider’s open by adjusted close/close, an approximation requiring verification of each source’s conventions. This vectorized engine does not model borrowing costs, short constraints, impact, partial positions, or delistings. Across 505 evaluated sessions, 29 of 45,490 positions have missing open returns and are marked to zero; that choice can materially alter the result. Delistings are not claimed to be correctly valued.
In this snapshot and under these rules, 2008 to 2009 capital ends at approximately 0.509 and compounded return from March to May 2009 is −40.3%. This curve does not exactly reproduce the literature’s methodology or prove that a real strategy would have been executable. Daniel and Moskowitz document momentum losses during strong rebounds; magnitude depends on the portfolio, universe, and convention.
The economic interpretation of the episode goes beyond correcting a coding error. In a violent rebound, previous losers can rise sharply while previous winners recover less. The short leg in losers then loses even if the market as a whole rises. This explanation is a mechanism hypothesis, not an attribution calculated by the lab: attributing each loss would require retaining per-asset contributions and separating long, short, and cost components.
An informative comparison holds decisions not being investigated fixed. If window, universe, frequency, and cost all change at once, a capital difference does not identify which caused it. Try one modification at a time, retain the same sample, and record runs. When many variants are explored on the same period, even an exceptional curve may result from selection; later validation periods and criteria chosen before seeing their results are needed.
import io,zipfile,re
from p01data import sha256
url='https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Momentum_Factor_CSV.zip'
archivo=Path(os.environ.get('P01_MOM_PATH',Path('p01_project')/'raw'/'french_momentum.zip'))
raw=fetch(url,archivo); z=zipfile.ZipFile(io.BytesIO(raw)); txt=z.read(z.namelist()[0]).decode('latin-1')
rows=[]
for line in txt.splitlines():
if re.match(r'^\s*\d{6}\s*,',line):
a=line.split(','); rows.append((int(a[0]),float(a[1])/100))
mom=dict(rows); tres=np.array([mom[200903],mom[200904],mom[200905]])
print('SHA256:',sha256(raw),'| factor marzo, abril, mayo:',tres,
'| compuesto como cartera reinvertida:',float(np.prod(1+tres)-1))npm run lab and open the connection link.The analyzed download has hash 27ed60e5b2caa9ea334a261cddfa864a9926f6bf45e9677c95dfd835c5abb315 and monthly values −11.80%, −34.36%, and −12.54%. Compounding them as if one unit of capital were reinvested yields approximately −49.4%. The public factor is a portfolio spread with its own construction; its combination is not our engine’s curve and may be revised in future publications.
Exercises
def backtest(weights,returns,cost_bps):
raise NotImplementedError()What to remember
The vectorized engine makes that chain explicit and enables a metamorphic test. The next stage introduces orders, fills, and accounting to examine execution assumptions simplified here.