How to Build an LLM-Driven Backtesting System for Trading Records

    This article walks through building a lightweight backtesting and analysis system that turns personal trade execution records into an objective performance report using historical market data. It covers the five-layer architecture, normalizing exported trade files into model-friendly text, driving an LLM through step-by-step prompts with clear acceptance criteria, validating market data APIs before development, making data collection observable, modeling storage with idempotent writes, and running trade-pairing analysis to produce win rate, drawdown, and holding-period metrics. It also lists common failure modes and practical countermeasures.

    1. Background and Problem Definition

    Many individual investors share a familiar experience: their account equity curve drifts sideways for a long time, losing trades outnumber winning ones, yet they cannot tell whether the real problem lies in stock selection, market timing, or position sizing. Answering this question by reviewing trades on gut feeling is nearly worthless. The only reliable path is to convert actual execution records into computable data, then run backtests against historical market data so that conclusions come from data rather than emotion.

    This article targets a concrete goal: ingesting personal trade execution statements, joining them with historical market data, and generating an objective analysis report. It breaks down the full process of building a lightweight backtesting analysis system. The focus is not on any single model or tool, but on how to decompose a vague requirement into engineering steps that an LLM can execute reliably.

    2. Overall Architecture

    A minimum viable system typically has five layers:

    1. Data export layer: export trade details from the trading software;
    2. Format conversion layer: convert spreadsheet files into structured text to reduce parsing ambiguity for the model;
    3. Market data layer: pull daily and intraday data through public data interfaces;
    4. Storage layer: persist to a local database with a well-defined, extensible schema;
    5. Analysis layer: pair buys with sells, compute P&L, and aggregate win rate and holding periods.

    The key design principle is one-way dependency: each upper layer depends only on the confirmed, working output of the layer below it. If any layer has not been validated, work does not proceed to the next one.

    3. Step 1: Normalizing the Trade Statement

    Trading software usually exports spreadsheet files. Handing a binary spreadsheet directly to a model often leads to incomplete row and column reads, misread merged cells and date formats, and ultimately distorted statistics.

    A more robust approach is to first convert the file into a plain-text markup format such as a Markdown table, because such formats are “visible line by line” to the model and significantly reduce the chance of skipped rows. After conversion, manually spot-check three things:

    • completeness of trade dates and times;
    • sign consistency between trade direction and volume;
    • whether cost fields such as commissions and stamp duties are missing.

    An illustrative field layout:

    1. | trade_date | code | name | side | price | volume | fee |
    2. | 2025-02-11 | 6xxxxx | Example | BUY | 12.30 | 1000 | 5.20 |

    Once the fields are aligned, every downstream statistic has a trustworthy foundation.

    4. Step 2: Driving Development with Stepwise Prompts

    The pattern most likely to spiral out of control in practice is “state the entire requirement at once, then wait for the result.” This is especially true for personalized tasks: the model tends to assume data structures on its own and add dependencies without being asked, producing artifacts that do not run.

    A more reliable approach is decomposed, workflow-style collaboration:

    • Step 1, symbol extraction only: pull all stock codes and names from the statement, then confirm them manually;
    • Step 2, interface validation only: test each data interface for connectivity and output a test report;
    • Step 3, collection only: fetch data through the validated interfaces and print progress;
    • Step 4, ingestion only: write records into the local database using the agreed schema;
    • Step 5, only then, metric computation and report generation.

    Each prompt should contain four elements: goal, input path, constraints, and acceptance criteria. Step 2, for example, can be written as:

    1. Goal: verify the availability of the market data interfaces
    2. Input: local interface documentation (including access credentials)
    3. Constraints: use only the interfaces already listed in the documentation; do not add dependencies
    4. Acceptance: call each interface one by one and output a success/failure list with failure reasons

    This style compresses the model’s “creative space” to the minimum, making artifacts reviewable and rollback-friendly.

    5. Step 3: Validating Data Interface Availability

    Any data project should start with an “interface health check” rather than jumping straight into business code. The general practice is to save the interface documentation as a local file, have the model generate a test script from it, call each interface one by one, and record return status, field structure, and rate-limiting behavior, ultimately producing an availability checklist.

    Engineering details worth emphasizing:

    • Credential security: access tokens must not be hardcoded into source code; store them in environment variables or a local configuration file and add them to the version control ignore list;
    • Rate-limit awareness: intraday datasets are large, so batching and retries (exponential backoff is recommended) must be designed in;
    • Field validation: sample-check null rates, timestamp time zones, and adjustment methods for the returned data to avoid the “fetched but unusable” trap.

    6. Step 4: Observable Collection Progress and Storage Modeling

    Long-running tasks suffer most from “black-box waiting.” A collection script must be observable: it should print the current symbol, the number completed, retry counts, and the estimated remaining volume. A simple implementation:

    1. for i, code in enumerate(codes, 1):
    2. df = fetch_daily(code, start, end)
    3. save_to_db(df)
    4. print(f"[{i}/{len(codes)}] {code} rows={len(df)} ok")

    For the storage layer, three normalized tables are recommended: a symbol metadata table, a daily market data table, and an intraday market data table. Use (code, trade_time) as the unique constraint across them and adopt an idempotent write strategy (update if the row exists). This way, repeated runs never create dirty data, and it is easy to extend with additional fact tables and a trade records table later.

    7. Step 5: Backtesting and Analysis Method

    Once the data is complete, the core of the analysis logic is pairing buys and sells: match each sell against prior buys using either FIFO or per-trade matching, compute per-trade P&L, return, and holding days, then aggregate into metrics such as win rate, profit/loss ratio, maximum drawdown, and average holding period.

    The output report should contain at least three layers of conclusions: overall return attribution, P&L distribution by symbol, and bucketed performance by holding period. Only after bucketing can you determine whether the problem is “failing to hold winners” or “failing to cut losses.”

    8. Common Problems and Countermeasures

    • Model response stalls: long tasks occasionally produce no output for a long stretch; interrupt and resume, and require the model to persist intermediate results each time so the run is recoverable;
    • Context bloat: overly long documents and logs dilute attention, so feed content in segments and keep only the fragments needed for the current step;
    • Hallucinated interfaces: the model may invent parameters that do not exist, so the local documentation must be the single source of truth and verification must be enforced during acceptance;
    • Untrustworthy results: keep the raw data and scripts behind any statistical conclusion so that results are reproducible.

    9. Conclusion

    The real value of this kind of project is not letting the model make decisions for you, but turning the experience of “repeatedly staring at trade statements” into an automated, reproducible data pipeline. The method transfers to any scenario that needs “tabular data + external data + statistical conclusions”: normalize the input first, collaborate step by step, validate before developing, and make things observable before chasing speed. Once the workflow is fixed, the model’s capability is reliably converted into engineering output.