~3 hours Intermediate Python
Build a complete ML trading strategy on real ETF market data — features, model, leakage-safe validation, and a cost-aware backtest — with AI coding and research agents helping you. You leave with a working pipeline you keep and can extend.
Pick a feature set and a cost assumption. The simulated pipeline shows the folds, the IC, and the gross vs net result. No server, no API key — it runs in your browser.
Feature set: Cost per trade:
Press "Run the pipeline" to see the folds, the IC, and the gross vs net result.
What it is: Read in order, one lesson at a time, over about 3 hours with one 10-minute break. Tick the Done box when you finish a lesson. Your progress is saved in your browser. Every lesson has the same shape: What it is, Why it matters, code you can copy and run, a small task to try yourself, and two check questions with the answers hidden until you open them. The deliverable is a complete, working strategy pipeline you keep and can extend.
Why it matters: A workshop only works if you do it, not just read it. The tick boxes and the small tasks keep you moving, one small step at a time, from raw prices to a tested strategy — and an honest verdict on whether it works.
# No code to run in this lesson.
# Just read the plan below, then start with Setup.
print('Ready. Start with Setup.')
Try it yourself: Tick the Done box on this lesson and watch the progress bar move.
Check:
About 3 hours, with one 10-minute break.
A complete, working strategy pipeline you keep and can extend — data loading, features, model, and backtest.
What it is: You need Python 3.11 or newer. Install the libraries from requirements.txt: pandas, scikit-learn, lightgbm, scipy, matplotlib, yfinance, jupyter, plus the ml4t companion library for backtesting. A Docker image and a Colab notebook are provided as fallbacks if installing locally is hard. Data is free Yahoo Finance through yfinance — and a bundled ETF dataset / synthetic fallback ships with the repo, so no paid data and no brokerage account are ever needed. The practice code on this page runs offline with synthetic data and plain Python, so no API key is needed.
Why it matters: If setup is hard, you never start. Keep it to a few commands, then run the pipeline and learn by doing.
# Check your Python version (you need 3.11 or newer)
import sys
print(sys.version)
print("OK" if sys.version_info >= (3, 11) else "Please upgrade Python")
# Real workshop setup (run in your terminal, not here):
# pip install -r requirements.txt
# # pandas, scikit-learn, lightgbm, scipy, matplotlib, yfinance, jupyter
# python run_workshop.py # runs the whole pipeline end to end
# Fallbacks: a Docker image and a Colab notebook are provided.
Try it yourself: Run the code above to check your Python version. Then, in your terminal, try pip install -r requirements.txt (optional — the examples on this page run without it).
Check:
Python 3.11 or newer.
No. Yahoo Finance is free, and a synthetic fallback ships with the repo.
What it is: The source brief for this workshop said Python, pandas, scikit-learn, and LightGBM throughout — and then added one contradictory line saying to implement everything in Rust instead. The workshop was built in Python, matching every stated library, dataset, and tool (LightGBM, ml4t, Claude Code, Colab). Rust's ML and quant ecosystem is far thinner than Python's, so a Rust port would change the scope substantially, not just the syntax. If you actually want a Rust port, that is a separate job — say so explicitly.
Why it matters: Following the libraries, not the stray line, keeps the workshop runnable. Python is where the data tools, the models, and the backtesting libraries live.
# This workshop is in Python.
print('Python 3.11+, pandas, scikit-learn, LightGBM, ml4t')
Try it yourself: Write down, in one sentence, why this workshop uses Python.
Check:
Python — matching every stated library, dataset, and tool.
Rust's ML/quant ecosystem is far thinner, so a port would change the scope, not just the syntax.
What it is: This workshop optimizes for a rigorous, honest process — leakage-safe validation, realistic costs, correct signal metrics — because that process maximizes your odds of finding real, durable edge. It does not, and cannot, guarantee a profitable strategy. No legitimate workshop can promise that, and anyone who does is selling something. The included run intentionally reports its real result (a modest loss after costs on the sample data) rather than a cherry-picked win, because that is the outcome a correct backtest is supposed to be able to produce.
Why it matters: Trading is adversarial and non-stationary: other traders adapt, and markets change. A process that tells you the truth — even when the truth is 'this signal is too weak' — is worth more than a backtest that flatters you.
print('Goal: an honest process. Not a promise of profit.')
Try it yourself: Read the results section near the end of this page (mean IC 0.0027, net return -2.44%). Write one sentence about what that result teaches you.
Check:
No. It guarantees a rigorous, honest process — leakage-safe validation, realistic costs, and correct signal metrics.
Because a correct backtest must be able to produce a loss. A workshop that only ever 'wins' is hiding something.
What it is: By the end of the workshop you will be able to do six things: (1) Build a complete end-to-end ML trading strategy on real ETF market data. (2) Build a feature engineering, model training, and backtesting pipeline with AI coding-agent assistance. (3) Use an AI research agent to generate, critique, and refine trading ideas. (4) Apply purged, embargoed time-series cross-validation to prevent leakage. (5) Evaluate signal quality with the Information Coefficient and a cost-aware backtest. (6) Leave with reusable code you can point at a different universe or horizon.
Why it matters: These six objectives are the spine of the workshop. Every block below serves one of them, and the final checklist at the end tests them.
# The six objectives, as a checklist.
objectives = [
'1. Build an end-to-end ML strategy on real ETF data',
'2. Build the feature -> model -> backtest pipeline with an AI coding agent',
'3. Use an AI research agent to generate, critique, and refine ideas',
'4. Apply purged, embargoed time-series cross-validation',
'5. Evaluate with the Information Coefficient and a cost-aware backtest',
'6. Leave with reusable code for a different universe or horizon',
]
for o in objectives:
print(o)
Try it yourself: Copy the six objectives into a notebook. Tick each one off as you finish the matching block.
Check:
Six.
You leave with code you can reuse: point it at different ETFs, or a different prediction horizon, and rerun.
What it is: You should be comfortable with pandas — reading tables, grouping by date and ticker, and shifting a series. Basic ML (train/test split, fitting a model) and basic market terms (returns, features, cross-validation) help but are not required; this page explains each one in plain words first. You need a coding agent such as Claude Code for the agent-assisted build, and a research-agent workflow (prompts are provided below) that runs with any capable chat model with web search.
Why it matters: Knowing the prerequisites in advance stops you getting stuck on the wrong thing. The hard ideas in this workshop are leakage and costs, not pandas syntax.
# Quick self-check: can you read this?
import statistics
prices = [100, 101, 102, 101, 103]
rets = [(prices[i] / prices[i-1] - 1) for i in range(1, len(prices))]
print('Daily returns:', [round(r, 4) for r in rets])
print('Average return:', round(statistics.mean(rets), 4))
Try it yourself: Run the code above. If the returns make sense to you, you are ready. If not, read the plain-words box in the next block first.
Check:
No. Being comfortable with pandas is the main requirement; market terms are explained in plain words.
A coding agent (for example Claude Code) and a research-agent workflow (prompts provided, runnable with any capable chat model with web search).
What it is: In standard machine learning you shuffle your data, split it randomly, and assume tomorrow looks like yesterday. Trading breaks all three assumptions. (1) Non-stationarity: markets change — a pattern that worked in 2019 may not work in 2024. (2) Low signal-to-noise: the real signal is tiny compared with random price moves, so a model can easily 'learn' noise. (3) Autocorrelated errors: mistakes cluster together in time, so one bad week is not one bad sample, it is many. (4) Regime shifts: calm markets, crashes, and rate rises behave like different worlds. That is why this workshop uses walk-forward validation, not a random split.
Why it matters: If you treat trading like a normal ML problem, your backtest will look great and your live results will not. Every safeguard in this workshop — purging, embargo, OOS-only predictions, costs — exists because of these four facts.
# A tiny picture of non-stationarity: the same rule, two regimes.
# Calm regime: prices drift up 0.1% a day. Crash regime: prices fall 2% a day.
calm = [100 * (1.001 ** i) for i in range(5)]
crash = [100 * (0.98 ** i) for i in range(5)]
print('Calm :', [round(p, 1) for p in calm])
print('Crash :', [round(p, 1) for p in crash])
print('One rule cannot fit both. That is non-stationarity.')
Try it yourself: Write one sentence for each of the four problems (non-stationarity, low signal-to-noise, autocorrelated errors, regime shifts) in your own words.
Check:
Because shuffling destroys time order, and the label depends on time — plus markets change, so tomorrow does not look like yesterday.
The real signal is tiny compared with random price moves, so a model can easily learn noise instead of signal.
What it is: The whole strategy is four small Python modules, in a chain: data_pipeline.py loads the prices, features.py builds features and the label, model_cv.py trains the model with leakage-safe validation, backtest.py turns predictions into a portfolio and measures it. run_workshop.py runs all four in order and writes the charts and results_summary.md. Every module speaks the same language: a long-format table indexed by (date, ticker) with OHLCV columns — Open, High, Low, Close, Volume. OHLCV is just the price record for one day: the price at the open, the highest and lowest prices during the day, the price at the close, and how much was traded.
Why it matters: Four small modules beat one big script. You can test each one alone, swap one out, and point the whole chain at a different universe by changing one list.
# The pipeline, in order. Each step hands its output to the next.
steps = [
'1. data_pipeline.py -> (date, ticker) OHLCV panel',
'2. features.py -> features + forward-return label',
'3. model_cv.py -> out-of-sample predictions + IC per fold',
'4. backtest.py -> portfolio, costs, Sharpe, drawdown',
' run_workshop.py -> runs 1-4, writes charts + results_summary.md',
]
for s in steps:
print(s)
Try it yourself: Draw the four modules as four boxes with arrows between them. Under each box, write what goes in and what comes out.
Check:
It loads the prices — real Yahoo Finance data, or the synthetic fallback — into a long-format (date, ticker) OHLCV table.
A long-format table indexed by (date, ticker), with OHLCV columns. Every module depends on it.
What it is: Point Claude Code at the empty repo skeleton and prompt: 'Scaffold a 4-module Python pipeline: data loading (yfinance + offline fallback), feature engineering, purged walk-forward CV with a gradient-boosted model, and a cost-aware backtest. Long-format (date, ticker) OHLCV schema throughout.' Then compare its scaffold to the reference implementation in the repo — discuss where it diverges and why. Give it the module docstrings as context, and ask it to preserve the (date, ticker) MultiIndex contract, since every module depends on it.
Why it matters: An AI coding agent is fast at scaffolding, but it does not know your contracts unless you tell it. Comparing its scaffold with the reference teaches you what the agent got right, what it guessed, and where your instructions were vague.
# The exact prompt to give the coding agent (copy it as text):
prompt = (
'Scaffold a 4-module Python pipeline: data loading (yfinance + '
'offline fallback), feature engineering, purged walk-forward CV with '
'a gradient-boosted model, and a cost-aware backtest. Long-format '
'(date, ticker) OHLCV schema throughout.'
)
print(prompt)
print()
print('Then compare its scaffold with the reference, module by module.')
Try it yourself: Run the prompt above with your coding agent on an empty folder. List three ways its scaffold differs from the reference modules.
Check:
The module docstrings, and the instruction to preserve the (date, ticker) MultiIndex contract.
Compare its scaffold to the reference implementation, and discuss where it diverges and why.
What it is: Pull ten ETFs with free daily history — no paid feed: SPY (US large stocks), QQQ (US tech-heavy stocks), IWM (US small stocks), EFA (developed markets outside the US), EEM (emerging markets), TLT (long US government bonds), IEF (medium US government bonds), GLD (gold), USO (oil), XLK (US technology sector). Together they span equities, rates, and commodities, so the model learns across different kinds of markets, not just one index. In the real code this is load_data(UNIVERSE, start='2010-01-01', prefer_real=True) — it tries Yahoo Finance first and falls back to the bundled synthetic data if there is no internet.
Why it matters: A diverse universe is the point: a signal that only works on one ETF is probably noise. Ten different ETFs, across three asset classes, give the model something real to learn from.
# The universe, with what each ETF holds (plain words).
UNIVERSE = ['SPY', 'QQQ', 'IWM', 'EFA', 'EEM', 'TLT', 'IEF', 'GLD', 'USO', 'XLK']
meaning = {'SPY': 'US large stocks', 'QQQ': 'US tech-heavy stocks',
'IWM': 'US small stocks', 'EFA': 'developed markets ex-US',
'EEM': 'emerging markets', 'TLT': 'long US gov bonds',
'IEF': 'medium US gov bonds', 'GLD': 'gold',
'USO': 'oil', 'XLK': 'US technology sector'}
for t in UNIVERSE:
print(t, '-', meaning[t])
print()
print('Real code: load_data(UNIVERSE, start="2010-01-01", prefer_real=True)')
Try it yourself: Pick two ETFs from the list and write, in one sentence each, what market they represent.
Check:
Ten ETFs, spanning equities, rates, and commodities.
The loader falls back to the bundled synthetic data, so the pipeline still runs.
What it is: Features are numbers computed from past prices that might predict the next move. All of them are computed strictly from information available at close of day t — nothing from the future. The repo builds: momentum over 5, 10, 21, and 63 days (how much the price moved), 1-day return, volatility over 21 and 63 days (how jumpy the price has been), RSI over 14 days (a 0-100 score: high means the price rose a lot recently), moving-average ratio 10-day over 50-day (is the short trend above the long trend?), range (high minus low, divided by close), close-to-high, volume z-score over 21 days (is volume unusual?), skew over 21 days (are the big moves up or down?), and cross-sectional rank features (how strong is this ETF compared with the others today?).
Why it matters: Features are the model's eyes. Good features describe the market in several ways at once — trend, jumpiness, strength, and relative position — so the model is not betting everything on one number.
# Momentum, volatility, and RSI in plain Python (no libraries needed).
# Real code in features.py does the same with pandas rolling windows.
closes = [100, 101, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111]
def momentum(prices, w):
return prices[-1] / prices[-1 - w] - 1
def volatility(rets):
mean = sum(rets) / len(rets)
return (sum((r - mean) ** 2 for r in rets) / len(rets)) ** 0.5
rets = [closes[i] / closes[i-1] - 1 for i in range(1, len(closes))]
print('Momentum 5d :', round(momentum(closes, 5), 4))
print('Momentum 10d:', round(momentum(closes, 10), 4))
print('Volatility :', round(volatility(rets), 4))
print()
print('Real code: f["mom_5"] = close.pct_change(5); f["vol_21"] = ret1.rolling(21).std()')
print(' f["rsi_14"] = _rsi(close, 14); f["sma_ratio_10_50"] = close.rolling(10).mean() / close.rolling(50).mean() - 1')
Try it yourself: Using the closes list above, change the last price to 115 and recompute momentum 5d. Does it go up or down? Why?
Check:
A 0-100 score over 14 days: high means the price rose a lot recently, low means it fell a lot recently.
How strong one ETF is compared with the other ETFs on the same date — its rank within that day, not across all of history.
What it is: Leakage is the silent killer of trading ML: information from the future sneaking into a feature or a label, so the backtest looks great and live trading fails. Two rules. (1) The forward-return label must be shifted: the label for day t is the return from close of day t to close of day t+5, computed as close.shift(-5) / close - 1. The last 5 rows per ticker have no label and are dropped — they have no future to predict. If you forget the shift, the model 'predicts' a return it has already seen. (2) Cross-sectional ranks must be computed within each date, not across the whole panel: rank the 10 ETFs against each other on the same day. Ranking across all dates mixes the future into the past.
Why it matters: Most 'amazing' trading results are leakage, not skill. These two rules are the difference between a model that learned something real and a model that cheated.
# The label: forward 5-day return. Row t uses only data through t+horizon
# that occurs strictly AFTER t. The last rows have no label and are dropped.
closes = [100, 101, 102, 101, 103, 105, 104, 106, 108, 107]
HORIZON = 5
labels = []
for i in range(len(closes)):
if i + HORIZON < len(closes):
labels.append(round(closes[i + HORIZON] / closes[i] - 1, 4))
else:
labels.append(None) # no future yet: drop this row
print('Closes:', closes)
print('Labels:', labels)
print()
print('Real code: f["fwd_ret"] = close.shift(-HORIZON) / close - 1')
print('Cross-sectional ranks are computed within each date, never across the whole panel.')
Try it yourself: Take the closes list above. What is the label for day 0? Now imagine you forgot the shift and used the return from day 0 to day 0 — what would the model 'learn'?
Check:
So the label for day t is the return after day t. Without the shift, the model sees the answer it is supposed to predict.
Ranking across all dates mixes the future into the past. Rank the ETFs against each other on the same day only.
What it is: Standard k-fold CV shuffles the data and splits it randomly. For time series that is wrong twice over. First, shuffling destroys the time order the label depends on — a test row from January can sit next to training rows from March, so the model trains on the future. Second, with a 5-day forward label, training rows near a test row share the same future prices: their label windows overlap the test window. The model is not predicting the future; it is remembering it. That is why the workshop uses walk-forward CV instead: train on the past, test on the next slice of time, then step forward.
Why it matters: A random split gives you a flattering number and a false sense of safety. Walk-forward is slower and stricter — and honest.
# Why shuffling is wrong: the label window overlaps.
# Label for day 10 looks at days 10..15. A training row from day 12
# looks at days 12..17. They share days 12..15. That is leakage.
HORIZON = 5
train_day, test_day = 12, 10
print('Test label window : days', test_day, '..', test_day + HORIZON)
print('Train label window : days', train_day, '..', train_day + HORIZON)
print('Overlap: days 12..15 are in BOTH. The model has seen the test answer.')
print()
print('Fix: walk forward. Train on the past, test on the next slice, step forward.')
Try it yourself: Draw a timeline of 20 days. Mark a test window (days 10-15) and a training row at day 12. Shade the overlap. That shaded part is the leakage.
Check:
It shuffles the data, so training rows can come from after the test rows — the model trains on the future.
Train on the past, test on the next slice of time, then step forward and repeat.
What it is: Purged and embargoed walk-forward CV is the fix, from Marcos Lopez de Prado. Purge: delete every training row whose label window overlaps the test window — if a training row's 5-day label touches the test period, throw it out. Embargo: after each test fold, skip a buffer of 5 days before training resumes, because information leaks across the boundary even without a direct overlap. The workshop runs 6 walk-forward folds, purged (5-day) and embargoed (5-day), with horizon 5. In the real code this is run_cv(feat, n_splits=6, horizon=HORIZON, embargo=HORIZON).
Why it matters: Purging removes the direct leak. The embargo removes the indirect leak. Together they are the standard way serious quants validate a time-series model.
# Purged + embargoed splits, in plain Python.
# Test fold: days 100..119. Label horizon 5, embargo 5.
# Purge: drop training rows whose label window touches days 100..119.
# Embargo: skip days 120..124 before training resumes.
HORIZON, EMBARGO = 5, 5
test_start, test_end = 100, 119
purge_from = test_start - HORIZON # label windows starting here reach into the test fold
embargo_to = test_end + EMBARGO
print('Test fold :', test_start, '..', test_end)
print('Purge training rows with label windows starting at', purge_from, 'or later')
print('Embargo : skip days', test_end + 1, '..', embargo_to, 'before training resumes')
print()
print('Real code: run_cv(feat, n_splits=6, horizon=HORIZON, embargo=HORIZON)')
Try it yourself: With a test fold of days 100-119 and horizon 5, which training rows must be purged? Write the rule in one sentence.
Check:
Delete training rows whose label window overlaps the test window.
After each test fold, skip a buffer of days before training resumes, because information leaks across the boundary.
What it is: Per fold, train a gradient-boosted model: LightGBM, or its sklearn equivalent HistGradientBoostingRegressor (the included run used sklearn because LightGBM was not installed locally). Gradient boosting builds many small decision trees, one after another, each one fixing the mistakes of the ones before it. It handles tabular features well, needs little tuning, and gives feature importances you can read. In the real code this is make_model(), then model.fit(X_train, y_train) inside each fold — never on the whole dataset at once, and never on the test fold.
Why it matters: One model per fold, trained only on the past, is the whole point of walk-forward validation. A single model trained on everything would leak.
# Gradient boosting in plain words: many small trees, each fixing the
# mistakes of the ones before it. Here is the sklearn equivalent
# (LightGBM is the first choice in the real code; this is its fallback).
# Real code:
# from model_cv import make_model
# model = make_model() # LightGBM if installed, else HistGradientBoostingRegressor
# model.fit(X_train, y_train) # X_train: features, y_train: forward returns
# preds = model.predict(X_test) # only on the test fold, never seen in training
#
# A tiny stand-in: predict with the average of the training labels.
train_labels = [0.01, -0.02, 0.03, 0.00, 0.02]
baseline = sum(train_labels) / len(train_labels)
print('Baseline prediction (mean of training labels):', round(baseline, 4))
print('The real model does better than this baseline — if it has real signal.')
Try it yourself: In one sentence, what does gradient boosting do? Then write down why you train one model per fold instead of one model on everything.
Check:
A gradient-boosted model: many small decision trees built one after another, each fixing the mistakes of the ones before it.
sklearn HistGradientBoostingRegressor, because LightGBM was not installed locally.
What it is: The Information Coefficient is the standard signal-quality metric on real trading desks. For each date, take the model's predicted forward returns and the realized forward returns, rank both, and compute the Spearman correlation between the two ranks. Then average that correlation across dates. An IC of 0 means the model predicts nothing. A positive IC means the model's ranking points the right way. Real-world cross-sectional equity/ETF signals typically run 0.02-0.08. Anything far outside that range on real data is a leakage red flag, not a win — it means the model probably saw the answer.
Why it matters: IC measures ranking, not size: it asks 'did the model put the winners above the losers?', which is exactly what a long/short portfolio needs.
# Spearman correlation in plain Python: rank both lists, then correlate the ranks.
def ranks(values):
order = sorted(range(len(values)), key=lambda i: values[i])
r = [0] * len(values)
for rank, i in enumerate(order):
r[i] = rank
return r
def spearman(a, b):
ra, rb = ranks(a), ranks(b)
n = len(a)
ma, mb = sum(ra) / n, sum(rb) / n
num = sum((ra[i] - ma) * (rb[i] - mb) for i in range(n))
den = (sum((x - ma) ** 2 for x in ra) * sum((x - mb) ** 2 for x in rb)) ** 0.5
return num / den if den else 0.0
predicted = [0.02, 0.01, -0.01, 0.03, -0.02]
realized = [0.03, 0.00, -0.02, 0.04, -0.01]
print('IC for this date:', round(spearman(predicted, realized), 4))
print('Real signals usually run 0.02-0.08. Far outside that = leakage red flag.')
Try it yourself: Change the last realized value from -0.01 to +0.05. What happens to the IC? Why?
Check:
For each date, the rank correlation between predicted and realized forward returns, averaged across dates. It measures whether the model ranks winners above losers.
Typically 0.02-0.08. Anything far outside that on real data is a leakage red flag, not a win.
What it is: Prompt a research agent with the fold-by-fold IC table and ask it to do three things: (a) flag any fold whose IC looks implausibly high (a leakage smell), (b) propose two alternative feature families to test, and (c) write the null hypothesis your IC needs to beat. The null hypothesis is the boring explanation: 'the model predicts nothing; the IC is zero, and any positive number is luck.' Your IC has to beat that, consistently, across folds — not just in one fold.
Why it matters: A research agent is good at critiquing, not just generating. Asking it to red-team your own result is how you stop fooling yourself.
# The three questions to give the research agent (copy them as text):
questions = [
'1. Flag any fold whose IC looks implausibly high (leakage smell).',
'2. Propose two alternative feature families to test.',
'3. Write the null hypothesis my IC needs to beat.',
]
for q in questions:
print(q)
print()
print('Null hypothesis: the model predicts nothing; IC = 0, and any positive IC is luck.')
Try it yourself: Write the null hypothesis for your own IC in one sentence. Then write one reason a single high-IC fold might be luck.
Check:
One fold with an implausibly high IC — far above 0.02-0.08 — which usually means the model saw the answer, not that it found gold.
'The model predicts nothing; the IC is zero, and any positive number is luck.'
What it is: Take a 10-minute break. Stand up, stretch, get water. When you come back, the second half starts: turning out-of-sample predictions into a portfolio, adding real costs, and finding out whether the strategy survives them. That is where most 'great' models turn mediocre — and that is the lesson.
Why it matters: A break is part of the workshop, not a gap in it. The backtest block needs fresh eyes.
print('Break over. Block 4: the cost-aware backtest.')
Try it yourself: During the break, write down one prediction: will the strategy survive costs? Keep it, and check it after Block 4.
Check:
10 minutes.
Block 4: the cost-aware backtest.
What it is: Take only out-of-sample predictions — predictions made by a model that never saw those rows in training. Never use in-sample fitted values; they are the model's memory, not its skill. Each rebalance date, rank the 10 ETFs by predicted return, go long the top 30% (the 3 best) and short the bottom 30% (the 3 worst), equal-weighted, dollar-neutral — meaning the long side and the short side hold the same amount of money, so the portfolio is not simply betting that the market goes up. The middle 4 ETFs are held in nothing. In the real code this is run_backtest(oos_preds, panel, horizon=HORIZON, cost_bps=COST_BPS).
Why it matters: Dollar-neutral long/short is the cleanest test of ranking skill: if the model ranks well, the longs beat the shorts, whatever the market does.
# Long top 30% / short bottom 30%, dollar-neutral, equal-weighted.
# 10 ETFs: long the 3 best predicted, short the 3 worst predicted.
predicted = {'SPY': 0.02, 'QQQ': 0.03, 'IWM': -0.01, 'EFA': 0.01, 'EEM': -0.02,
'TLT': 0.00, 'IEF': -0.01, 'GLD': 0.02, 'USO': -0.03, 'XLK': 0.04}
ranked = sorted(predicted, key=lambda t: predicted[t], reverse=True)
longs, shorts = ranked[:3], ranked[-3:]
print('Long :', longs, ' (weight +1/3 each)')
print('Short:', shorts, ' (weight -1/3 each)')
print('Middle 4 held in nothing. Longs and shorts hold the same money: dollar-neutral.')
print()
print('Real code: run_backtest(oos_preds, panel, horizon=HORIZON, cost_bps=COST_BPS)')
Try it yourself: Using the predicted values above, what happens if XLK is actually the worst performer next week? Which side loses?
Check:
In-sample fitted values are the model's memory, not its skill. Only OOS predictions test whether it can predict unseen data.
The long side and the short side hold the same amount of money, so the portfolio is not just betting the market goes up.
What it is: Every rebalance you buy and sell, and every trade costs money. Turnover is how much of the portfolio changes at each rebalance — in the included run, 69.79% per rebalance, which is high. Cost is charged per trade in basis points: 1 basis point is 0.01%, so 10 basis points is 0.10% per trade. Compare the gross equity curve (no costs) with the net curve (after costs), side by side. This is usually where a 'great' model turns mediocre, and that is the lesson: a weak signal gets eaten by turnover and costs. Change COST_BPS in backtest.py and rerun run_workshop.py to see it yourself.
Why it matters: Costs are not a detail. They are the difference between a strategy that works on paper and one that works in real life.
# Costs in basis points: 1 bp = 0.01%. High turnover x cost = the signal gets eaten.
COST_BPS = 10 # 10 basis points per trade = 0.10%
turnover = 0.6979 # 69.79% of the portfolio changes each rebalance
rebalances_per_year = 52
cost_drag = turnover * (COST_BPS / 10000) * rebalances_per_year
print('Turnover per rebalance:', round(turnover * 100, 2), '%')
print('Cost drag per year :', round(cost_drag * 100, 2), '%')
print()
print('Included run: cost drag 1.76% per year. Gross return -0.71%, net -2.44%.')
print('Change COST_BPS in backtest.py and rerun run_workshop.py to see it change.')
Try it yourself: If turnover is 70% and cost is 10 bps per trade, what is the cost per rebalance? (Hint: 70% x 0.10%.)
Check:
0.01%. So 10 basis points is 0.10% per trade.
1.76% per year — the difference between the gross return (-0.71%) and the net return (-2.44%).
What it is: Four numbers tell you how the backtest did. Sharpe ratio: return divided by volatility — how much return you got per unit of bumpiness. A Sharpe of 1 is good, 0 is nothing, negative means you lost money for the bumps. Max drawdown: the biggest fall from a peak to a trough — in the included run, -88.94% net, which means the portfolio at its worst was worth about 11% of its peak. Hit rate: the share of rebalances that made money (48.62% net — slightly worse than a coin flip). Cost drag: how much return costs ate each year (1.76%).
Why it matters: These four numbers together are honest. Return alone lies; return plus volatility, drawdown, hit rate, and costs tells the truth.
# Sharpe and max drawdown in plain Python.
def sharpe(returns, risk_free=0.0):
mean = sum(returns) / len(returns)
var = sum((r - mean) ** 2 for r in returns) / len(returns)
return (mean - risk_free) / (var ** 0.5) if var else 0.0
def max_drawdown(equity):
peak, worst = equity[0], 0.0
for v in equity:
peak = max(peak, v)
worst = min(worst, v / peak - 1)
return worst
rets = [0.01, -0.02, 0.015, -0.01, 0.005, -0.03, 0.02]
equity = [1.0]
for r in rets:
equity.append(equity[-1] * (1 + r))
print('Sharpe (daily, toy example):', round(sharpe(rets), 3))
print('Max drawdown :', round(max_drawdown(equity) * 100, 2), '%')
print()
print('Included run, net: return -2.44%, vol 5.79%, Sharpe -0.43, max drawdown -88.94%, hit rate 48.62%.')
Try it yourself: Using the equity list above, find the peak and the lowest point after it. What is the drawdown?
Check:
Return divided by volatility — how much return you got per unit of bumpiness. Negative means you lost money for the bumps.
The biggest fall from a peak to a trough. In the included run it was -88.94% net.
What it is: Ask Claude Code to add a stress test: rerun the backtest restricted to the worst-volatility quartile of dates — the 25% of days when the market was most jumpy. Then interpret the result: if the strategy only makes money (or only loses money) on the wild days, it is a volatility-regime bet in disguise, not a general signal. A real, durable signal should work across regimes, not just in one kind of weather.
Why it matters: Stress tests are how you find out what your strategy really is. A strategy that only works in a crash is not a strategy; it is a crash bet.
# Stress test idea: split dates into volatility quartiles, backtest each one.
# If the strategy only works in the wildest quartile, it is a regime bet.
# Prompt to give the coding agent (copy it as text):
prompt = (
'Add a stress test to backtest.py: rerun the backtest restricted to '
'the worst-volatility quartile of dates (top 25% by realized volatility), '
'and report Sharpe and return for that quartile vs the full sample.'
)
print(prompt)
print()
print('Interpretation: if the result lives only in the wild quartile,')
print('the strategy is a volatility-regime bet in disguise.')
Try it yourself: Write one sentence: what would it mean if the strategy only made money in the worst-volatility quartile?
Check:
Rerun the backtest restricted to the worst-volatility quartile of dates — the 25% of days when the market was most jumpy.
It is a volatility-regime bet in disguise, not a general signal.
What it is: Four knobs, in order: (1) Horizon — HORIZON in features.py, currently 5 trading days. A longer horizon (20 days) is slower and smoother; a shorter one (1 day) is noisier. (2) Cost assumptions — COST_BPS in backtest.py. Real costs depend on what you trade and how big you are. (3) Position sizing — how much money goes into each long and short, and whether you cap any single ETF. (4) Feature set — add a feature family, remove a weak one, and rerun run_workshop.py to see if the IC improves. Swap the universe, horizon, or cost assumption and rerun run_workshop.py — the whole pipeline recomputes end to end.
Why it matters: Start with the knobs, not the model. Changing the horizon or the costs changes the answer more than tuning the model does.
# The four knobs, and where they live.
knobs = [
('Horizon ', 'HORIZON in features.py (now 5 trading days)'),
('Cost ', 'COST_BPS in backtest.py (per-trade cost in basis points)'),
('Position size ', 'weights in backtest.py (equal-weighted now; cap any single ETF)'),
('Features ', 'build_features() in features.py (add or remove a family)'),
]
for name, where in knobs:
print(name, '-', where)
print()
print('Then rerun: python run_workshop.py # the whole pipeline recomputes')
Try it yourself: Pick one knob and write down what you would change first, and why.
Check:
HORIZON in features.py — currently 5 trading days.
COST_BPS in backtest.py.
What it is: This pipeline is a research workshop, not a production trading system. Production quant infrastructure starts where this stops: execution modeling (how your order actually gets filled), capacity and slippage at real size (your trades move the price when you are big), live monitoring (is the signal still working today?), and point-in-time data hygiene (making sure the data you used was actually available at the time you pretend to trade on it). Do not skip these before risking real money.
Why it matters: Knowing where the pipeline stops is as important as knowing what it does. The gap between a research backtest and live trading is where most money is lost.
print('Research pipeline: done. Production: execution, capacity, slippage, monitoring, point-in-time data.')
Try it yourself: Write down the four production topics in your own words, and one sentence on why each one matters.
Check:
Your trade moves the price against you, so you get a worse price than the one on screen — bigger when your position is bigger.
Making sure the data you used was actually available at the time you pretend to trade on it — no future data sneaking in.
What it is: You leave with six files. data_pipeline.py: real yfinance + synthetic-fallback ETF OHLCV loader. features.py: leakage-safe feature + forward-return label builder. model_cv.py: purged/embargoed walk-forward CV, LightGBM/HGB model, IC scoring. backtest.py: cost-aware long/short backtest on OOS predictions only. run_workshop.py: orchestrates all four modules, produces charts + results_summary.md. requirements.txt: everything needed to run locally. Swap the universe, horizon (HORIZON in features.py), or cost assumption (COST_BPS in backtest.py) and rerun run_workshop.py.
Why it matters: Six small files, each with one job, is a pipeline you can actually reuse. That is the deliverable.
# The six artifacts, and what each one does.
artifacts = [
('data_pipeline.py', 'real yfinance + synthetic-fallback ETF OHLCV loader'),
('features.py ', 'leakage-safe feature + forward-return label builder'),
('model_cv.py ', 'purged/embargoed walk-forward CV, LightGBM/HGB, IC scoring'),
('backtest.py ', 'cost-aware long/short backtest on OOS predictions only'),
('run_workshop.py ', 'orchestrates all four; produces charts + results_summary.md'),
('requirements.txt', 'everything needed to run locally'),
]
for f, d in artifacts:
print(f, '-', d)
Try it yourself: List the six artifacts from memory, then check yourself against the list above.
Check:
run_workshop.py — it orchestrates all four modules.
backtest.py — COST_BPS.
What it is: The coding agent (for example Claude Code) is best used for: scaffolding modules, writing tests for the purge/embargo split logic, refactoring the feature builder when you add a new indicator, and adding the volatility-regime stress test in Block 4. Give it the module docstrings in this repo as context, and ask it to preserve the (date, ticker) MultiIndex contract, since every module depends on it.
Why it matters: Use the coding agent for code, not for judgement. It writes the scaffolding fast; you decide whether the logic is right.
# What to ask the coding agent for:
asks = [
'Scaffold the 4-module pipeline',
'Write tests for the purge/embargo split logic',
'Refactor the feature builder when I add an indicator',
'Add the volatility-regime stress test',
]
for a in asks:
print('-', a)
print('Always: preserve the (date, ticker) MultiIndex contract.')
Try it yourself: Write a one-line instruction to a coding agent that tells it to preserve the (date, ticker) contract.
Check:
Scaffolding modules, writing tests for the purge/embargo logic, refactoring the feature builder, and adding the stress test.
The module docstrings, and the instruction to preserve the (date, ticker) MultiIndex contract.
What it is: The research agent is best used for: critiquing IC results for leakage smells, proposing and briefly justifying new feature families (it should cite why a feature might carry signal, not just list ideas), and red-teaming your backtest assumptions — cost bps, quantile thresholds, rebalance frequency — before you trust a result. It runs with any capable chat model with web search.
Why it matters: A research agent's job is to argue with you. If it cannot find a hole in your result, the result is stronger. If it can, you just saved yourself money.
# What to ask the research agent for:
asks = [
'Critique my IC results for leakage smells',
'Propose new feature families, with a why for each',
'Red-team my backtest assumptions: cost bps, quantiles, rebalance frequency',
]
for a in asks:
print('-', a)
Try it yourself: Write one backtest assumption (for example, cost bps) and ask a research agent to red-team it. Write down its strongest objection.
Check:
Why the feature might carry signal — not just a list of ideas.
Attack the assumptions — cost bps, quantile thresholds, rebalance frequency — before you trust the result.
What it is: Here is the reusable prompt template for the research agent, word for word. Paste your fold table, IC summary, or backtest stats where it says Context. It says at the top: you are reviewing a quant research result, not producing investment advice. Then three questions: (1) Does anything here look like a leakage artifact? Why or why not? (2) Propose 2 alternative feature families with a one-line economic rationale each. (3) What is the strongest argument this result doesn't generalize out of sample?
Why it matters: A fixed template makes the critique repeatable. Same three questions, every result, every time — so you compare results fairly.
# The research-agent prompt template, verbatim. Copy it as text.
template = """You are reviewing a quant research result, not producing investment advice.
Context: [paste fold table / IC summary / backtest stats]
1. Does anything here look like a leakage artifact? Why or why not?
2. Propose 2 alternative feature families with a one-line economic rationale each.
3. What is the strongest argument this result doesn't generalize out of sample?"""
print(template)
Try it yourself: Copy the template above, paste your own IC summary into the Context line, and run it with a chat model. Write down its answer to question 3.
Check:
'You are reviewing a quant research result, not producing investment advice.' It keeps the agent in a reviewing role, not an advising one.
The strongest argument that this result doesn't generalize out of sample — the best case against your own strategy.
What it is: Here are the real results from the included run, in full, with nothing hidden. Model backend: sklearn HistGradientBoostingRegressor (LightGBM not installed locally). Universe: SPY, QQQ, IWM, EFA, EEM, TLT, IEF, GLD, USO, XLK. Label: 5-trading-day forward return. Validation: 6 walk-forward folds, purged (5-day) and embargoed (5-day). Mean out-of-sample IC: 0.0027. Backtest, net of costs: annualized return -2.44%, vol 5.79%, Sharpe -0.43, max drawdown -88.94%, hit rate 48.62%, average turnover 69.79%, cost drag 1.76%. Gross (no costs): return -0.71%, Sharpe -0.12, max drawdown -76.49%, hit rate 50.05%.
Why it matters: These numbers are the point of the workshop. A weak signal, eaten by turnover and costs, is a normal, useful outcome — it shows exactly why cost-aware backtesting and purged CV exist.
# The included run, as a table you can check.
results = [
('Mean OOS IC ', '0.0027'),
('Net return (annualized)', '-2.44%'),
('Net vol (annualized) ', '5.79%'),
('Net Sharpe ', '-0.43'),
('Net max drawdown ', '-88.94%'),
('Net hit rate ', '48.62%'),
('Avg turnover/rebalance ', '69.79%'),
('Cost drag (annualized) ', '1.76%'),
('Gross return ', '-0.71%'),
('Gross Sharpe ', '-0.12'),
]
for k, v in results:
print(k, ':', v)
print()
print('Model: sklearn HistGradientBoostingRegressor. Label: 5-day forward return.')
Try it yourself: Write the net return, Sharpe, and max drawdown from memory, then check them against the table.
Check:
0.0027 — far below the 0.02-0.08 range of real signals.
-2.44%. Turnover (69.79% per rebalance) and costs (1.76% drag per year) ate a weak signal.
What it is: Three honest readings. First, these numbers are from synthetic data unless yfinance + internet were available when you ran this — check the '[data]' log line at startup. Second, a small or negative Sharpe here is a normal, useful workshop outcome, not a failure: it shows exactly how much a weak signal gets eaten by turnover and transaction costs — the whole reason cost-aware backtesting and purged CV exist. A strategy that only 'works' ungated by costs, or only in-sample, is not a strategy. Third, nothing here is investment advice or a claim of live profitability. Past and simulated performance do not predict future results.
Why it matters: Honest reading is a skill. The numbers are not good or bad on their own — they are evidence, and the evidence here says: weak signal, high turnover, costs win.
print('Synthetic data unless yfinance was available. Negative Sharpe = normal, useful outcome.')
Try it yourself: Write one sentence explaining to a friend why a negative Sharpe in this workshop is useful, not a failure.
Check:
It shows how a weak signal gets eaten by turnover and costs — the exact lesson cost-aware backtesting exists to teach.
Check the '[data]' log line at startup.
What it is: This is educational material, not investment advice, and no output here is a guarantee — or even an expectation — of future profit. Markets are adversarial and non-stationary; a signal that scores well historically can decay or vanish. Before deploying real capital: paper-trade extensively, test across multiple regimes, model capacity and slippage at your actual position size, and consult a licensed financial professional.
Why it matters: This disclaimer is not fine print. It is the most important paragraph in the workshop.
print('Educational material only. Not investment advice. No guarantee of profit.')
Try it yourself: Write down the four steps to take before deploying real capital.
Check:
No. It is educational material only.
Paper-trade extensively, test across multiple regimes, model capacity and slippage at your actual position size, and consult a licensed financial professional.
What it is: Tick each item when you can do it: (1) I can explain why trading ML is not standard supervised learning. (2) I ran run_workshop.py end to end. (3) I can explain leakage, and why the label is shifted and ranks are within each date. (4) I can explain purged + embargoed CV. (5) I can explain the Information Coefficient and what 0.0027 means. (6) I can build the long-top-30% / short-bottom-30% portfolio. (7) I can explain gross vs net, Sharpe, drawdown, hit rate, and cost drag. (8) I ran the volatility-regime stress test. (9) I can change the universe, horizon, or costs and rerun. (10) I can state the disclaimer in my own words.
Why it matters: A checklist turns a workshop into a skill. If you cannot tick an item, go back to its block — it is listed next to each item below.
# Final checklist — tick each one in your notebook.
items = [
'Explain why trading ML is not standard ML',
'Run run_workshop.py end to end',
'Explain leakage: shifted label, ranks within each date',
'Explain purged + embargoed CV',
'Explain the Information Coefficient (and 0.0027)',
'Build the long/short top-30% / bottom-30% portfolio',
'Explain gross vs net, Sharpe, drawdown, hit rate, cost drag',
'Run the volatility-regime stress test',
'Change universe / horizon / costs and rerun',
'State the disclaimer in your own words',
]
for i, it in enumerate(items, 1):
print(f'{i}. [ ] {it}')
Try it yourself: Go through the checklist. For every item you cannot tick, write down which block to revisit.
Check:
Ten.
Go back to its block and redo it — the checklist is a test, not a formality.
What it is: Next steps, in order. (1) Change one knob — the universe, the horizon, or the cost assumption — and rerun run_workshop.py. See how the IC and the net return move. (2) Add one new feature family, with an economic reason why it might carry signal, and test it. (3) Run the research-agent prompt template on your new result. (4) Next in the repo: Quant Research with AI Agents — the full research workflow this workshop follows. (5) Then the Financial agent workshop in the repo, for a production-style agent system on bare Debian. And always: paper-trade before risking real capital.
Why it matters: One knob at a time. Change everything at once and you will never know what helped.
print('Next: change one knob, rerun, then Quant Research with AI Agents.')
Try it yourself: Pick your first knob to change (universe, horizon, or costs) and write it down.
Check:
One knob — the universe, the horizon, or the cost assumption — then rerun run_workshop.py.
Quant Research with AI Agents, then the Financial agent workshop.
© 2026 Oswaldo Bentti. All rights reserved.
All courses · Ozbit News · quantbite.io · www.linkedin.com/in/ozbit