Building a Securities Trading Backtesting System with LLMs: A Practical Guide

    This article walks through building a minimal yet practical trading backtesting system driven by large language models (LLMs). It covers a four-layer pipeline architecture, converting broker trade statements into model-readable text, decomposing tasks into verifiable single steps, designing a query-ready database schema, avoiding look-ahead bias, modeling transaction costs, and a checklist of common pitfalls. The core takeaway: humans define the workflow and acceptance criteria, models execute repetitive work, and results must always be verified.

    1. Why This Project: An Unconventional Entry into Quantitative Trading

    The starting point was not ambitious. After years working in counter operations, IT maintenance, and offline business management, one practitioner went through a phase of “frequent trading and unstable returns” on a personal brokerage account. They decided to stop reviewing trades by gut feeling and instead turn several months of real transaction records into a computable data asset, using historical market data for a serious self-audit.

    This need is highly representative: most individual investors do not lack market-data software; what they lack is the ability to align “my own behavior” with “market outcomes” for analysis. This kind of task falls squarely within the comfort zone of today’s LLMs, which excel at translating vague natural-language intent into structured data pipelines and statistical scripts.

    The conclusion to state upfront: handing backtesting over to a model for fully automatic completion is a classic case of over-trust. The approach that actually works is “humans define the process, the model executes, and results are always verified.”

    2. Overall Architecture: A Four-Stage Pipeline

    A minimum viable system can be split into four layers, decoupled from one another through files or table schemas, so that a failure in any single layer does not require rebuilding the whole system.

    1. Data ingestion layer: convert the trade details exported from the broker (usually a spreadsheet file) into a plain-text structure that is easier for the model to parse;
    2. Data acquisition layer: pull daily and intraday market data according to a symbol list, and store it in an extensible local database;
    3. Computation layer: reconstruct matching and positions, model trading costs, and calculate metrics;
    4. Presentation layer: output visualizations and a written diagnostic report.

    The core value of layering is “replaceability.” Today you use a spreadsheet conversion tool; tomorrow you switch to a script that reads directly. Today you use one data feed; tomorrow you switch to another. As long as the table schema stays unchanged, the upper layers require no modification.

    3. Step One: Making the Trade Statement “Readable”

    Feeding a spreadsheet file directly to the model commonly leads to a “only part of it was read” failure. There are usually two causes: merged cells and multi-row headers cause column semantics to drift; and the parsing function reads only the first sheet by default or truncates a long table.

    So it is recommended to first convert the spreadsheet into clearly structured plain-text markup (for example, a table syntax with pipe separators on each row), and explicitly declare the meaning of each field:

    1. | Trade Date | Symbol | Side | Quantity | Price | Commission | Stamp Duty |

    After conversion, always do a spot check: randomly pick three trades and manually verify whether “quantity × price + fees” matches the account change. This step takes five minutes and can save hours of error attribution later.

    4. Step Two: Have the Model “Work in Steps,” Not Make One Big Wish

    A repeatedly validated lesson: dumping the entire requirement on the model at once makes the output easy to lose control—it will invent its own directory structure, pull in dependencies on its own initiative, and hardcode key parameters into the code.

    A more reliable way to collaborate is “process decomposition + single-step acceptance.” The first step does only one thing: extract a deduplicated symbol list from the trade records, and after manual confirmation, move on to the next step.

    The prompt for the extraction step can be written as a task order with clear constraints:

    1. Task: Extract all securities symbols from the provided trade details.
    2. Requirements:
    3. 1. Deduplicate and preserve the order of first appearance;
    4. 2. Output as two columns (symbol, name); leave the name blank if missing;
    5. 3. Do not add any symbol not present in the source text;
    6. 4. Output only the result, no explanation.

    The second step is to pull the data. At this point, spell out “the data source documentation path, how credentials are read, storage conventions, and progress visibility” all at once:

    1. Task: Build the market-data fetching feature.
    2. Input: the confirmed symbol list from the previous step, the API documentation (credentials read from environment variables; hardcoding is forbidden).
    3. Requirements:
    4. 1. Prefer the primary data source, and switch to a backup source on failure;
    5. 2. The database must follow conventions and be extensible, including table-creation scripts and indexes;
    6. 3. Print real-time progress to the console (current symbol / total, success / failure counts);
    7. 4. Support resumable downloads and retry on failure, with retries using exponential backoff.

    Regarding the phenomenon of “the model not responding for a long time,” the engineering response is not to wait, but to set a timeout and a heartbeat: interrupt a single run once it exceeds a threshold, and require the model to output an execution plan before continuing. This turns uncontrollable waiting into controllable retries.

    5. Data Layer Design: Leave Structure for “Questions You Will Ask Later”

    Beginners often equate storing data with “just saving it,” while a mature approach is to first think clearly about how you will query it in the future. It is recommended to split into at least three tables:

    1. CREATE TABLE trade_detail (
    2. id INTEGER PRIMARY KEY,
    3. trade_date TEXT NOT NULL,
    4. symbol TEXT NOT NULL,
    5. side TEXT NOT NULL,
    6. quantity INTEGER NOT NULL,
    7. price REAL NOT NULL,
    8. fee REAL DEFAULT 0
    9. );
    10. CREATE TABLE daily_bar (
    11. symbol TEXT NOT NULL,
    12. trade_date TEXT NOT NULL,
    13. open REAL, high REAL, low REAL, close REAL, volume REAL,
    14. PRIMARY KEY (symbol, trade_date)
    15. );
    16. CREATE TABLE minute_bar (
    17. symbol TEXT NOT NULL,
    18. trade_time TEXT NOT NULL,
    19. close REAL, volume REAL,
    20. PRIMARY KEY (symbol, trade_time)
    21. );

    Three key points: the primary key is the deduplication rule, preventing duplicate fetches from doubling the data; the composite primary key of date and symbol makes incremental updates naturally idempotent; keeping fees in a separate column means that when you later compare “with-fee / without-fee” returns, there is no need to backfill data.

    6. Backtesting Logic: Fix the “Rules” First, Then Talk About Optimization

    The place where individual review most easily deceives itself is secretly using future information in the backtest. The remedy is simple: all buy/sell decisions may only reference completed data from day T and earlier, and a decision made on day T is executed at the open on T+1 or at the next-day average price.

    Costs must be modeled, otherwise high-frequency trading will be severely overestimated:

    1. def cost(turnover, commission_rate=0.00025, min_comm=5.0,
    2. stamp_tax_rate=0.001, slippage=0.0005):
    3. commission = max(turnover * commission_rate, min_comm)
    4. return commission + turnover * (stamp_tax_rate + slippage)

    The evaluation metrics should cover at least: cumulative return, annualized volatility, maximum drawdown, win rate, profit/loss ratio, turnover rate, and number of trades. Looking only at total return will almost certainly lead to the wrong conclusion.

    7. Common Pitfalls Checklist

    • Survivorship bias: backtesting only current holdings while ignoring symbols already closed out;
    • Silent data gaps: suspensions and ex-rights not handled, causing abnormal jumps in returns;
    • Hardcoded credentials: keys embedded in documentation and committed along with the code;
    • Overfitting: parameters repeatedly tuned to perfection on history, then failing out of sample;
    • Overreaching conclusions: treating statistical correlation directly as “investment skill.”

    8. Conclusion: The Model Is the Executor; the Methodology Is the Asset

    The most valuable output of this practice is not any piece of code, but a reusable collaboration paradigm: humans are responsible for defining the process and acceptance criteria, the model is responsible for compressing repetitive labor down to minutes, and the data structures and evaluation metrics are responsible for making conclusions stand up. Once the process is captured, no matter how the tools change, the quality of the review is unaffected—this is the dividing line between upgrading a “feeling” into a “method.”