How to Build an LLM-Driven Backtesting and Trade Review System
This article walks through the engineering practice of building a large-language-model-driven system for reviewing securities trades and running backtests. It covers a five-layer architecture, converting exported trade statements into machine-readable text, breaking work into verifiable steps instead of one long prompt, validating market data APIs and managing quotas, designing a normalized local database, and building the backtest engine and reporting layer. It also lists common pitfalls such as lookahead bias, overfitting, and unreliable model output, showing how a repeatable data pipeline turns trading decisions from emotion into evidence.
1. Why Personal Trade Review Needs Engineering
When an account swings for a long time and losses outnumber wins, most individual investors blame “bad luck” or “an unstable mindset,” yet they have no quantifiable chain of evidence. One piece of advice that comes up repeatedly in the industry is to keep reviewing your own real trade records and extract stable trading patterns from them. But manually scrolling through hundreds or thousands of fill records is nearly impossible, and the conclusions are easily contaminated by subjective emotion. The engineering solution is to treat “review” as a data project: first obtain structured data, then align it with historical market data, and finally output objective reports using a consistent set of metrics.
The difficulty of this kind of project lies not in the algorithms but in the data and the workflow. Raw trade records are messy in format, inconsistent in field meaning, and uneven in timestamp precision; market data must cover both daily and intraday granularity; and the backtest has to handle real-world constraints such as commissions, stamp duty, slippage, and the inability to trade at price limits. If any one of these stages is vague, the final report will be distorted.
2. Overall Architecture
It is best to split the system into five layers, with layers communicating only through explicit data contracts:
- Data ingestion layer: parse exported spreadsheet files and unify field naming and types.
- Data service layer: pull historical data for the symbol list through a public market data API, then store it locally and update it incrementally.
- Storage layer: a normalized local database with separate tables for market data and trades, plus indexes.
- Backtesting engine layer: replay history according to strategy rules and output per-trade signals and position changes.
- Reporting layer: generate metric summaries, charts, and conclusion text.
The core benefit of layering is “replaceability.” The data source can be swapped, the backtest rules can be swapped, and the report template can be swapped, without rebuilding the entire project.
3. Step One: Turn the Statement into a Machine-Readable Format
Most trading software exports spreadsheet files. If you hand the spreadsheet directly to a large model for analysis, common problems arise: long tables get truncated, numeric columns are treated as text, and merged cells shift fields out of place, so the model ends up “reading only the first few dozen rows and drawing conclusions.”
A more reliable approach is to normalize the format first: convert the various spreadsheets into lightweight markup text, then let the model interpret it. After conversion, three things must hold: one record per line, unique and semantically clear column names, and amounts and quantities as pure numbers. A sample field specification looks like this:
trade_date | symbol | name | side | price | volume | amount | fee | tax2026-01-06 | 600xxx | Sample Co. | BUY | 12.34 | 1000 | 12340.00 | 5.00 | 0.00
Also add a “data quality flag” column that records missing values, abnormal prices (such as 0 or beyond the day’s price limit), and so on, so they can be filtered out later. Doing this step solidly raises the credibility of every analysis that follows.
4. Step Two: Replace One Long Prompt with Stepwise Collaboration
A common mistake is to throw all requirements at the model at once and expect it to complete an end-to-end system automatically. Highly personalized, strongly constrained tasks easily go out of control under a single long instruction: the directory structure becomes messy, dependencies are pulled in arbitrarily, and requirements change while the code is being written.
A more reliable approach is to cut the task into verifiable small steps, each with a clear deliverable and acceptance criteria:
- Step 1: Extract a deduplicated symbol list from the trade records and confirm it manually.
- Step 2: Download the data API documentation locally to form a structured description file.
- Step 3: Test each API for connectivity and field validity, output a test report, and mark usable APIs and quota limits.
- Step 4: Design the database schema and submit it for review before writing the storage code.
- Step 5: Implement the backtest logic and finally generate the report.
At each step, require the model to first explain the plan, then write the code, and finally provide a self-test method. Having a human act as a “gate” between steps is the key to controlling complexity.
5. Step Three: Validate Data APIs and Manage Quotas
Market data is usually accessed through token-based APIs, and different APIs differ markedly in rate limits, history depth, adjustment methods, and intraday granularity. In engineering, validate before use to avoid discovering halfway through that a field does not exist.
The validation checklist should include: whether authentication succeeds, whether the returned fields match the documentation, the maximum number of records returned per call, the pagination and looping strategy, the effect of adjustment parameters on prices, and the retry and backoff mechanism for failures. Sensitive information such as tokens should be injected through environment variables or a local configuration file and added to the version-control ignore list; it must never be hardcoded in a script.
import os, time, requestsTOKEN = os.environ["DATA_TOKEN"] # Read the token from an environment variable; never write it into codedef fetch(url, params, retry=3):for i in range(retry):resp = requests.get(url, params={**params, "token": TOKEN}, timeout=10)if resp.status_code == 200:return resp.json()time.sleep(2 ** i) # Exponential backoffraise RuntimeError("API failed repeatedly")
6. Step Four: Normalized Local Database Design
Design storage for extensibility: adding symbols, raising frequency, or adding factors should not require schema changes. It is advisable to split into at least four tables — a symbol reference table, a daily market data table, an intraday market data table, and a trade detail table — all using “symbol code + time” as a composite primary key, with an index on the time column. Use fixed-point numbers or integers in the smallest currency unit for amounts to avoid accumulated floating-point error.
Ingestion should follow a “write to a temporary table, validate, then merge” pattern, combined with unique constraints to make it idempotent so that repeated runs produce no dirty data. Also record the fetch time and source of each batch to make it traceable.
7. Step Five: Backtesting and Reporting
The backtesting engine must explicitly define: initial capital, position rules, buy and sell trigger conditions, the fee model, handling of unfillable trades (price limits, trading halts), and a fallback strategy for missing data. The output should include at least total return, annualized return, maximum drawdown, win rate, profit/loss ratio, number of trades, and average holding days.
For the reporting layer, it is best to separate “metric calculation” from “conclusion generation”: metrics are computed deterministically by code, while the conclusion text can be written by the model based on the metrics, but it must cite the source of the metrics to prevent the model from making judgments out of thin air.
8. Common Problems and Risk Control
- The model is unresponsive for a long time: interrupt it promptly and reduce the task granularity; do not waste time in endless waiting.
- Lookahead bias: using future data by mistake in a backtest is the most hidden and most fatal error, so slice strictly by time.
- Overfitting: repeatedly tuning parameters inflates historical performance, so keep an out-of-sample period for validation.
- Extreme conclusions: if the model gives an absolute judgment such as “certain failure,” treat it as a signal to go back and check the data and workflow item by item, rather than as a fact.
9. Conclusion
Turning trade review into a repeatable data pipeline is worth far more than a one-off conclusion. Its real output is not a single evaluation but a set of methods that can be tested and iterated: standardized data, verifiable steps, and reproducible metrics. Only when the workflow is stable does the basis for decisions shift from emotion to evidence.
