Courses  /  Finance & Trading

Quant Research with AI Agents

Full Course / Workshop Intermediate Python No paid data needed

Learning material, not investment advice. This workshop teaches a rigorous, honest process for testing trading ideas. It does not promise profit, and no output here is a guarantee of future results. Before risking real money: paper-trade extensively, test across multiple regimes, model capacity and slippage at your actual position size, and consult a licensed financial professional.

Build a complete end-to-end machine learning trading strategy on real ETF market data — with AI coding agents building the pipeline and AI research agents generating, validating, and refining the ideas. This page is about how AI agents change the quant workflow. The companion lab, ML Trading Strategy, End to End, in the Workshop folder next to this page, has the full hands-on pipeline code.

How to use this workshop

What it is

Read in order, one lesson at a time. 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 or prompts you can copy, a small task to try yourself, and two check questions with the answers hidden until you open them. This workshop is closely related to the companion Hands-On ML Trading Strategy workshop in this same Workshop folder — that one is the hands-on lab with the full pipeline code. This page is about how AI agents change the quant workflow: what the coding agent does, what the research agent does, and how you go from a rule-based idea to a structured, reproducible ML workflow.

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 — and the demo at the end lets you run the whole agent workflow on your own idea.

Code / prompts to copy

# No code to run in this lesson.
# Just read the plan, 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

What is the difference between this page and the Hands-On ML Trading Strategy workshop?

That page is the companion hands-on lab with the full pipeline code. This page is about how AI agents change the quant workflow — generating, validating, and refining ideas with agents.

What do you walk away with?

Reusable code, notebooks, and a practical workflow you can adapt to your own trading and financial ML projects.

Setup — what you need

What it is

You need Python 3.11 or newer, with pandas, scikit-learn, LightGBM, scipy, matplotlib, and yfinance, plus the ml4t companion library for backtesting — all open-source, installed from requirements.txt. 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. 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. The practice code on this page runs offline with synthetic data and plain Python, so no API key is needed for the practice here. A Docker image and a Colab notebook are provided as fallbacks if installing locally is hard.

Why it matters

If setup is hard, you never start. Keep it to a few commands, then run the pipeline and learn by doing.

Code / prompts to copy

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

Check

What Python version do you need?

Python 3.11 or newer.

Do you need a paid data feed or a brokerage account?

No. Yahoo Finance is free, and a synthetic fallback ships with the repo.

A plain note: learning material, not investment advice

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: other traders adapt, and a signal that scores well historically can decay or vanish. 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. The included run in the companion lab intentionally reports its real result (a modest loss after costs) rather than a cherry-picked win, because that is the outcome a correct backtest is supposed to be able to produce. 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

Trading is adversarial: you are competing with other people who are also trying to win. 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.

Code / prompts to copy

print('Goal: an honest process. Not a promise of profit.')

Try it yourself

Write one sentence, in your own words, about what 'not investment advice' means for this workshop.

Check

Does this workshop guarantee a profitable strategy?

No. It guarantees a rigorous, honest process — leakage-safe validation, realistic costs, and correct signal metrics.

What should you do before risking real money?

Paper-trade extensively, test across multiple regimes, model capacity and slippage at your real position size, and consult a licensed financial professional.

By the end of this workshop, you will have — the six outcomes

What it is

By the end of this workshop, you will have: (1) Built a complete end-to-end machine learning trading strategy using real ETF market data. (2) Created a feature engineering, model training, and backtesting pipeline with AI coding agents. (3) Learned how to use AI research agents to generate, validate, and refine trading ideas. (4) Applied time-series cross-validation and leakage prevention techniques used by professional quantitative teams. (5) Evaluated model performance using metrics such as the Information Coefficient and realistic, cost-aware backtests. (6) Walked away with reusable code, notebooks, and a practical workflow you can adapt to your own trading and financial ML projects.

Why it matters

These six outcomes are the spine of the workshop. Every section below serves one of them, and the final checklist at the end tests them.

Code / prompts to copy

# The six outcomes, as a checklist.
outcomes = [
    '1. Build an end-to-end ML trading strategy on real ETF data',
    '2. Create the feature -> model -> backtest pipeline with AI coding agents',
    '3. Use AI research agents to generate, validate, and refine ideas',
    '4. Apply time-series cross-validation and leakage prevention',
    '5. Evaluate with the Information Coefficient and cost-aware backtests',
    '6. Walk away with reusable code, notebooks, and a practical workflow',
]
for o in outcomes:
    print(o)

Try it yourself

Copy the six outcomes into a notebook. Tick each one off as you finish the matching section.

Check

How many outcomes are there?

Six.

What does outcome 6 mean in plain words?

You leave with code, notebooks, and a workflow you can reuse on your own trading and financial ML projects.

Who this workshop is ideal for

What it is

