This is general information, not financial advice.
This is the loop I’d build to test a trading idea before trusting it with a cent. You describe the idea in plain English. Claude turns it into code and tests it against 5 years of real price history. When it loses, a second agent goes through the exact trades that lost money, rewrites the entry and the exit, and runs it again. Every failed version gets saved so the next one doesn’t repeat it.
The part the AI never touches is risk. Your stop loss and your max drawdown live in a file Claude is blocked from editing, and they get forced on top of every test. After 8 years of trading, that’s the bit I care about most.
About 45 minutes the first time. You won’t write any code, but you will paste things into a terminal.
Before you start
You need Claude Code on a paid plan. Pro, Max, Team or Enterprise. If you haven’t installed it, the first section of the grunt work setup has the one-line install. The Claude desktop app runs Claude Code too, if the terminal isn’t your thing.
You need Python 3. Open your terminal and type python3 --version. If you get a version number, you’re set. If not, install it from python.org.
What it tests on. Daily prices from Yahoo Finance through yfinance, a free, unofficial library. It’s not affiliated with Yahoo and it’s meant for personal research, which is exactly what this is. The backtesting itself runs on backtesting.py, a free open source library.
A backtest is not a forecast. Passing this loop means the idea survived the past, under the costs and rules you set. That’s the minimum bar, not a green light.
Step 1: Make a folder and open Claude Code in it
Make an empty folder called quant-loop anywhere you like. In your terminal, type cd and a space, drag the folder onto the terminal window, press enter, then type claude.
cd /Users/you/Documents/quant-loop
claude
Everything from here gets pasted into that Claude Code session.
Step 2: Lock the risk rules
This one prompt installs the two libraries, creates the 2 files the AI is never allowed to change, and blocks Claude from editing them. Open risk.py in the block below first and change the numbers to yours: the ticker (ASX tickers end in .AX, so CBA.AX, BHP.AX), your stop loss, your max drawdown and your broker’s commission.
What the 2 files do:
- risk.py holds your rules. Every trade gets a stop loss at your percentage from entry, no matter what the strategy says. If the account ever falls past your max drawdown from its peak, everything closes and the strategy stops trading for the rest of the test.
- backtest.py downloads the price history, runs the strategy with those rules forced on top, and prints PASS or FAIL. It keeps the last 12 months back for a final test the loop never sees (step 6). It passes only if the strategy made money, beat simply buying and holding, made at least 10 trades and never hit the drawdown limit.
Set up this folder for a trading backtest. Do exactly these steps and nothing else.
1. Install the Python packages backtesting and yfinance. If pip refuses because the system Python is managed, create a virtual environment called .venv in this folder, install them there, and use that environment's python for every python command from now on. Tell me which python you used.
2. Create risk.py with exactly the text between RISK START and RISK END. Don't change anything.
3. Create backtest.py with exactly the text between BACKTEST START and BACKTEST END. Don't change anything.
4. Create graveyard.md containing the single line: # Graveyard
5. Create .claude/settings.json containing exactly the text between SETTINGS START and SETTINGS END.
6. Show me the contents of risk.py so I can check it.
RISK START
# LOCKED. Claude is blocked from editing this file. Only you change these numbers.
TICKER = "BHP.AX" # the market to test on. ASX tickers end in .AX
YEARS = 5 # years of daily price history
HOLDOUT_MONTHS = 12 # the last 12 months are kept back for your final test
CASH = 10_000 # starting balance for the test
COMMISSION = 0.002 # 0.2% per trade, change it to match your broker
STOP_LOSS_PCT = 0.05 # every trade gets a stop 5% from entry, no exceptions
MAX_DRAWDOWN_PCT = 0.20 # if the account falls 20% from its peak, everything closes and trading stops
MIN_TRADES = 10 # fewer trades than this is luck, not a strategy
RISK END
BACKTEST START
# LOCKED. Claude is blocked from editing this file.
# Runs strategy.py against real price history with the rules in risk.py forced on top.
import sys, os, datetime
import pandas as pd
import yfinance as yf
from backtesting import Backtest
import risk
from strategy import TradingStrategy
def with_risk(Base):
class Guarded(Base):
def init(self):
super().init()
self._peak = 0
self._halted = False
def next(self):
self._peak = max(self._peak, self.equity)
if self._halted or self.equity < self._peak * (1 - risk.MAX_DRAWDOWN_PCT):
self._halted = True
if self.position:
self.position.close()
return
super().next()
for t in self.trades:
if t.is_long:
limit = t.entry_price * (1 - risk.STOP_LOSS_PCT)
if t.sl is None or t.sl < limit:
t.sl = limit
else:
limit = t.entry_price * (1 + risk.STOP_LOSS_PCT)
if t.sl is None or t.sl > limit:
t.sl = limit
Guarded.__name__ = Base.__name__
return Guarded
final = "--final" in sys.argv
data = yf.Ticker(risk.TICKER).history(period=f"{risk.YEARS}y", auto_adjust=True)
if data.empty:
sys.exit(f"No price data came back for {risk.TICKER}. Check the ticker in risk.py.")
data = data[["Open", "High", "Low", "Close", "Volume"]]
data.index = data.index.tz_localize(None)
cutoff = data.index[-1] - pd.DateOffset(months=risk.HOLDOUT_MONTHS)
data = data[data.index > cutoff] if final else data[data.index <= cutoff]
bt = Backtest(data, with_risk(TradingStrategy), cash=risk.CASH, commission=risk.COMMISSION, finalize_trades=True)
s = bt.run()
trades = s["_trades"]
problems = []
if s["# Trades"] < risk.MIN_TRADES:
problems.append(f"only {s['# Trades']} trades, need {risk.MIN_TRADES}")
if s["Return [%]"] <= 0:
problems.append("lost money")
if s["Return [%]"] <= s["Buy & Hold Return [%]"]:
problems.append("did worse than just buying and holding")
if s["_strategy"]._halted:
problems.append("hit the max drawdown limit, so trading was stopped")
result = "PASS" if not problems else "FAIL (" + "; ".join(problems) + ")"
os.makedirs("runs", exist_ok=True)
losers = trades[trades["ReturnPct"] < 0][["EntryTime", "ExitTime", "EntryPrice", "ExitPrice", "SL", "ReturnPct", "Duration"]]
losers.to_csv("runs/losing_trades.csv", index=False)
row = pd.DataFrame([{
"time": datetime.datetime.now().isoformat(timespec="seconds"),
"test": "final" if final else "main",
"return_pct": round(s["Return [%]"], 2),
"buy_hold_pct": round(s["Buy & Hold Return [%]"], 2),
"max_drawdown_pct": round(s["Max. Drawdown [%]"], 2),
"trades": s["# Trades"],
"win_rate_pct": round(s["Win Rate [%]"], 2) if s["# Trades"] else 0,
"result": result,
}])
row.to_csv("runs/history.csv", mode="a", header=not os.path.exists("runs/history.csv"), index=False)
print(f"Test: {'FINAL (held-back months)' if final else 'MAIN'} {data.index[0].date()} to {data.index[-1].date()} {risk.TICKER}")
print(f"Locked rules: stop loss {risk.STOP_LOSS_PCT:.0%}, max drawdown {risk.MAX_DRAWDOWN_PCT:.0%}")
print(f"Return {s['Return [%]']:.1f}% | Buy and hold {s['Buy & Hold Return [%]']:.1f}% | Max drawdown {s['Max. Drawdown [%]']:.1f}% | Trades {s['# Trades']} | Losing trades {len(losers)}")
print(f"RESULT: {result}")
BACKTEST END
SETTINGS START
{
"permissions": {
"deny": ["Edit(/risk.py)", "Edit(/backtest.py)", "Edit(/runs/**)"]
}
}
SETTINGS END
The deny rules in that settings file stop Claude’s file tools from editing risk.py, backtest.py or the results folder. They apply to the agent in step 3 as well.
You’ll know it worked when Claude shows you
risk.pywith your numbers in it, and the folder hasrisk.py,backtest.py,graveyard.mdand a.claudefolder.
Changing a number later? Open risk.py yourself in any text editor, change it and save. Claude can’t do it for you, which is the point.
Step 3: Create the second agent
This is the agent that goes through the losing trades and rewrites the strategy. Paste this in:
Create a subagent file at .claude/agents/trade-doctor.md with exactly the text between AGENT START and AGENT END. Don't change anything.
AGENT START
---
name: trade-doctor
description: Use after a backtest FAILS. Reads the losing trades and the graveyard, saves the failed version, then rewrites only the entry and exit rules in strategy.py.
tools: Read, Write, Edit, Bash, Grep, Glob
---
You fix trading strategies that failed a backtest. You change entries and exits only. You never touch risk.
Every time you run:
1. Read runs/losing_trades.csv, the last 5 lines of runs/history.csv, graveyard.md and strategy.py.
2. Find the pattern in the losing trades. For example: entries that get stopped out within a few days, entries straight after a big move, exits that give back most of a gain, losses bunched in one market phase. Describe it in 2 sentences using numbers from the CSV.
3. Save the failed version. Copy strategy.py to graveyard/vN_strategy.py, where N is the next number, and add an entry to graveyard.md with: the version number, the idea in one line, the RESULT line from history.csv, the pattern you found, and the change you are about to make.
4. Read every earlier entry in graveyard.md. Never make a change that has already been tried and failed.
5. Edit strategy.py. Change only the entry and exit logic, aimed at that pattern. Keep the class name TradingStrategy. Use only data available on that day, never future prices. Do not add stop losses, position sizing or drawdown logic, those are forced on top by backtest.py. Prefer one simple rule that makes sense over fine-tuning numbers to fit a handful of trades.
6. Never edit, overwrite, move or delete risk.py, backtest.py, anything in runs/ or anything in .claude/, with any tool, including shell commands. Never run backtest.py with --final.
7. Report back in 3 lines: the pattern, the change, the graveyard version number.
AGENT END
Then quit Claude Code (type /exit) and start it again with claude. A new agent and new settings only load when a session starts.
You’ll know it worked when you type
/agentsandtrade-doctoris in the list.
Step 4: Describe your idea in plain English
Swap the idea in the brackets for yours. Keep it to something you could explain to a mate in a sentence or two.
Turn my trading idea into strategy.py using the backtesting.py library. The class must be called TradingStrategy. Long only unless my idea says otherwise. Use only price and volume data available on that day, never future prices. Do not add stop losses or position sizing, backtest.py forces those from risk.py. My idea: [for example, buy when the price closes above its 50 day average and the 50 day average is above the 200 day average, sell when it closes back below the 50 day average]. Then run backtest.py and show me the full output.
You’ll know it worked when you see a block ending in
RESULT: PASSorRESULT: FAILwith the reasons. A FAIL here is normal. That’s what the loop is for.
Step 5: Start the loop
First paste the rules for the loop:
You're now running a backtest loop. Each round: 1. Run backtest.py and print the full output. 2. If it says RESULT: PASS, stop and tell me. 3. If it says FAIL, use the trade-doctor subagent to save this version and rewrite the entry and exit, then start the next round. Rules for you too: never edit, overwrite, move or delete risk.py, backtest.py, anything in runs/ or anything in .claude/, with any tool, including shell commands, and never run backtest.py with --final. If 3 rounds in a row get worse, stop and tell me the idea might be the problem, not the rules.
Then give it the finish line:
/goal The most recent backtest output printed in this conversation ends with "RESULT: PASS", or stop after 15 turns.
/goal keeps Claude starting new rounds on its own until the condition is true, instead of stopping to ask you. A small model checks the condition after each turn by reading the conversation, which is why the loop prints the full output every round. Type /goal clear to stop it early.
You’ll know it worked when you see
trade-doctorrunning between backtests, new entries piling up ingraveyard.md, and every round printing the lineLocked rules: stop loss 5%, max drawdown 20%with your numbers.
That printed line is your tamper check. The deny rules block Claude’s file tools, but a shell command could still write to a file. If those numbers ever change from what you set, stop the loop.
Step 6: The final test, which you run yourself
A loop that keeps rewriting a strategy against the same 4 years will eventually find something that fits those 4 years. That doesn’t mean it works. So backtest.py holds the last 12 months back, and only you run the test on them.
When the loop passes, open a second terminal window in the same folder and run:
python3 backtest.py --final
If Claude made a .venv in step 2, run .venv/bin/python backtest.py --final instead (on Windows, .venv\Scripts\python backtest.py --final).
You’ll know it worked when it prints
Test: FINALwith dates covering the last 12 months. If it passes on months the loop never saw, the idea has earned a closer look. If it fails, it was fitted to the past. Write that in the graveyard and go again with a new idea, not a tweak.
Don’t paste the final result back into the loop. The moment the agent starts fixing the held-back months, they stop being a fair test.
Before any real money
Paper trade it first, for longer than feels necessary. And when you do go live, set the same stop loss and maximum loss in your broker yourself, so the rules from risk.py exist in the real account too, not just in the test.
When it goes wrong
“No price data came back”. The ticker in risk.py is wrong. ASX tickers need .AX on the end. Look the ticker up on Yahoo Finance and copy it exactly.
It never passes. Some ideas just don’t work, and finding that out for free is the win. Check graveyard.md for what’s been tried, then start a new idea. Read runs/history.csv to see every round side by side.
Only a handful of trades. The idea is too picky for daily data on one stock. Loosen the idea, or test a more active market. Don’t lower MIN_TRADES to sneak a pass through.
trade-doctor never runs. Restart Claude Code, then check /agents. If it still isn’t there, ask Claude to show you .claude/agents/trade-doctor.md.
pip errors in step 2. Let Claude make the .venv like the prompt says. Every python command after that has to use it.
The loop stops after one round. Check /goal on its own shows the goal as active. Your Claude Code version needs to be recent enough to have it, so run claude update.
The checklist
-
risk.pyhas your ticker, stop loss, drawdown and commission -
.claude/settings.jsonhas the 3 deny rules -
/agentsshowstrade-doctor - Every round prints your locked rules, unchanged
-
graveyard.mdgrows every time a version fails - You ran
--finalyourself, and kept the result out of the loop - Paper traded before real money, with the same rules set in your broker
