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

    This article walks through building an LLM-assisted backtesting system for securities trading, covering a four-layer architecture, a step-by-step collaboration workflow, database schema examples, common failure modes, and the metric definitions required for reproducible backtesting and trading behavior attribution. It shows how to use large language models to compress boilerplate coding time while keeping judgment, risk control, and data contracts in human hands.

    1. Why Use LLMs for the “Dirty Work” of Backtesting

    Individual investors have long reviewed their trades by manually reading through execution statements. The pain points cluster in three areas: data scattered across export files from brokerage software, inconsistent field definitions, and the absence of a quantifiable statistical view. The industry adage of “review your execution statements repeatedly until you find your own trading pattern” is essentially a data engineering problem: first turn unstructured or semi-structured records into structured data, then replay them against historical market data, and finally output verifiable metrics.

    The value of LLMs in this kind of task is not making buy or sell decisions for you. It is compressing the time spent writing boilerplate code: parsing tables, wiring up data API calls, writing table creation statements, and generating statistical scripts. Judgment and risk control must still be done by humans.

    2. Overall Architecture: Four Layers

    1. Data ingestion layer: trade record import plus market data fetching (daily bars and intraday bars).
    2. Storage layer: a local relational database, modeled in three tiers: raw, cleaned, and features.
    3. Computation layer: the backtesting engine, responsible for matching, slippage, fees, and advancing position state.
    4. Presentation layer: a metrics dashboard and trade behavior attribution reports.

    The key benefit of layering is idempotency: rerunning any layer does not pollute the others. This matters especially when you repeatedly ask the model to change code.

    3. Step Breakdown and Collaboration Pattern

    3.1 Step 1: Convert exported files into a model-friendly intermediate format

    Trading software usually exports spreadsheets. Letting the model read binary spreadsheets directly tends to cause row and column misalignment and truncated numbers. A more reliable approach is to first convert them into plain-text marked-up documents (for example, converting tables to Markdown tables) and then hand them to the model. After conversion, manually spot-check the first and last rows and the total row to confirm that amount, quantity, and fee/tax fields have not lost precision.

    3.2 Step 2: Extract the symbols first, do not write the system yet

    Give the model only one task at first: extract the list of stock codes and names from the trade records, output it as a deduplicated list, and have a human confirm it. This step is the contract anchor for the whole workflow; all subsequent data fetching and table creation are based on it.

    3.3 Step 3: Deliver data fetching requirements in small steps

    Break a grand goal like “build a backtesting system” into small, acceptance-testable tasks. A reference prompt structure:

    1. Goal: Build a securities trading backtesting and analysis system (step 1 only for now)
    2. Symbol list: see the confirmed result from the previous step
    3. Data source: locally wrapped data access module (credentials stored in a config file)
    4. Task: fetch all daily and intraday data for the symbols above
    5. Requirements:
    6. 1) The database schema must be well-normalized and extensible; provide the DDL first, then write code
    7. 2) Print real-time progress to the console: current symbol, completed/total, retry count for failures
    8. 3) Support resumable runs; repeated execution must not produce duplicate data
    9. 4) On API rate limiting, retry with exponential backoff; do not silently skip

    3.4 Step 4: Table creation example

    1. CREATE TABLE daily_bar (
    2. ts_code VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open DECIMAL(12,3),
    5. high DECIMAL(12,3),
    6. low DECIMAL(12,3),
    7. close DECIMAL(12,3),
    8. volume BIGINT,
    9. amount DECIMAL(18,2),
    10. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    11. PRIMARY KEY (ts_code, trade_date)
    12. );
    13. CREATE TABLE trade_fill (
    14. fill_id BIGSERIAL PRIMARY KEY,
    15. ts_code VARCHAR(16),
    16. direction CHAR(1), -- B/S
    17. price DECIMAL(12,3),
    18. quantity INT,
    19. fee DECIMAL(12,2),
    20. trade_date DATE,
    21. source_row INT -- original row number, for traceability
    22. );

    Keeping traceability fields like source_row is the most overlooked design choice in data projects and saves the most time later.

    4. Common Failure Modes and How to Handle Them

    • Apparent hang with no response: the model produces no output for a long time. The fix is to abort manually and resend the same instruction, which usually recovers. Engineering-wise, split long tasks into smaller ones and keep each task within a single verifiable output.
    • Loss of control from one-shot delivery: the more customized the requirements, the more a human should define the process first and then hand it off step by step.
    • Silently swallowed exceptions: the prompt must explicitly state that failures must raise errors and list them; otherwise missing data gets treated as a normal result.
    • Hardcoded credentials: put access tokens in a local config file excluded from version control, and mask them in logs.

    5. Metric Definitions for Backtesting and Attribution

    The basic metrics should include annualized return, maximum drawdown, Sharpe ratio, win rate, profit/loss ratio, and average holding days. Behavior attribution then measures patterns such as “whether the holding period of losing trades is significantly longer than that of winning trades” and “whether there is chasing of highs at fixed times of day.” All metrics must state the assumptions for commissions, stamp duty, and slippage; otherwise the conclusions are not reproducible.

    6. Engineering Wrap-Up

    Turn the workflow into schedulable tasks: incremental data update, feature computation, backtesting, report generation, with a logging service and monitoring alerts for failure notification. Write intermediate artifacts to object storage for traceability. If a cloud container platform hosts it, managed databases and task orchestration can reduce operational overhead, with the model plugged in only as an assistant for code generation and documentation.

    7. Conclusion

    LLMs can compress the build cycle of a backtesting system from weeks to hours, but only if a human thinks the process through first: standardized intermediate formats, minimal task granularity, confirmed data contracts, and explicit exception and credential policies. Get those four right, and the model output becomes a maintainable engineering asset rather than a throwaway script.