This workshop is ideal for six groups of people. Data scientists and machine learning engineers interested in quantitative finance. Python developers looking to apply AI and ML to real-world trading problems. Quantitative analysts and researchers who want to modernize their workflows with AI agents. Algorithmic traders seeking a structured, reproducible ML workflow beyond rule-based strategies. Software engineers exploring AI-assisted development for financial applications. Students and professionals with intermediate Python skills who want hands-on experience building production-style ML pipelines for financial markets. You need intermediate Python — being comfortable with pandas is the main requirement — and basic ML and market terms help but are not required; this page explains each one in plain words first.

Why it matters

Knowing who a workshop is for tells you what it assumes. This one assumes you can write Python and want to apply it to trading — it does not assume you already know quantitative finance.

Code / prompts to copy

# Which group are you? Tick the ones that fit.
groups = [
    'Data scientist / ML engineer interested in quantitative finance',
    'Python developer applying AI and ML to trading',
    'Quant analyst / researcher modernizing with AI agents',
    'Algorithmic trader moving beyond rule-based strategies',
    'Software engineer exploring AI-assisted development for finance',
    'Student / professional with intermediate Python, building ML pipelines',
]
for g in groups:
    print('[ ]', g)

Try it yourself

Write down which group you belong to, and one thing you want to be able to do after this workshop.

Check

Do you need to be a professional trader to take this workshop?

No. Intermediate Python is the main requirement; market terms are explained in plain words.

What does 'quantitative finance' mean in plain words?

Using numbers, data, and models — instead of gut feeling — to make trading decisions.

Machine learning for trading, in plain words

What it is

Machine learning for trading means: instead of writing down a fixed trading rule yourself, you give a computer many examples of market data, and it learns patterns that might predict the next move. An ETF is a basket of stocks (or bonds, gold, oil) that trades like one share — for example SPY holds US large stocks, GLD holds gold. A feature is a number computed from past prices that might predict the next move, like momentum (how much the price moved recently). A model is the program that turns features into a prediction. A backtest is running the model on past data to see how it would have done — with real costs included, or it means nothing.

Why it matters

If you cannot explain a term in plain words, you cannot tell whether the model is doing something real or something silly. Plain words first, code second.

Code / prompts to copy

# The five words, in one line each.
words = {
    'ETF': 'a basket of stocks (or bonds, gold, oil) that trades like one share',
    'Feature': 'a number from past prices that might predict the next move',
    'Model': 'the program that turns features into a prediction',
    'Backtest': 'running the model on past data to see how it would have done',
    'Agent': 'an AI that does a job for you: writes code, or researches an idea',
}
for k, v in words.items():
    print(k, '-', v)

Try it yourself

Explain 'backtest' to a friend in one sentence, without using the word 'backtest'.

Check

What is an ETF in plain words?

A basket of stocks (or bonds, gold, oil) that trades like one share.

What is a feature?

A number computed from past prices that might predict the next move — for example momentum.

Rule-based strategies vs ML — what changes

What it is

A rule-based strategy is a fixed rule you write yourself: 'buy when the 10-day average crosses above the 50-day average.' It is simple, transparent, and easy to test — but it only knows what you told it. An ML strategy learns its own rules from data: you give it features (momentum, volatility, RSI, and more) and it finds which combinations predicted returns in the past. The ML version can find patterns you would never think of — but it can also find patterns that are just noise, or leakage (information from the future sneaking in). That is why the validation in this workshop is stricter than the model itself.

Why it matters

Rule-based is a good start and a good baseline: if your ML model cannot beat a simple rule, the model is not earning its keep. ML adds flexibility; it does not remove the need for honest testing.

Code / prompts to copy

# Rule-based: one fixed rule, written by you.
# ML: the computer learns the rule from data.
# Both are tested the same way: out-of-sample, with costs.
closes = [100, 101, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111]

def sma(prices, w):
    return sum(prices[-w:]) / w

print('10-day average:', round(sma(closes, 10), 2))
print('Rule-based signal: buy if the last price is above the 10-day average:',
      closes[-1] > sma(closes, 10))
print()
print('ML signal: the model weighs momentum, volatility, RSI, and more,')
print('and outputs a predicted return for each ETF. Same test, stricter rules.')

Try it yourself

Write down one rule-based strategy in one sentence. Then write down what an ML model would need to beat it.

Check

What is a rule-based strategy?

A fixed rule you write yourself, like 'buy when the 10-day average crosses above the 50-day average.'

What is the main risk of an ML strategy?

It can learn patterns that are just noise — or leakage, information from the future sneaking in.

What AI agents change — speed, critique, reproducibility

What it is

AI agents change three things about the quant workflow. Speed: a coding agent scaffolds a whole pipeline in minutes, and a research agent reads and summarizes far more than you could in a day. Critique: a research agent can be asked to argue with your result — to find leakage smells, to propose alternative features, to red-team your assumptions — so you stop fooling yourself. Reproducibility: when the agent writes the code, the tests, and the runbook from your prompts, the whole workflow is written down and can be rerun by anyone, instead of living in one person's head. Together, that is what 'modernizing a workflow with AI agents' means: faster, better challenged, and reproducible.

