Building an LLM-Assisted Backtesting System for Securities Trading: A Practical Guide
This article walks through building a reproducible securities trading backtesting system with LLM-assisted development. It covers normalizing broker-exported trade records into structured text, batch-fetching daily and intraday quotes with retry, rate limiting and idempotent writes, a minimal backtesting engine that advances time and capital, and objective performance metrics such as drawdown and Sharpe ratio. It also documents common failure modes of LLM coding workflows and practical countermeasures.
1. Background and Problem Definition: Why Individual Investors Need a Backtesting System
Most individual investors make trading decisions based on intuition and fragmented news, with no quantitative review of their own historical behavior. A typical pain point: the account swings up and down over the long run, losses outnumber gains, and yet the investor cannot say whether the losses came from stock selection, market timing, or position sizing. The only reliable way to answer that question is to reconstruct historical fills into a computable dataset and replay them under a consistent set of rules.
The system built here has four layers:
- Data layer: convert the trade details exported from brokerage software into structured data a machine can parse;
- Data acquisition layer: take a list of symbols as input, batch-fetch daily and intraday quotes, and persist them to storage;
- Computation layer: implement buy/sell signal evaluation and the projection of positions and the equity curve;
- Reporting layer: output objective performance metrics rather than subjective impressions.
It is worth stressing that the value of backtesting is not “proving a strategy makes money” but exposing behavioral bias. The first design principle is therefore reproducibility: the same input must produce the same output, and any randomness must be fixed or recorded.
2. Data Preparation: From Spreadsheet Files to Structured Text
The settlement statements exported from a brokerage client are usually spreadsheet files with fields such as trade date, security code, side, quantity, price, commission, and stamp duty. Feeding a binary spreadsheet straight to a model often leads to problems like “only the first few dozen rows were read,” “numeric precision lost,” and “merged cells misparsed.”
The more robust engineering approach is to run a format normalization step first: use a document conversion tool to turn the spreadsheet into structured text markup, then hand it to the model. After conversion, check three things:
- whether the row count matches the original file (guards against truncation);
- whether amount and quantity fields are still numeric rather than strings with thousands separators;
- whether dates are normalized to
YYYY-MM-DD, avoiding a mix of2024/1/5and20240105.
A sample directory layout:
backtest/├── data/│ ├── trades.md # normalized settlement statement│ └── quotes/ # quote storage directory├── db/│ └── market.db├── src/│ ├── fetch_quotes.py # quote fetching│ ├── schema.sql # table definitions│ └── engine.py # backtesting engine└── reports/
3. Requirement Breakdown: Turning a One-Line Request into Verifiable Steps
A common mistake is handing the complete requirement to the model in one shot and expecting it to carry out the whole pipeline autonomously. Personalized tasks that involve the local environment and private credentials are especially prone to going off the rails: the model may invent fields, skip validation, or write paths that cannot run.
A more reliable pattern is humans define the process, the model does the execution, with a clear acceptance artifact for each step:
- Step 1: extract a deduplicated list of security codes and names from the settlement statement, confirmed manually;
- Step 2: design the database schema, reviewing fields and indexes;
- Step 3: implement the quote-fetching script, requiring live progress output;
- Step 4: implement the backtesting engine, getting a single symbol working first;
- Step 5: run in batch and generate reports.
This “small steps, fast iterations” approach cuts an uncontrollable long chain into several short, rollback-able ones, so a failure means redoing only one step.
4. Market Data Ingestion: Engineering Conventions for API Calls
Quote data usually comes from two kinds of sources: an open-source data interface library maintained by a community, or an interface provided by a data vendor (the latter often requires credits or a permission tier). Either way, integration should follow a consistent convention:
# Pseudocode: fetch skeleton with retry and rate limitingdef fetch_daily(code, start, end, client, max_retry=3):for i in range(max_retry):try:df = client.daily(code=code, start=start, end=end)if df is None or df.empty:time.sleep(1) # back off on empty resultcontinuereturn dfexcept RateLimitError:time.sleep(2 ** i) # exponential backoff to avoid throttlingraise RuntimeError(f"fetch failed: {code}")
Four constraints matter:
- Credential isolation: tokens and other sensitive values go into a local config file or environment variables, never into prompts or source code;
- Rate limiting and backoff: batch fetching must control frequency and use exponential backoff when throttled;
- Idempotent writes: upsert keyed on (symbol, date) so repeated runs produce no dirty data;
- Observable progress: print
[i/N] code done, elapsed x safter each symbol, making it easy to tell whether the job is stuck or still running.
For the database, keep “quotes” and “trades” in separate table groups, split quotes into daily and intraday tables, and add a unique index on (code, trade date); the trade table should retain the original fields plus an import batch identifier for traceability.
CREATE TABLE daily_quote (code TEXT NOT NULL,trade_date TEXT NOT NULL,open REAL, high REAL, low REAL, close REAL,volume REAL, amount REAL,PRIMARY KEY (code, trade_date));
5. A Minimal Viable Backtesting Engine
The core of the engine is advancing time and capital together. At the daily level, the loop skeleton looks like this:
for date in trading_days:for sig in strategy.on_bar(date): # produce target positionsbroker.rebalance(sig, price=close[date])equity.append(broker.total_value(close[date]))
Real-world details that must be handled include: price limits that prevent a fill, valuation of positions on suspension days, minimum trading units for each side, two-sided costs (commission, transfer fee, stamp duty on sells), and scaling down target positions when cash is insufficient. Backtests that ignore these constraints tend to be overly optimistic.
Performance evaluation should cover at least: cumulative return, annualized volatility, maximum drawdown, Sharpe ratio, number of trades and win rate, and profit/loss ratio. Looking at total return alone is the most common form of self-deception.
6. Real-World Problems with LLM-Assisted Development and Countermeasures
A few typical problems show up in practice:
- Unresponsive stalls: no output for a long time. Countermeasure: shorten the granularity of each step, and manually interrupt on timeout and rerun, which usually recovers on the first attempt;
- Field hallucination: inventing nonexistent API parameters. Countermeasure: provide local API documentation as the single source of truth and require the model to list the parameter table before calling;
- Environment drift: inconsistent paths and dependency versions. Countermeasure: pin the virtual environment and emit a dependency list;
- Silent errors: the script “succeeds” but the data is empty. Countermeasure: enforce assertions on row counts and numeric ranges.
7. Conclusion and Extensions
The real payoff of using an LLM to build a backtesting system is not the time saved typing code, but turning a vague review of past trades into a verifiable process. Stay neutral on tooling: a general-purpose interface library or a data service for acquisition, a document normalization tool for conversion, a local relational database for storage, and an AI coding assistant for orchestration. If more compute and concurrency are needed later, data and tasks can move to cloud object storage, container platforms, and job scheduling services to enable parallel backtests across many symbols with archived results. In the end, the conclusion this system produces may not be pleasant to hear—it may determine that your trading pattern is heading toward losses, but that is exactly the point of quantitative review: only by admitting the problem is there any chance of correcting it.
