How to Build an LLM-Driven Backtesting System from Broker Trade Confirmations

    This article walks through the practical engineering of turning exported trade confirmations into a reproducible backtesting and statistics pipeline, with the large language model acting as a code generator rather than an analyst. It covers a five-layer architecture, normalizing spreadsheets into structured text, driving development with step-by-step prompts and human checkpoints, probing public market-data APIs before implementation, relational schema design for idempotent incremental loads, and the metric definitions used for trade pairing, win rate, and drawdown. It also lists common failure modes and the controls that keep results verifiable.

    1. Starting Point: Why Trade Confirmations Need to Become Computable Data

    Most individual investors’ account curves show a long pattern of sideways movement, with drawdowns outweighing gains. The cause is usually not stock-picking ability but the absence of an objective measure of their own behavior. A common piece of community advice is to review trade records repeatedly until a stable trading pattern emerges, yet manually reading through hundreds or thousands of fill records makes statistical conclusions practically impossible. A workable alternative is to structure historical trade records, align them with market data from the same period, and use backtesting plus statistical metrics to produce verifiable judgments.

    The hard part of this pipeline is not model capability but engineering constraints: whether the data is complete, whether fields are normalized, whether interfaces are usable, and whether intermediate results are reproducible. This article therefore follows a “process first, implementation second” structure, limiting the model’s role to executor and code generator, while a human owns process definition and result validation.

    2. Overall Architecture and Data Flow

    A maintainable analysis system is best split into five layers:

    1. Export layer: export fill details from the broker or trading software, typically as spreadsheet files.
    2. Normalization layer: convert the spreadsheet into structured plain text to reduce parsing ambiguity for the model.
    3. Market data layer: pull daily and intraday data through public data interfaces, validating fields before anything is stored.
    4. Storage layer: a local relational database, with schema fields reserved for extension and for marking data sources.
    5. Analysis layer: pair buys with sells, compute the P&L distribution, holding periods, win rate, and drawdown, then output a report.

    The data flow is one-directional, and every layer produces an inspectable intermediate artifact (converted text, an interface test report, row-count statistics for the load). These artifacts are the basis for troubleshooting later.

    3. Step One: Normalizing the Trade Confirmation File

    Handing a spreadsheet directly to the model tends to produce problems such as “only the first N rows were read,” incorrect column type inference, and merged cells causing rows to shift. A safer approach is to first convert it into a clearly structured, line-based text table, then have the model extract fields from that text.

    After conversion, three things need human confirmation: completeness of trade dates and times, whether the values of the buy/sell direction are consistent, and whether amount and quantity units match (mixing yuan with ten-thousand yuan, or shares with lots, is the most common source of error). If there are non-trade records such as dividends, stock splits, or fees, they should be flagged separately so they do not contaminate P&L calculations.

    A sample field specification:

    1. date | Trade date, normalized to YYYY-MM-DD
    2. time | Trade time, normalized to HH:MM:SS
    3. code | Security code, original number of digits preserved
    4. name | Security name, used only for verification
    5. side | BUY / SELL, no mixed-language values allowed
    6. price | Average fill price, float, in currency units
    7. volume | Fill quantity, integer, in shares
    8. amount | Trade amount, float, in currency units
    9. fee | Fee, float, in currency units

    4. Step Two: Driving Model Development with Stepwise Prompts

    One repeatedly confirmed lesson: throwing all requirements at the model at once makes the output easy to lose control of, with a messy directory structure, missing dependencies, and error handling quietly omitted. A more reliable approach is to break the work into small verifiable tasks, each producing a result that can be checked immediately.

    A recommended prompt skeleton has four parts: role and goal, input locations, constraints, and acceptance criteria.

    1. Goal: Build the data acquisition module of a securities trading backtesting analysis system.
    2. Inputs: locally converted trade confirmation text; locally saved public data API documentation.
    3. Constraints:
    4. 1. Use only the interfaces listed in the documentation; do not invent parameters;
    5. 2. Read credentials from local environment variables; never write them into code or logs;
    6. 3. The database schema must include a source marker and an update timestamp field;
    7. 4. The fetch process must report progress (completed/total, failure list).
    8. Acceptance: process only 5 symbols first, print the number of rows loaded and sample records, then wait for human confirmation before the full run.

    The first step should only have the model extract the symbol list for human review; only the second step implements fetching and loading. This “small steps plus a human gate” pattern keeps the cost of locating an error as low as possible.

    5. Step Three: Multi-Source Data and Interface Availability Checks

    Market data usually comes from several public sources that differ substantially in coverage, rate limits, and field naming. Coding the calls directly often means discovering halfway through a run that an interface is not authorized or a field is missing.

    A more engineering-minded prerequisite is interface probing: first obtain the API documentation and save it as local text, then have the model generate a separate test script for each candidate interface, run them one by one, and aggregate the results into a test report. The report should contain at least: whether the call succeeded, the list of returned fields, the maximum number of records per call, time range limits, and a classification of failure reasons. Deciding which interfaces to use in the real implementation based on that report avoids rework later.

    One security baseline needs emphasis: access credentials are read only from environment variables or local configuration, never committed to a code repository, never written to logs, and never placed in a prompt.

    1. import os
    2. # Read credentials only from the environment to avoid hardcoding and log leakage
    3. TOKEN = os.environ.get("DATA_SOURCE_TOKEN")
    4. if not TOKEN:
    5. raise RuntimeError("Missing data access credential; configure the environment variable first")

    6. Step Four: Local Database Design Essentials

    The goal of the storage layer is to be extensible, reproducible, and incremental. A relational database is recommended, built around three core tables: security reference data, daily market data, and intraday market data, with a composite unique constraint on symbol and trade date, plus a unique index to make writes idempotent and support resuming from a checkpoint.

    Design checklist:

    • Unify time and timezone; do not compare date fields as strings.
    • Keep the original data source field to enable cross-validation across sources.
    • Record the load batch and update time to support incremental sync.
    • Use a high-precision numeric type for prices to avoid accumulated floating-point error.
    • Build composite indexes for common queries (symbol + date range).

    7. Step Five: Backtesting and Metric Definitions

    Once the data is in place, the core of the analysis is reconstructing discrete fills into “trade pairs.” A common convention is first-in-first-out or per-fill pairing, matching each sell against an earlier buy and computing gross profit per pair, then subtracting fees on both sides to get net P&L.

    The basic metrics should include: total return, annualized volatility, maximum drawdown, win rate, profit/loss ratio, average holding days, and largest single-trade loss. To keep conclusions from being distorted, three rules must be explicit: do not draw strategy conclusions when the sample is too small; flag extreme market conditions and trading halts separately; and report the calculation process for every metric rather than the conclusion alone, so results can be reviewed.

    8. Common Problems and Risk Controls

    • The model hangs for a long time during execution: set timeouts and stage checkpoints, then rerun from the most recent completed step instead of starting over.
    • Parsing results that “look right but are statistically wrong”: cross-validate with checkable aggregates such as row counts and total amounts.
    • Interface rate limiting: add backoff retries and request intervals, and queue failed items separately.
    • Non-reproducible conclusions: pin dependency versions and keep the original intermediate files and random seeds.

    9. Conclusion

    The value of handing trade reviews to automation is not how optimistic the model’s conclusions are, but that it converts subjective narrative into checkable numbers. When the system reports that “the current behavior pattern has a negative long-term expectation,” the most valuable next action is not more parameter tuning but reducing position size and trading frequency, then re-validating the process itself over a longer sample. Stepwise decomposition, layer-by-layer acceptance, and transparent metric definitions are the parts of this kind of personal data engineering project that are genuinely reusable.