Why it matters

Agents do not make you smarter about markets. They make the workflow faster and more honest — if you ask them to challenge you, not just to agree with you.

Code / prompts to copy

# The three changes, as a checklist.
changes = [
    'Speed: scaffold a pipeline in minutes, read far more than you could',
    'Critique: ask the agent to argue with your result, find leakage smells',
    'Reproducibility: code, tests, and runbook written down, rerunnable by anyone',
]
for c in changes:
    print('-', c)

Try it yourself

Pick one of the three changes and write one sentence about how it would help your own work.

Check

What are the three things AI agents change?

Speed, critique, and reproducibility.

How does a research agent help you stop fooling yourself?

Ask it to argue with your result: find leakage smells, propose alternative features, red-team your assumptions.

What AI agents do not change — markets are adversarial

What it is

Agents do not change the hard facts. Markets are adversarial: other traders adapt, and a signal that works today can decay or vanish tomorrow. Markets are non-stationary: calm markets, crashes, and rate rises behave like different worlds. The signal is tiny compared with random price moves, so a model can easily learn noise. No agent can promise a profitable strategy, and no prompt can remove the need for leakage-safe validation, realistic costs, and honest metrics. If an agent tells you it found a guaranteed winner, that is the moment to be most suspicious.

Why it matters

This is the most important lesson in the workshop. Agents make the work faster — they do not make the market easier.

Code / prompts to copy

print('Agents change the workflow. They do not change the market.')

Try it yourself

Write one sentence about why a signal that worked last year might not work this year.

Check

Can an AI agent guarantee a profitable strategy?

No. Markets are adversarial and non-stationary; no legitimate workshop or agent can promise profit.

What does 'non-stationary' mean in plain words?

Markets change over time — a pattern that worked in one period may not work in another.

The end-to-end pipeline — data, features, model, backtest

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

Code / prompts to copy

# 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

What does data_pipeline.py do?

It loads the prices — real Yahoo Finance data, or the synthetic fallback — into a long-format (date, ticker) OHLCV table.

What is the shared contract between the modules?

A long-format table indexed by (date, ticker), with OHLCV columns. Every module depends on it.

Data — real ETF market data, the 10-ETF universe

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.

Code / prompts to copy

# 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

How many ETFs are in the universe, and what do they span?

Ten ETFs, spanning equities, rates, and commodities.

What happens if Yahoo Finance is not available?

The loader falls back to the bundled synthetic data, so the pipeline still runs.

Features — momentum, volatility, RSI, and more

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

Code / prompts to copy

# Momentum, volatility, and RSI in plain Python (no libraries needed).
# The 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

What is RSI in plain words?

A 0-100 score over 14 days: high means the price rose a lot recently, low means it fell a lot recently.

What is a cross-sectional rank feature?

How strong one ETF is compared with the other ETFs on the same date — its rank within that day, not across all of history.

Model and backtest — gradient boosting, then a cost-aware portfolio

What it is

Per fold, train a gradient-boosted model: LightGBM, or its sklearn equivalent HistGradientBoostingRegressor. Gradient boosting builds many small decision trees, one after another, each one fixing the mistakes of the ones before it. Then take only out-of-sample predictions — never in-sample fitted values — and 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. Dollar-neutral means 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. Add turnover accounting and a per-trade cost in basis points (1 basis point is 0.01%), and compare gross vs net equity curves.

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. Costs are not a detail — they are the difference between a strategy that works on paper and one that works in real life.

Code / prompts to copy

