Building an LLM-Driven Backtesting System for Securities Trading
This article presents a practical engineering approach to turning personal trading records into reproducible securities backtesting and attribution analysis with the help of large language models. It explains why raw exported statements are hard to analyze, proposes a five-layer architecture with verifiable steps, defines a minimal normalized schema with uniqueness and conservation checks, and describes resumable, rate-limited market data ingestion. It also covers how to involve an LLM in development, common backtesting statistical pitfalls, handling stalled tool chains, and a suggested rollout order.
1. Background: Why Personal Trading Records Are Hard to Analyze Directly
Most individual investors export their trade statements from trading software as spreadsheet files. The fields are complete, but the data is full of problems that are “human-friendly but machine-unfriendly”: the trade date and time are split across multiple columns, buy/sell direction is written in Chinese text, fees are scattered across columns, field names contain spaces and units, and blank rows and subtotal rows are mixed in.
If you hand this content directly to a large language model for analysis, common outcomes are that the model reads only part of the rows, treats a total row as a single trade, or drifts during field mapping. The final conclusions then cannot be reproduced.
So the first engineering principle is not “make the model smarter” but “turn the data into a deterministic structure first.” A workable pipeline is: spreadsheet export → generic format conversion (convert to lightweight markup text that is easy for the model to read) → schema validation → database ingestion → computation. The model is responsible for understanding semantics and generating code, while deterministic programs are responsible for validation and computation. The two have clearly separated responsibilities.
2. Overall Architecture: Breaking the Task into Verifiable Steps
A recommended design splits the system into five layers, decoupled from each other through files and database tables:
- Ingestion layer: read the exported statement, and unify encoding and delimiters.
- Conversion layer: convert the spreadsheet into structured markup text, preserving the original row numbers for traceability.
- Semantic layer: the large language model generates the field mapping and extraction script, which is frozen after manual confirmation.
- Storage layer: a local relational database with normalized design, keeping both the raw table and the cleaned table.
- Analysis layer: market data fetching, backtesting engine, and performance and attribution reports.
The key constraint is that “every step has an artifact, a validation, and is rollback-capable.” For example, the conversion artifact must be comparable line by line against the original file; before ingestion, it must pass primary key uniqueness checks and amount conservation checks (buy amount, sell amount, total fees consistent with account changes).
3. Data Normalization: Fields, Primary Keys, and Validation Rules
A recommended minimal field set is as follows (illustrative):
trade_id -- business primary key: date + time + symbol + side + sequencesymbol -- instrument code (unified zero-padding and exchange suffix)side -- direction enum: BUY / SELLprice -- trade price (fixed-point decimal, floating point forbidden)quantity -- trade quantity (integer)amount -- trade amount = price * quantityfee_commission -- commissionfee_transfer -- transfer feefee_stamp -- stamp dutyfee_other -- other feestrade_time -- timestamp in a unified time zoneraw_line_no -- original row number, for traceback
Validation rules should be frozen as assertions:
- Uniqueness:
trade_idis not duplicated; - Conservation:
amount ≈ price * quantity(sub-cent tolerance allowed); - Completeness: side, quantity, and price are non-empty and positive;
- Consistency: sell-side stamp duty appears only on the sell side, and commission stays within a reasonable range of lower and upper bounds.
Illustrative code (pseudocode, emphasizing the flow rather than a specific library):
def validate(df):assert df.trade_id.is_unique, "duplicate primary key"assert (df.amount - df.price * df.quantity).abs().max() < 1e-6assert df.side.isin(["BUY", "SELL"]).all()assert (df.loc[df.side == "SELL", "fee_stamp"] >= 0).all()return True
4. Market Data Fetching: Resumable, Observable, and Rate-Limited
Backtesting needs both daily bars and intraday data. In engineering terms, “fetching” should be treated as an independent job rather than a one-off script:
- Task list: take the instrument list as input and generate a task table (symbol, frequency, start/end date, status, retry count).
- Resume from checkpoint: use the task status and the maximum date already stored as a cursor, and continue from the cursor after an interruption.
- Rate limiting and backoff: apply token-bucket rate limiting to the data source, and use exponential backoff retries when rate-limited, to avoid the account being restricted.
- Idempotent writes: use a “symbol + frequency + time” unique key for overwrite writes, so repeated runs produce no dirty data.
- Observable progress: output completed/total, current symbol, rate, and estimated remaining time, so you can tell at any time whether it is stuck.
Pseudocode illustration:
for task in pending_tasks:rows = fetch(task.symbol, task.freq, task.start, task.end)upsert(rows, keys=["symbol", "freq", "ts"])task.mark_done()log_progress(done, total, rate)
It is worth emphasizing that different data sources differ in field definitions, adjustment methods, and handling of trading halts. You must record the “data version and adjustment flag” at ingestion time; otherwise the backtesting results cannot be explained.
5. The Right Way to Involve a Large Language Model in Development
A common mistake in practice is handing all requirements to the model at once, which leads to uncontrollable output. A more reliable approach is “humans define the process, the model writes the code, and programs do the validation”:
- First have the model extract the instrument list and field mapping, and verify them manually;
- Then have it generate the data fetching module, requiring logging and progress output;
- Then generate the ingestion script, with unique keys and validation assertions;
- Finally generate the backtesting and reporting modules, requiring reproducible random seeds and a parameter snapshot.
The prompt should contain four elements: input file path and format, output table schema, constraints (rate limiting / idempotency / exception handling), and acceptance criteria (assertions and log fields). Also require the model to explicitly list assumptions where it is uncertain, rather than silently guessing.
6. Backtesting and Attribution: Avoiding Common Statistical Pitfalls
The backtesting part should cover at least: transaction costs, slippage, price limits and trading halts, equity curve, maximum drawdown, turnover rate, and return attribution by symbol and by month. Common pitfalls include look-ahead bias (using information only available after that day’s close), survivorship bias (keeping only currently existing instruments), and overfitting (repeatedly tuning parameters in-sample). Mitigation approaches are out-of-sample validation, parameter sensitivity analysis, and a penalty on the number of trades.
7. Engineering Handling of Exceptions and “Fake Death” Issues
When a large language model assists in generating code, the toolchain occasionally becomes unresponsive for a long time. In engineering terms, there is no need to dwell on the cause; instead, aim for “recoverability”: set a timeout and staged commits for each generation, and continue only after the artifact is written to disk; keep the last working version of the code and roll back on failure; split long tasks into small tasks and accept them one by one. This way, even if interrupted, the completed portion is not lost.
8. Conclusion and Recommendations
Turning personal trading records into objective analysis depends not on how strong the model is, but on data normalization, step-by-step process decomposition, and result reproducibility. A suggested rollout order: first do field mapping and validation, then market data fetching and resume-from-checkpoint, and finally backtesting and attribution. If you need to handle larger-scale data and task scheduling, you can adopt general cloud capabilities (such as object storage for raw files, a message queue for task distribution, a container platform for running fetching and backtesting jobs, and logging and monitoring/alerting services to observe progress), evolving a one-off local script into a sustainable personal quantitative analysis platform.
