Building an LLM-Driven Backtesting Analysis System from Historical Trade Records

    This article walks through building a backtesting analysis system from historical trade settlement records, covering a five-layer architecture, format normalization of exported spreadsheets, step-by-step natural-language orchestration of market data retrieval, local database schema design, and common engineering pitfalls such as stalled executions, requirement drift, and inconsistent data conventions. Readers will learn how to use an LLM's code generation and tool-calling abilities to turn scattered execution logs into verifiable, reproducible statistical analysis, with practical prompt elements and validation checkpoints at each stage.

    1. Introduction: Starting from a Real Pain Point

    Many individual investors share a familiar experience: account equity swings unpredictably over long periods, losing trades clearly outnumber winning ones, yet when reviewing performance only a handful of memorable trades come to mind. The root cause is often not “misreading the market” but the absence of a structured review of historical trades. There is a piece of trader folklore that says “keep re-reading your own settlement records until your trading pattern emerges.” Its engineering meaning is straightforward: turn scattered execution records into a data asset that can be counted, attributed, and backtested.

    This article takes “building a backtesting analysis system from historical settlement records” as its goal and breaks down the full pipeline from raw files to an analysis report. It focuses on how an LLM’s code generation and tool-calling capabilities can compress work that would otherwise take days of manual effort into something measured in hours. All product forms discussed here are described in generic terms and do not point to any specific vendor.

    2. Overall Architecture

    A usable backtesting analysis system typically has five layers:

    1. Data ingestion layer: converts spreadsheet files exported from trading software into a machine-friendly text structure.
    2. Data acquisition layer: pulls daily and intraday market data through public financial data interfaces.
    3. Storage layer: a local relational database with a well-defined, extensible schema.
    4. Computation layer: calculates metrics such as returns, win rate, profit/loss ratio, holding period, and drawdown distribution.
    5. Presentation layer: produces an objective analysis report rather than subjective conclusions.

    The key design principle is one-way dependency: each layer depends only on interfaces exposed by the layer beneath it, so replacing any single layer (for example, switching data sources) does not affect the others.

    3. Step 1: Preprocessing the Settlement Records

    Mainstream trading software mostly exports spreadsheet files. Handing a spreadsheet directly to an LLM for analysis carries obvious risk: when the model uses a code interpreter to parse multiple sheets, merged cells, and mixed thousands separators and percentages, it tends to skip rows or misalign columns, which ultimately distorts the statistical basis.

    A safer approach is to perform format normalization first, converting the spreadsheet into a plain-text markup structure. This yields three benefits:

    • Column names and data types become explicit, reducing guesswork by the model;
    • The row count is fixed with no hidden formatting, making chunked feeding straightforward;
    • Any later model or script can reuse the same intermediate artifact at low cost.

    After normalization, manually spot-check several rows at the top and bottom to confirm field alignment before moving on.

    4. Step 2: Driving Data Retrieval with Natural Language

    4.1 Plan the flow first, then let the model act

    One repeatedly confirmed lesson: do not hand the entire set of requirements to the model at once. Personalized tasks are especially prone to getting out of control — the model invents its own directory structure, adds dependencies on its own initiative, and collapses multiple steps into one error that is hard to localize.

    The recommended alternative is “small steps, fast iterations” orchestration:

    1. Step 1: Extract the list of instrument names from the settlement records -> manual confirmation
    2. Step 2: Pull daily data for each instrument and persist it -> verify row counts
    3. Step 3: Pull intraday data -> verify time continuity
    4. Step 4: Compute trade-level metrics -> spot-check a sample
    5. Step 5: Output the analysis report

    Each step should have a verifiable acceptance criterion, so the model’s output can be judged quickly as either “pass” or “redo.”

    4.2 Elements a good prompt should include

    A high-quality instruction should cover at least: the objective, input paths, data source priority, storage requirements, and observability requirements. An example:

    1. Please build a market data retrieval module:
    2. - The instrument list comes from the confirmed result of the previous step;
    3. - Prefer the financial data interface documentation already configured locally (path below);
    4. - Write results into the local database, with a well-defined and extensible schema;
    5. - During execution, output current progress, number of successful records, and failure reasons;
    6. - When the interface is rate-limited, retry with exponential backoff; do not silently skip.

    The “output progress” item is particularly important: it turns black-box execution into white-box execution, so when something goes wrong you can immediately tell whether the problem is network, permissions, or fields.

    4.3 Upfront validation of interface availability

    Before pulling data in earnest, run an interface probe: save the data service documentation as a local text file, have the model generate a test script based on it, call each interface one by one, and summarize the results into an availability report. This avoids discovering halfway through that an interface lacks permission or that fields differ from expectations. In engineering terms, this is the classic “validate the assumption before investing in implementation.”

    5. Step 3: Designing the Local Storage Schema

    A few general conventions are recommended for the storage layer:

    • Build a composite primary key on “instrument + interval + time” for market data tables; this is naturally idempotent, so repeated pulls produce no dirty data;
    • Keep the original fields in the trade records table, and add a column for the normalized direction (buy/sell) and amount to make aggregation easier;
    • Give every table created_at and source fields to guarantee traceability;
    • Index the time fields, so time-range filtering during backtesting does not degrade into full table scans.

    The test for extensibility is simple: when adding a new data interval or a new data source, do existing table schemas need to change? If the answer is “yes,” the abstraction has not gone far enough.

    6. Common Problems and Engineering Responses

    Stalled execution. Some models produce no output for long stretches during long-chain tasks. The response is not repeated retries but rather: reduce the granularity of each task, split long tasks into batches, add timeouts and heartbeat logging inside the script, so a human only needs to terminate and resume from the checkpoint when things get stuck.

    Requirement drift. This shows up as the model adding features that were never requested. The countermeasure is to write “what not to do” into the instruction and to strictly compare deliverables against a checklist at each acceptance step.

    Inconsistent data conventions. Adjustment methods for prices, handling of trading halts, and volume units must be fixed at the start of the project and written into configuration; otherwise backtest conclusions are not reproducible.

    7. Conclusion

    Turning settlement records into a backtestable data asset depends less on how powerful the model is than on whether the workflow is sliced finely enough and every step is verifiable. Only when analysis conclusions are presented as statistical measures rather than emotions do the flaws in a trading pattern truly surface. As for whether the system’s final verdict is optimistic, that is another question altogether — but at least it is backed by data.