# 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: model = make_model()  # LightGBM if installed, else HistGradientBoostingRegressor')
print('           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

What is gradient boosting in plain words?

Many small decision trees built one after another, each fixing the mistakes of the ones before it.

What does dollar-neutral mean?

The long side and the short side hold the same amount of money, so the portfolio is not just betting the market goes up.

Scaffolding with a coding agent — the exact prompt

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 companion lab — 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.

Code / prompts to copy

# 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

What should you give the coding agent as context?

The module docstrings, and the instruction to preserve the (date, ticker) MultiIndex contract.

What do you do after the agent scaffolds the pipeline?

Compare its scaffold to the reference implementation, and discuss where it diverges and why.

Ask the agent to write tests — especially for purge and embargo

What it is

The most valuable test the coding agent can write is for the purge/embargo split logic: given a test fold, check that no training row's label window overlaps it, and that the embargo buffer is skipped. A bug here is silent — the pipeline runs, the backtest looks great, and the result is a lie. Other good agent tasks: tests that every feature uses only data available at close of day t, tests that the (date, ticker) contract holds between modules, and a test that the backtest only ever uses out-of-sample predictions.

Why it matters

Tests are where the agent earns its keep: the split logic is small, exact, and easy to get wrong — exactly the kind of thing a test catches and a human eye misses.

Code / prompts to copy

# A test the coding agent can write: does any training label window
# overlap the test fold? If yes, the split leaks.
HORIZON, EMBARGO = 5, 5

def split_is_clean(train_days, test_start, test_end):
    for d in train_days:
        label_window = (d, d + HORIZON)  # label for day d looks at days d..d+5
        if label_window[0] <= test_end and label_window[1] >= test_start:
            return False, d  # overlap: this training row leaks
    if any(test_end < d <= test_end + EMBARGO for d in train_days):
        return False, 'embargo'
    return True, None

train = [80, 85, 90, 94]   # last training day 94: label window 94..99, test starts 100 -> clean
print('Clean split?', split_is_clean(train, 100, 119))
train_bad = [80, 85, 90, 97]  # day 97: label window 97..102 overlaps test 100..119
print('Leaky split?', split_is_clean(train_bad, 100, 119))

Try it yourself

Change the test fold to days 200-219 and find the last training day that is still clean. Why that day?

Check

Why test the purge/embargo logic?

A bug there is silent: the pipeline runs, the backtest looks great, and the result is a lie.

What else should the agent test?

That every feature uses only data available at close of day t, and that the backtest only uses out-of-sample predictions.

Refactoring with the agent — add a feature without breaking the pipeline

What it is

When you add a new indicator, ask the coding agent to refactor the feature builder: add the new feature inside build_features(), keep the same (date, ticker) output shape, keep every feature leakage-safe (only data through close of day t), and update the tests. The prompt should say what the feature is, what data it may use, and what must not change. Then rerun run_workshop.py and check whether the IC improves — if it does not, the feature did not earn its place.

Why it matters

Refactoring is where agents save the most time and cause the most damage. The rule is simple: the agent may change the inside of a module, never the contract between modules.

Code / prompts to copy

# Prompt to give the coding agent when adding a feature (copy as text):
prompt = (
    'Add a 21-day momentum feature to build_features() in features.py. '
    'Use only closing prices available at close of day t. '
    'Keep the (date, ticker) MultiIndex output shape exactly the same, '
    'and update the tests. Do not change the label or the backtest.'
)
print(prompt)
print()
print('Then rerun: python run_workshop.py  # did the IC improve? If not, drop the feature.')

Try it yourself

Write a prompt for adding a 63-day volatility feature, following the same shape: what it is, what data it may use, what must not change.

Check

What may the agent change when refactoring?

The inside of a module — never the contract between modules.

How do you know if a new feature earned its place?

Rerun the pipeline and check whether the IC improves. If it does not, drop the feature.

Reviewing agent code — you are still the quant

What it is

The agent writes the code; you review it. Check four things every time: (1) the (date, ticker) contract is preserved — every module still speaks the same table shape; (2) no feature uses future data — read the shift and rolling windows, do not just trust the names; (3) the split logic purges and embargoes correctly — run the test from the previous lesson; (4) the backtest uses only out-of-sample predictions. If any check fails, send it back with the exact failure, not a vague 'fix it'.

Why it matters

Reviewing is a skill, not a formality. The agent is fast and confident; your job is to be the one who checks the things that matter.

Code / prompts to copy

# A review checklist you can run on any agent-written module.
review = [
    '(date, ticker) contract preserved?  (same index, same OHLCV columns)',
    'No feature uses future data?        (check every shift and rolling window)',
    'Purge + embargo correct?            (run the split test)',
    'Backtest uses OOS predictions only? (never in-sample fitted values)',
    'Costs included?                     (COST_BPS applied, gross vs net shown)',
]
for item in review:
    print('[ ]', item)
print()
print('If a check fails, send it back with the exact failure, not "fix it".')

Try it yourself

Review the feature code from Section 2 against the checklist above. Which check is hardest to verify by eye, and why?

Check

What are the four things to check in agent-written code?

The (date, ticker) contract, no future data in features, correct purge/embargo, OOS-only backtest — plus costs included.

How should you send a failure back to the agent?

With the exact failure — the test that failed and the numbers — not a vague 'fix it'.

Generate trading ideas with a research agent

What it is

A research agent generates ideas: give it a question — 'what features might predict 5-day ETF returns?' — and ask for ideas with a one-line economic reason each, not just a list. A good idea has a reason: momentum works because trends persist; mean-reversion works because prices overreact and bounce; volatility works because calm and jumpy markets behave differently. A list without reasons is not research, it is a brainstorm. Ask the agent to cite why a feature might carry signal, and to say what would prove it wrong.

Why it matters

Ideas are cheap; reasons are not. An idea with an economic reason can be tested. An idea without one can only be hoped for.

Code / prompts to copy

# Prompt to give the research agent (copy as text):
prompt = (
    'Propose 3 feature families that might predict 5-day ETF returns. '
    'For each one, give a one-line economic reason why it might carry signal, '
    'and say what result would prove it wrong.'
)
print(prompt)
print()
print('Good answers have reasons: "momentum: trends persist."')
print('Bad answers are just lists: "momentum, RSI, volume."')

Try it yourself

Ask a research agent for 3 feature families with reasons. Which reason is strongest, and why?

Check

What makes a trading idea testable?

A one-line economic reason why it might carry signal — and a statement of what would prove it wrong.

What is the difference between research and a brainstorm?

Research gives reasons and falsifiable claims; a brainstorm is just a list.

Validate ideas — the null hypothesis and the leakage smell

What it is

Before you build an idea, validate it. Ask the research agent: what is the null hypothesis this idea needs to beat? The null hypothesis is the boring explanation: 'the model predicts nothing; the IC is zero, and any positive number is luck.' Then ask it to look at your IC table and flag any fold whose IC looks implausibly high — real signals usually run 0.02-0.08, so a fold at 0.30 is a leakage smell, not a win. Validation is cheaper than building: a bad idea caught in five minutes saves five hours of pipeline work.

Why it matters

The null hypothesis is your sparring partner. If your idea cannot beat 'it predicts nothing', it is not an idea yet.

Code / prompts to copy

# The two validation questions (copy them as text):
print('1. What is the null hypothesis my IC needs to beat?')
print('   Answer: the model predicts nothing; IC = 0, any positive IC is luck.')
print('2. Does any fold look implausibly high? (Real signals: 0.02-0.08.)')
print('   A fold at 0.30 is a leakage smell, not a win.')

Try it yourself

Write the null hypothesis for your own idea in one sentence. Then write one reason a single high-IC fold might be luck.

Check

What is the null hypothesis?

'The model predicts nothing; the IC is zero, and any positive number is luck.'

What is a leakage smell in an IC table?

One fold with an implausibly high IC — far above 0.02-0.08 — which usually means the model saw the answer.

Refine ideas — what to change when the IC is weak

What it is

When the IC is weak, the research agent helps you refine instead of guessing. Ask it: which feature family should I try next, and why? Should I change the horizon (1 day is noisier, 20 days is smoother)? Should I change the universe, or the quantile thresholds (top 30% vs top 20%)? Each suggestion must come with a reason and a test: 'try momentum over 63 days, because trends persist longer in ETFs; test it by rerunning the pipeline and comparing the IC.' Refinement is a loop: propose, test, keep or drop — and the agent keeps the loop moving.

Why it matters

Refinement without a test is just opinion. Every suggestion needs a reason and a rerun.

Code / prompts to copy

# The refine loop, in code shape.
# Propose -> test -> keep or drop. The agent proposes; the pipeline decides.
proposals = [
    ('Try momentum over 63 days', 'trends persist longer in ETFs'),
    ('Try a 20-day horizon', 'slower, smoother, less noise'),
    ('Try top 20% / bottom 20%', 'fewer, stronger bets'),
]
for what, why in proposals:
    print('Propose:', what, '-', why)
    print('Test   : rerun run_workshop.py, compare the IC. Keep or drop.')
    print()

Try it yourself

Pick one refinement from the list above and write down the exact test you would run to check it.

Check

How do you refine an idea instead of guessing?

Ask the agent for a suggestion with a reason, then test it by rerunning the pipeline and comparing the IC.

What should you change first: the model or the horizon?

The horizon, costs, or features — the knobs change the answer more than tuning the model does.

The reusable research-agent prompt template

What it is

Use this template every time you review a result. It is the same one from the companion lab, and it works for any idea, not just this workshop. Paste your fold table, IC summary, and backtest stats into the context, then ask the three questions. The first line matters most: 'You are reviewing a quant research result, not producing investment advice.' That keeps the agent in the reviewer role — critical, precise, and honest — instead of cheerleading your idea.

Why it matters

A template beats a fresh prompt every time: the same three questions, asked the same way, make results comparable across ideas.

Code / prompts to copy

# The reusable research-agent prompt template (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 into your notes. Fill in the context with the honest results from Section 6 and run it with a research agent.

Check

What is the first line of the template, and why does it matter?

'You are reviewing a quant research result, not producing investment advice.' It keeps the agent in the reviewer role instead of cheerleading.

What are the three questions?

1. Leakage artifact? 2. Two alternative feature families with reasons. 3. Strongest argument the result does not generalize.

Why k-fold cross-validation is wrong for time series

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 professional quant teams use 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.

Code / prompts to copy

# 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

What does k-fold CV do that breaks time series?

It shuffles the data, so training rows can come from after the test rows — the model trains on the future.

What is walk-forward CV in plain words?

Train on the past, test on the next slice of time, then step forward and repeat.

Purged + embargoed walk-forward CV (Lopez de Prado)

What it is

Purged and embargoed walk-forward CV is the fix, from Marcos Lopez de Prado, and it is the technique professional quantitative teams use. 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 companion lab 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.

Code / prompts to copy

# 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

What does 'purge' mean?

Delete training rows whose label window overlaps the test window.

What does 'embargo' mean?

After each test fold, skip a buffer of days before training resumes, because information leaks across the boundary.

Leakage checkpoint — the label must be shifted, ranks within each date

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.

Code / prompts to copy

# 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

Why must the forward-return label be shifted?

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.

Why must ranks be computed within each date?

Ranking across all dates mixes the future into the past. Rank the ETFs against each other on the same day only.

Ask the agents to hunt for leakage — before you trust a result

What it is

Before you trust any result, ask both agents to hunt for leakage. Ask the research agent the template questions from Section 4. Ask the coding agent to write a test that checks: no feature uses data after close of day t, no training label window overlaps a test fold, and the embargo buffer is respected. Then run the tests. A result that survives both agents' hunting is worth more than a result that was never challenged — and a leak found now costs nothing, while a leak found with real money costs everything.

Why it matters

Leakage hunting is a habit, not a one-off check. Make it the last step before every backtest, and the first step after every 'amazing' result.

Code / prompts to copy

# The leakage hunt, as a checklist for both agents.
hunt = [
    'Research agent: does anything look like a leakage artifact? Why?',
    'Coding agent: test that no feature uses data after close of day t',
    'Coding agent: test that no training label window overlaps a test fold',
    'Coding agent: test that the embargo buffer is respected',
    'You: if the IC is far above 0.02-0.08, assume leakage until proven otherwise',
]
for h in hunt:
    print('[ ]', h)

Try it yourself

Run the hunt checklist on the worked example from the previous lesson. Which item would catch a forgotten label shift?

Check

What should you do after an 'amazing' result?

Hunt for leakage first: run the agent checks and the split tests before believing it.

What IC range should make you suspicious?

Far above 0.02-0.08 on real data — assume leakage until proven otherwise.

The Information Coefficient (IC) — did the model rank winners above losers?

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.

Code / prompts to copy

# 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

What is the Information Coefficient in plain words?

For each date, the rank correlation between predicted and realized forward returns, averaged across dates. It measures whether the model ranks winners above losers.

What IC range is normal for real signals?

Typically 0.02-0.08. Anything far outside that on real data is a leakage red flag, not a win.

Sharpe, max drawdown, hit rate — how the backtest really did

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. Hit rate: the share of rebalances that made money — 50% is a coin flip. Cost drag: how much return costs ate each year. Return alone lies; return plus volatility, drawdown, hit rate, and costs tells the truth.

Why it matters

These four numbers together are honest. A strategy with a great return and a terrible drawdown is a strategy that will scare you out of it at the worst moment.

Code / prompts to copy

# 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('Companion lab, 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

What is the Sharpe ratio in plain words?

Return divided by volatility — how much return you got per unit of bumpiness. Negative means you lost money for the bumps.

What is max drawdown?

The biggest fall from a peak to a trough.

Turnover and costs — where great models turn mediocre

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 companion lab's 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.

Code / prompts to copy

# 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('Companion lab: 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

What is a basis point?

0.01%. So 10 basis points is 0.10% per trade.

What was the cost drag in the companion lab's run?

1.76% per year — the difference between the gross return (-0.71%) and the net return (-2.44%).

The honest results — a weak signal gets eaten by costs

What it is

Here are the companion lab's real numbers, reported honestly. Model: 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 — far below the 0.02-0.08 range of real signals. Backtest, net of costs: annualized return -2.44%, volatility 5.79%, Sharpe -0.43, max drawdown -88.94%, hit rate 48.62%, average turnover 69.79%, cost drag 1.76%. Gross (before costs): return -0.71%, Sharpe -0.12, max drawdown -76.49%, hit rate 50.05%. These numbers are from synthetic data unless yfinance and internet were available when the run happened. A small, negative Sharpe here is a normal, useful 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.

Why it matters

This is the most honest page in the workshop. A workshop that only ever 'wins' is hiding something. The lesson is not 'this signal failed' — it is 'this is how you find out, cheaply, before real money is involved.'

Code / prompts to copy

# The honest results, as numbers you can check.
results = {
    'Mean out-of-sample IC': 0.0027,
    'Net return (annualized)': '-2.44%',
    'Gross return (annualized)': '-0.71%',
    'Net Sharpe': -0.43,
    'Gross Sharpe': -0.12,
    'Net max drawdown': '-88.94%',
    'Net hit rate': '48.62%',
    'Avg turnover / rebalance': '69.79%',
    'Cost drag (annualized)': '1.76%',
}
for k, v in results.items():
    print(k, ':', v)
print()
print('Lesson: a weak signal gets eaten by turnover and costs.')

Try it yourself

Write one sentence about what these results teach you. Then ask the research agent the template questions about them.

Check

What was the mean out-of-sample IC?

0.0027 — far below the 0.02-0.08 range of real signals.

Why is a losing run a useful workshop outcome?

It shows how much a weak signal gets eaten by turnover and costs — exactly what cost-aware backtesting and purged CV exist to reveal.

A structured, reproducible workflow — the same steps, every time

What it is

A reproducible workflow means: the same inputs, the same code, and the same steps always produce the same result — and anyone can rerun it. The structure is: (1) a written spec for the idea (what it is, why it might work, what would prove it wrong); (2) the four-module pipeline (data, features, model, backtest) with the (date, ticker) contract; (3) versioned code and notebooks, so you can go back to any earlier version; (4) tests for the split logic and the leakage rules; (5) a runbook — the exact commands to rerun everything (pip install -r requirements.txt, python run_workshop.py); (6) the results file, results_summary.md, written by the pipeline itself, not by hand. The agents help with every step: the coding agent writes the code and tests, the research agent writes the spec critique — but the structure is yours.

Why it matters

Reproducibility is what turns a one-off experiment into a workflow. Without it, you cannot tell whether a better result came from a better idea or from a different run.

Code / prompts to copy

# The workflow, as a checklist the pipeline itself can print.
workflow = [
    '1. Spec: what is the idea, why might it work, what would prove it wrong?',
    '2. Pipeline: data -> features -> model -> backtest, (date, ticker) contract',
    '3. Versioning: code and notebooks versioned, so any earlier version can be rerun',
    '4. Tests: purge/embargo split logic, leakage rules, OOS-only backtest',
    '5. Runbook: pip install -r requirements.txt, then python run_workshop.py',
    '6. Results: results_summary.md written by the pipeline, not by hand',
]
for w in workflow:
    print(w)

Try it yourself

Write a one-page runbook for your own idea: the six steps above, filled in with your idea's details.

Check

What does 'reproducible' mean in plain words?

The same inputs, code, and steps always produce the same result — and anyone can rerun it.

What is a runbook?

The exact commands to rerun everything, written down so anyone can follow them.

Notebooks and versioning — your lab book

What it is

A notebook is your lab book: the idea, the code, the charts, and the verdict, in one place, in order. Keep one notebook per idea, with the date, the spec, the IC table, the backtest numbers, and the verdict (keep, refine, or drop). Version your code with git: commit after each working step, with a message that says what changed and why. When a later idea beats an earlier one, you can go back and see exactly what the earlier one did — instead of guessing. The companion lab's repo shape is the template: six files, each with one job, plus the results file the pipeline writes.

Why it matters

A lab book is how science works, and quant research is science. Without it, you repeat mistakes and forget wins.

Code / prompts to copy

# A notebook template, as headings.
headings = ['Date', 'Idea + economic reason', 'Null hypothesis',
            'Features tried', 'IC table (per fold)', 'Backtest: gross vs net',
            'Verdict: keep / refine / drop', 'Next step']
for i, h in enumerate(headings, 1):
    print(str(i) + '.', h)

Try it yourself

Start a notebook for one idea using the headings above. Fill in the first three headings today.

Check

What goes in a notebook for one idea?

Date, spec, null hypothesis, features tried, IC table, backtest numbers, verdict, and next step.

Why version your code with git?

So you can go back to any earlier version and see exactly what it did, instead of guessing.

Modernizing a rule-based workflow — the checklist

What it is

If you already have a rule-based strategy, modernizing it means: (1) write the rule down as a spec, with its reason and its null hypothesis; (2) turn the rule's inputs into features (the rule's signal becomes one feature among many); (3) run the rule and the ML model side by side on the same walk-forward folds, with the same costs; (4) compare IC and net Sharpe — if the model cannot beat the rule, keep the rule; (5) let the research agent critique both; (6) keep the winner in the versioned pipeline, with tests and a runbook. Modernizing is not throwing the rule away — it is testing it properly, and letting the model earn its place.

