Building an LLM-Driven Backtesting System for Securities Trading: A Practical Guide
This article walks through building a personal backtesting system for securities trading with the help of large language models. It covers converting brokerage statements into machine-readable text, breaking the work into verifiable stages, validating market data APIs and managing credentials, designing a normalized database schema, running observable data collection jobs, writing effective prompts, handling stalled model sessions, and stating the assumptions and limits of backtest results. Readers will find a reusable workflow that turns subjective trading memory into structured data and reviewable conclusions.
1. Why Individual Investors Need Their Own Backtesting System
Most retail investors review their trades “by feel.” When the market goes well, they credit their own judgment; when it goes badly, they blame bad luck. Neither explanation rests on objective evidence. The first step in analyzing trading behavior is turning subjective memory into structured data: the time, price, quantity, and fees of every buy and sell form the most raw and truthful behavioral log. Only by replaying that log against historical market data can you answer a few key questions — Is my holding-period distribution reasonable? Do my win rate and profit/loss ratio support my current position sizing? Am I systematically adding to positions at the wrong moments?
A usable personal backtesting system essentially has to solve three things: where the data comes from, how it is stored, and how conclusions are computed. All three are “glue work” tasks that large language models handle well, which makes them a good first hands-on project for human-AI collaboration.
2. Data Preparation: Turning Statements into Machine-Readable Text
Statements exported from mainstream trading software are usually spreadsheet files. Handing a spreadsheet directly to a model tends to cause two problems: first, the row and column structure is lost during parsing, so values become misaligned with their fields; second, a long table gets truncated, and the model only “sees” part of the records yet produces a conclusion that looks complete.
A more reliable approach is to add a format-conversion step that normalizes spreadsheet files into a plain-text markup format. Such conversion tools are typically maintained by the open-source community; the idea is to normalize office documents, PDFs, and HTML into structured Markdown, preserving heading levels and the semantics of tables and lists so the model can read the content in segments.
After conversion, do a manual spot check focused on three points:
- Field completeness: whether trade date, security code, buy/sell direction, execution price, quantity, commission, and stamp duty are all present;
- Value accuracy: randomly pick 5–10 rows and compare them cell by cell against the original table;
- Record count consistency: the number of rows before and after conversion must match, to avoid silently dropping data.
This step looks tedious, but it determines the reliability of every later analysis. Errors in the data pipeline amplify all the way downstream, and the resulting “objective report” ends up more dangerous than intuition.
3. Breaking Down Requirements: Why “Explain Everything at Once” Goes Wrong
A common mistake is handing the complete requirement to the model in one shot and expecting it to fetch data, build the database, compute metrics, draw charts, and write the report on its own. Personalized, long-chain tasks drift off course easily in this mode: the model changes a table structure mid-way without notifying downstream steps, or pulls in third-party dependencies that were never agreed on.
A more effective pattern is “the workflow stays in your hands, the model executes”: the developer defines clear stage boundaries, and each stage delivers only one verifiable artifact. The breakdown used in this article:
- Extract the list of instruments from the statement, and confirm it manually;
- Fetch the market data API documentation and localize it into a searchable reference file;
- Run a connectivity test for each API and output an availability report;
- Design the database schema, and write collection code only after review;
- Implement collection tasks with progress output, load the data, and verify completeness;
- Write the backtesting and statistics logic and generate an analysis report.
Setting a “manual gate” at the end of every stage is the key to controlling complexity.
4. APIs and Credentials: Verify Availability Before Writing Business Code
Market data sources generally fall into two categories: paid data services that require credits or permissions, and free open-source financial data APIs. The former have well-defined fields and good stability; the latter offer broad coverage but occasional fluctuations. The recommended engineering strategy is “primary paid source, fallback free source,” with an abstraction layer in the configuration so business code does not depend directly on any single data provider.
Credential management must be emphasized: sensitive items such as tokens and keys should not be hardcoded in source code or prompts. Inject them through environment variables or a local configuration file, and add them to the version-control ignore list. Handing a document containing credentials directly to the model is convenient but creates a leak risk; instead, “the document should only describe the shape of the API, and credentials should be read by the program at runtime.”
The API availability test is best written as a repeatable script that outputs a structured report:
# Example: batch probing of API connectivityresults = []for name, fn in candidate_apis.items():try:df = fn(code="600000.SH", start="20240101", end="20240131")ok = df is not None and not df.emptyresults.append({"api": name, "ok": ok, "rows": 0 if df is None else len(df)})except Exception as e:results.append({"api": name, "ok": False, "error": str(e)})
Once the report is written to disk, the later collection code references only the APIs that passed the test, keeping uncertainty out of the main pipeline.
5. Storage Design: Prioritize Extensibility Over What Suffices Today
The most common mistake in personal projects is “stuffing everything into one wide table.” The proper approach separates dimensions from facts: a securities reference table holds code, name, and listing status; a daily bar table holds open, high, low, close, volume, and turnover; intraday or minute bars go in a separate table because the data volume differs by orders of magnitude; and a trade log table holds your own executions. All tables use a surrogate primary key, with a unique constraint on (symbol, trade_date) so that re-collecting data is naturally idempotent.
CREATE TABLE daily_bar (id BIGSERIAL PRIMARY KEY,symbol VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,open NUMERIC(12,3),high NUMERIC(12,3),low NUMERIC(12,3),close NUMERIC(12,3),volume BIGINT,amount NUMERIC(18,2),CONSTRAINT uk_daily UNIQUE (symbol, trade_date));
Collection tasks must have three properties: resumability (record the latest date already fetched), observable progress (current instrument, completion ratio, number of retries), and failure isolation (one instrument failing does not affect the whole run). Progress can go to a logging service or simply print to the terminal; what matters is that the developer always knows “what it is doing right now.”
6. Collaboration Prompts: Write the Constraints into the Instructions
An effective stage instruction usually contains five elements: goal, input location, output form, constraints, and acceptance criteria. For example, the second stage could be phrased as: take the confirmed instrument list from the previous step as input, read the local API documentation, implement the collection function, and write to the local database; print the processing progress for each instrument; when finished, output the number of records and the date range for manual verification. Stating explicitly in the instruction “do not modify existing table structures” and “do not introduce dependencies that were not specified” significantly reduces rework.
7. Stability Issues: Dealing with a “Frozen” Model
Long periods of no response during long tasks are a fairly common phenomenon with current AI coding tools, possibly caused by an overly long context, blocked tool calls, or an interrupted output stream. Practical countermeasures include: cut tasks into smaller pieces, change only one file per turn, ask the model to present a plan before writing code, set timeouts for command execution, and redirect long logs to a file instead of feeding all of them back into the context. When it hangs, there is no need to retry repeatedly — terminate it and resume from the last verifiable artifact.
8. Verifying Results and the Boundaries of Conclusions
Backtest conclusions must state their conventions: whether commission and stamp duty are included, whether price limits that prevent execution are considered, whether adjusted prices are used, and whether buy/sell points rely on future data. Return figures without these disclosures are meaningless. It is equally important to state the limits of backtesting — historical data cannot cover future liquidity and regulatory changes, and the purpose of a backtest is to expose flaws in behavioral patterns, not to predict returns. In this case, the model’s “conclusions” were clearly exaggerated, which is a useful reminder: model output is a hypothesis to be verified, not a conclusion.
9. A Reusable Methodology
Abstracted from this practice, the path is a general one: data normalization → staged breakdown → API availability verification → normalized modeling → observable collection → statistics with explicit conventions → manual review. The same path applies to log analysis, cost attribution, capacity evaluation, and similar scenarios. If you later need to scale up, you can containerize collection and computation, keep raw snapshots in object storage, decouple collection from computation with a message queue, and cover task failures and data delays with monitoring and alerting — evolving a personal script into a data product that runs sustainably.
