Building an LLM-Driven Backtesting System for Securities Trading: A Practical Guide
This article walks through building a practical, LLM-assisted backtesting system for securities trading, starting from a simple need: turning historical trade records into an objective analysis. It covers a five-layer architecture, exporting and normalizing trade confirmations, using narrow prompts to extract a security list with manual review, pulling market data into a well-structured local database, and handling common model-driven development pitfalls such as stalls, incomplete data reads, and hallucinated parameters. It also explains how to keep backtesting metrics restrained and assumptions explicit. The key takeaway is that LLMs compress repetitive work while humans define the problem, set constraints, and validate results; backtesting verifies historical performance only and does not promise future returns.
1. Where It Started: A Simple Need
Many developers have had this experience: an account goes up and down, and at year-end the settlement records show far more losing trades than winning ones, yet it is hard to say whether the problem lies in stock selection, timing, or position sizing. There is a common piece of advice in the industry: “Review your own trade records repeatedly, and gradually form a stable trading pattern.” The advice itself is sound, but manually going through years of trade details is extremely inefficient and tends to introduce subjective bias.
So a valuable small project emerged: structure historical trade records, connect them with market data, run backtests and statistics in code, and finally produce an objective analysis report. The tech stack for this kind of project is not complicated; the difficulty lies in process design and data quality, and that is exactly where LLMs and intelligent coding tools can help.
One conclusion needs to be stated up front: if this kind of system is treated as a “guaranteed profit tool,” it will most likely end up being judged as “heading toward destruction.” Backtesting can only verify how a strategy performed in the past; it cannot promise future returns. Setting the right expectations is the first step in a project like this.
2. Overall Architecture: Break the Task into Verifiable Small Steps
A maintainable backtesting system is usually divided into five layers:
- Data acquisition layer: pull daily and intraday data from market data interfaces;
- Data storage layer: a local database with a well-structured, extensible schema;
- Computation layer: trade matching, and calculation of positions and equity curves;
- Analysis layer: metrics such as return, drawdown, win rate, and profit/loss ratio;
- Presentation layer: progress output and report generation.
The key lesson is: do not hand all requirements to the model at once. For personalized, long-chain tasks, once the model is allowed to “freely improvise,” the output is very likely to go out of control. A more reliable approach is to think the process through yourself first, then issue instructions step by step, with manual confirmation at each step.
3. Step 1: Export Trade Confirmations and Normalize the Format
Most trading software can export trade details in Excel format. But letting the model read Excel directly is risky: when parsing libraries are called improperly, problems such as row/column misalignment, loss of numeric types, and some data not being read can occur, ultimately distorting the statistical results.
A more reliable approach is to perform a format normalization first, converting the spreadsheet into a structured plain-text markup format (a common industry practice is to convert various documents into Markdown so the model can understand them more easily). After conversion, check three things:
- Whether trade dates are all in the same format;
- Whether amounts and quantities are numeric, and whether there are thousands separators;
- Whether the buy/sell direction field has only two possible values.
An illustrative field structure:
| Trade Date | Code | Name | Direction | Price | Quantity | Commission |
4. Step 2: Have the Model Extract the Security List and Review It Manually
The first instruction should be extremely narrow: extract only the security codes and names that appear in the trade details, deduplicate them, and output a list, with no other computation. The output of a narrow instruction is verifiable and can be rolled back.
Once you have the list, you must compare it manually. Focus on whether there are duplicates caused by delisting, renaming, or code changes. Spending five minutes here can save hours of dirty-data troubleshooting later.
5. Step 3: Connect Market Data and Build the Database Properly
Start pulling data at Step 2. The prompt should hard-code the constraints: data source, security scope, data granularity, storage location, and progress visibility. Example:
Please build a market data pulling feature:1. The targets are the list above;2. Prefer the market data interface already configured locally (the config file contains access credentials);3. Pull all daily and intraday data;4. Write it into a local database with a well-structured, extensible schema;5. Print progress in real time during execution.
A few general conventions are recommended when building the database: create a unique index on the market data table by “security + period + date” to avoid duplicate writes; store raw data and processed data in separate tables; keep a data version or update-time field to support incremental updates; put credentials in a config file, not in the code, and not in version control.
If a single data source has missing fields or rate limits, use cross-validation across multiple sources: use one source as primary and another to fill gaps, and compare prices and volumes for consistency. When the difference exceeds a threshold, raise an alert rather than silently overwriting.
6. Common Problems and How to Handle Them
Model-driven development has three frequent pitfalls:
- Stalls: no output for a long time. The fix is to manually interrupt and rerun, which usually recovers; also split long tasks into small batches.
- Incomplete data reads: prioritize format normalization, and add row-count assertions in the code.
- Parameter hallucinations: the model may invent interface fields that do not exist. For anything involving an interface, require it to read the local documentation before writing code.
7. Backtesting and Analysis: Keep Metrics Restrained
The matching logic must be explicit: whether the execution price is the next day’s open or the same day’s close, how commissions and stamp duty are included, and whether limit-up/limit-down conditions allow a trade. These assumptions should be stated clearly at the beginning of the report.
Core metrics should not be too many: cumulative return, annualized return, maximum drawdown, win rate, profit/loss ratio, and number of trades are enough. When the sample size is too small, no conclusion has statistical significance.
8. Conclusion
The real value of this kind of project is not finding a “sure-win strategy,” but turning vague trading intuition into a quantifiable, reproducible validation process. The LLM is responsible for compressing repetitive work; the human is responsible for defining the problem, setting constraints, and validating results. If decision-making is handed over to the model entirely, the outcome is often being judged as “heading toward destruction” by both the data and the model.