Why it matters

The rule is your baseline, not your enemy. A model that cannot beat a simple rule has not earned its keep.

Code / prompts to copy

# Modernize a rule-based strategy, step by step.
steps = [
    '1. Write the rule down as a spec: reason + null hypothesis',
    '2. Turn the rule inputs into features (the rule becomes one feature)',
    '3. Run rule and ML side by side, same folds, same costs',
    '4. Compare IC and net Sharpe - if the model cannot beat the rule, keep the rule',
    '5. Let the research agent critique both',
    '6. Keep the winner in the versioned pipeline, with tests and a runbook',
]
for s in steps:
    print(s)

Try it yourself

Take a rule-based idea you know (for example, 'buy when the 10-day average crosses above the 50-day average') and write its spec: reason and null hypothesis.

Check

What is the first step in modernizing a rule-based strategy?

Write the rule down as a spec, with its reason and its null hypothesis.

When should you keep the rule instead of the model?

When the model cannot beat the rule on IC and net Sharpe, on the same folds with the same costs.

Adapting it — change the universe, horizon, costs, sizing, features

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. Ask the research agent to propose the change and the coding agent to implement it — but you decide, from the IC and the net Sharpe, whether to keep it.

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.

Code / prompts to copy

# 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

Where do you change the prediction horizon?

