Building a Securities Trading Backtesting System with LLMs: A Practical Guide
This article walks through the engineering practice of building a securities trading backtesting system with large language model assistance. It covers a five-layer architecture, converting unstructured trade records into structured text, driving data retrieval in small verifiable steps, designing normalized and extensible local tables, adding progress feedback and fault tolerance, and keeping backtest analysis rigorous. The key takeaway is that LLMs should handle requirement breakdown, code generation, and documentation work, while numerical conclusions must be decided by code.
1. Why This Project: Starting from a Simple Need
Many developers have had a similar experience: the account curve swings unpredictably, returns stay negative over the long run, and it is hard to tell whether the problem lies in stock selection, market timing, or position sizing. A common piece of industry advice is to repeatedly review your own trade records and extract stable trading patterns from them. Acting on that advice is impractical if you have to scroll through settlement statements by eye. The only workable path is to structure trading behavior and then replay it quantitatively against historical market data.
This article is not about benchmarking model capabilities. It addresses a more general engineering question: how to embed a large language model’s natural language understanding into a rigorous data analysis pipeline. The core assumption is that LLMs are well suited to requirement breakdown, code generation, and document understanding, but should not hold final decision authority over numerical computation.
2. Overall Architecture
A usable backtesting system has at least five layers:
- Data ingestion layer: importing trade records and pulling market data;
- Storage layer: a local relational database with properly designed schemas and tables;
- Computation layer: signal generation, fill simulation, and cost and slippage modeling;
- Analysis layer: return attribution, risk metrics, and statistics grouped by year and by instrument;
- Interaction layer: progress feedback, logs, and report output.
The LLM is involved mainly in the “glue work” of layers 1, 2, and 5, not in the numerical core of layers 3 and 4.
3. Step 1: Turn Unstructured Trade Records into Structured Text
Trading software usually exports spreadsheet files. Letting a model read a binary spreadsheet directly often leads to misaligned rows and columns, lost numeric precision, and silently truncated fields. The root cause is usually the parsing step rather than the model itself.
A safer approach is to perform a format conversion first, turning the spreadsheet into a well-structured plain-text markup format such as a Markdown table, and only then pass it to the model. After conversion, manually spot-check three things: whether all fields are present, whether numeric units are consistent, and whether date formats are consistent.
Trade Date | Symbol | Side | Quantity | Price | Commission2025-02-11 | 6XXXXX | Buy | 1200 | 12.34 | 5.21
Field definitions must be fixed in advance, especially the difference between “cost including fees” and “cost excluding fees”, which directly changes the profit and loss conclusion.
4. Step 2: Drive Model Data Retrieval at a Controlled Pace
The part most likely to go out of control in practice is handing all requirements to the model at once. For personalized, long-chain tasks, submitting everything in one shot often produces output that deviates from expectations and is hard to debug.
The recommended approach is a small-step confirmation strategy: first have the model extract the instrument list and review it manually; then have it write the data retrieval script; only then execute the database writes. The input and output of each step are verifiable.
Prefer mature market data APIs over web scraping for retrieval. The prompt needs to specify four things clearly: the source of the instrument list, the location of the API documentation, the secure way to pass in credentials, and the requirement to emit observable progress during execution.
# Skeleton: batch retrieval with progress feedbackfor idx, code in enumerate(codes, 1):df = fetch_daily(code, start="2023-01-01", end="2025-12-31")if df is None or df.empty:logger.warning("Empty data: %s", code)continueupsert_daily(code, df) # idempotent write, resumableprint(f"[{idx}/{len(codes)}] {code} done, {len(df)} rows")
Credentials should be injected through environment variables or a local configuration file, never written into prompts or the code repository.
5. Step 3: Keep Local Schemas Normalized and Extensible
Leave room for the future at the schema design stage. It is advisable to split tables into at least four categories: trade detail, daily market data, minute-level market data, and task run records. Each table uses a composite primary key of “instrument + time”, together with a unique index to enable idempotent writes, so repeated runs produce no dirty data.
Extensibility shows up in two places: first, the market data tables retain an adjustment factor field, so a later change in the adjustment method does not invalidate historical conclusions; second, all tables carry a data source and an update timestamp for traceability.
6. Step 4: Progress Visualization and Fault Tolerance
Long-running tasks must have progress output and failure isolation. A failure on a single instrument should not abort the whole run; it should be logged and the loop should continue. Resumable execution is key to handling API rate limits and network fluctuations.
One thing worth flagging: LLM-assisted coding still shows a “freeze” behavior, where a tool call stops responding for a long time and the interface appears stuck. The safe handling is to set timeouts, abort manually and rerun, and split long tasks into smaller batches. This is a tooling maturity issue, not a flaw in model logic.
7. Step 5: Rigor in Backtesting and Analysis
The most common backtesting mistakes are look-ahead bias and survivorship bias. Signals may only use data from the current day and earlier; the instrument pool must include delisted securities; transaction costs, stamp duty, and slippage must be included.
Beyond total return, the metrics should include annualized volatility, maximum drawdown, Sharpe ratio, win rate, and profit-loss ratio, with attribution grouped by year and by instrument. Only then can you tell whether losses come from the system or from individual instruments.
8. Conclusion and Recommendations
Hand your trade records to an LLM and it can produce a structured analysis report, but the conclusion may not be pleasant; it may directly judge that a certain trading approach trends toward losses over the long run. That is exactly what makes the system valuable: a reproducible data pipeline replaces subjective narrative.
The implementation advice comes down to four points: standardize the format before handing data to the model; break requirements into small steps and confirm each one; design storage with extensibility and idempotency in mind; and let code, not the model, decide numerical conclusions. If data volume or concurrency grows further, retrieval and computation can be moved to a combination of cloud container platforms, object storage, and message queues, with log services and monitoring alerts to keep tasks observable.