HORIZON in features.py — currently 5 trading days.

Where do you change the cost assumption?

COST_BPS in backtest.py.

Where this pipeline stops and production begins

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.

Code / prompts to copy

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

What is slippage in plain words?

Your trade moves the price against you, so you get a worse price than the one on screen — bigger when your position is bigger.

What is point-in-time data hygiene?

Making sure the data you used was actually available at the time you pretend to trade on it — no future data sneaking in.

Reusable artifacts — what you leave with

What it is

You leave with reusable code, notebooks, and a practical workflow. The code is 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. The full working code lives in the companion Hands-On ML Trading Strategy workshop in this same Workshop folder — run that lab, then bring its pipeline back here and adapt it with the agent workflow from this page.

Why it matters

Six small files, each with one job, is a pipeline you can actually reuse. That is the deliverable — plus the notebook habit and the agent prompts that go with it.

Code / prompts to copy

# 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)
print()
print('Full code: ML_Trading_Strategy_End_to_End/')

Try it yourself

List the six artifacts from memory, then check yourself against the list above.

Check

Which file produces the charts and results_summary.md?

run_workshop.py — it orchestrates all four modules.

Where is the full working code?

In the companion Hands-On ML Trading Strategy workshop in this same Workshop folder.

Final checklist — reusable code, notebooks, and a practical workflow

What it is

Before you call this workshop done, check every item: (1) You can explain ETF, feature, model, backtest, leakage, IC, Sharpe, and drawdown in plain words. (2) You can run the four-module pipeline end to end. (3) You have a coding-agent prompt that scaffolds the pipeline and preserves the (date, ticker) contract. (4) You have the research-agent template saved, and you have used it on a real result. (5) You can explain why k-fold is wrong and what purged + embargoed walk-forward does. (6) You can read an IC table and spot a leakage smell. (7) You can explain gross vs net, turnover, and cost drag. (8) You have one notebook started, with a spec, a null hypothesis, and a verdict. (9) You know where the pipeline stops and production begins. (10) You can state the disclaimer in your own words: this is learning material, not investment advice, and no profit is promised.

Why it matters

A checklist is how you know you actually learned it, not just read it. If an item is not ticked, go back to its section — that is what the tick boxes are for.

Code / prompts to copy

# The final checklist.
items = [
    'Explain ETF, feature, model, backtest, leakage, IC, Sharpe, drawdown in plain words',
    'Run the four-module pipeline end to end',
    'Coding-agent prompt saved (scaffold + preserve the contract)',
    'Research-agent template saved and used on a real result',
    'Explain why k-fold is wrong; what purged + embargoed does',
    'Read an IC table and spot a leakage smell',
    'Explain gross vs net, turnover, and cost drag',
    'One notebook started: spec, null hypothesis, verdict',
    'Know where the pipeline stops and production begins',
    'State the disclaimer in your own words',
]
for i, item in enumerate(items, 1):
    print(str(i) + '. [ ]', item)

Try it yourself

Go through the checklist honestly. For every unticked item, write down which section to revisit.

Check

How many items are on the final checklist?

Ten.

What should you do with an unticked item?

Go back to its section — that is what the tick boxes are for.

What to do next

What it is

Next, run the companion lab: ML Trading Strategy, End to End, in the Workshop folder next to this page — it has the full pipeline code, the 5 blocks, and the honest results. Build the pipeline there, then bring it back here and adapt it with the agent workflow from this page. After that, try the Financial agent workshop in the same folder: it builds a full financial agent system (Modules 0-9, Labs 1-7, capstone, production on bare Debian) and shows how agents, costs, and governance fit together in a real service. Keep the notebook habit: one idea, one notebook, one verdict — keep, refine, or drop.

Why it matters

One workshop teaches the pipeline. The next teaches the system around it. Do them in that order.

Code / prompts to copy

# Your next steps, in order.
print('1. Companion lab: Hands-On ML Trading Strategy (full pipeline code)')
print('2. Adapt it with the agent workflow from this page')
print('3. Financial agent workshop: agents, costs, governance in a real service')

Try it yourself

Open the companion lab page and tick its first lesson. That is your next step.

Check

What is the companion lab?

ML Trading Strategy, End to End — the full pipeline code, in the Workshop folder next to this page.

What comes after the companion lab?

The Financial agent workshop: a full financial agent system, Modules 0-9, Labs 1-7, capstone, and production.

Try the agent workflow here

Type a trading idea, then press the button. A simulated research agent will generate it in testable words, validate it, check for leakage, preview the IC, run a cost-aware backtest, and give a verdict: keep, refine, or drop.


Press the button to run the agent workflow on your idea.