Building an LLM-Assisted Trading Backtest System: A Practical Guide

    This article walks through the practical engineering of an LLM-assisted backtesting and analysis system that turns raw brokerage trade exports into computable data. It covers a five-layer architecture, field normalization, format conversion with validation, step-by-step human-AI collaboration, market data fetching with visible progress and resumable checkpoints, local database schema design, core analysis metrics, and common pitfalls with mitigation strategies. The key takeaway is that the value comes not from the model itself but from workflow decomposition, data validation, and observability design.

    1. Background: Why Turn Trade Confirmations into Computable Data

    Most individual investors and small research teams face the same problem: trading records are scattered across export files from brokerage clients, with inconsistent formats and redundant fields. They cannot be analyzed directly, and they rarely lead to stable, repeatable review conclusions. The “P&L curve” provided by charting software is usually a presentation of results, not a reusable analytical asset.

    A more valuable approach is to structure historical trade details and align them with market data from the same period. This lets you answer specific questions: Is the distribution of holding periods reasonable? Are losses concentrated in a particular type of instrument? Do the trigger conditions for adding to or reducing positions contain systematic bias?

    This article uses an LLM-assisted backtest analysis system as an example to show how to turn an “idea” into “engineering.”

    2. Overall Architecture

    A usable backtest analysis system is typically divided into five layers:

    1. Data ingestion layer: exports trade details from trading software and normalizes formats.
    2. Data transformation layer: converts tabular files into plain-text structures that LLMs can parse more easily.
    3. Market data layer: fetches daily and intraday data based on the instrument list.
    4. Storage layer: a local database with a well-structured, extensible schema.
    5. Analysis and presentation layer: generates statistical metrics, group comparisons, and visualization reports.

    The key design principle is “one-way flow with layer-by-layer validation.” The output of each layer must be a stable structure that the next layer can consume directly, preventing errors from accumulating along the pipeline.

    3. Step 1: Export and Format Normalization

    Trading software usually exports tabular files with inconsistent field names. Common issues include missing standardized trade direction, incomplete fee breakdown, and inconsistent timestamp precision. Start by building a field mapping table that maps original column names to unified Chinese fields or English snake_case fields:

    1. Trade time -> trade_time
    2. Symbol -> symbol
    3. Security name -> name
    4. Buy/sell direction -> side (buy/sell)
    5. Trade volume -> volume
    6. Trade price -> price
    7. Transaction amount -> amount
    8. Commission -> fee
    9. Stamp duty -> tax

    The goal of normalization is to ensure all subsequent statistics are based on the same semantics, rather than handling differences ad hoc during each analysis.

    4. Step 2: Use Format Conversion to Solve the “Incomplete Reading” Problem

    A common pitfall in practice is handing a tabular file directly to an LLM for analysis, only to have the model read part of the rows or misinterpret column meanings, leading to distorted conclusions. The cause is often not model capability but an unsuitable input format.

    A more reliable approach is to first convert the file into structured plain text (for example, a Markdown table or CSV text) and then pass it to the model. After conversion, perform three checks:

    • Row count consistency: the number of records before and after conversion must be equal.
    • Numeric sampling comparison: randomly select several rows and verify amounts and volumes.
    • Null and outlier statistics: identify missing fields and extreme values in advance.

    Illustrative validation logic:

    1. def validate(md_rows, raw_rows):
    2. assert len(md_rows) == raw_rows, "Row count mismatch; data was lost during conversion"
    3. for i in (0, len(raw_rows)//2, len(raw_rows)-1):
    4. assert md_rows[i]["amount"] == raw_rows[i]["amount"]
    5. return True

    5. Step 3: Step-by-Step Human-AI Collaboration, Not a Single One-Shot Request

    A repeatedly confirmed lesson is that handing a complete requirement to the model all at once easily produces uncontrolled output, especially for highly personalized tasks. A more reliable approach is to think through the workflow yourself first, break it into verifiable small steps, and proceed and confirm step by step.

    Recommended step breakdown:

    • Step 1: Extract the list of instrument names and codes from trade details, and review it manually.
    • Step 2: Build a market data fetching module with a clear data source and invocation method.
    • Step 3: Design the local database schema and load data into it.
    • Step 4: Implement metric calculation and report generation.

    Each step must be “observable”: the fetching process should output progress, and the processing stage should output intermediate statistics, so the user always knows what the system is doing and which step it has reached.

    6. Step 4: Fetching Market Data with Visible Progress

    Market data is usually obtained through data service APIs. Three types of constraints matter: call rate limits, maximum records per request, and tiered field permissions. Handle them in code as follows:

    1. for idx, sym in enumerate(symbols, 1):
    2. df = fetch_daily(sym, start="2020-01-01", end="2024-12-31")
    3. save_to_db(df)
    4. print(f"[{idx}/{len(symbols)}] {sym} done, {len(df)} records")

    It is also advisable to add failure retries and resumable checkpoints: use the instrument plus date range as a unique key, and skip ranges already stored on repeated runs to avoid consuming API quota unnecessarily.

    7. Step 5: Local Database Schema Design

    The storage layer should be split into three core tables: trade details, daily market data, and intraday market data, with reserved fields for extension. Key design points include: unique primary keys, time fields unified as timezone-aware time types, numeric fields using fixed-point types to avoid floating-point errors, and indexes on commonly queried fields.

    1. CREATE TABLE trade_detail (
    2. id BIGSERIAL PRIMARY KEY,
    3. trade_time TIMESTAMPTZ NOT NULL,
    4. symbol VARCHAR(16) NOT NULL,
    5. side SMALLINT NOT NULL,
    6. volume BIGINT NOT NULL,
    7. price NUMERIC(12,4) NOT NULL,
    8. amount NUMERIC(16,4) NOT NULL,
    9. fee NUMERIC(12,4) DEFAULT 0
    10. );
    11. CREATE INDEX idx_trade_symbol_time ON trade_detail(symbol, trade_time);

    8. Step 6: Analysis Dimensions and Report Output

    With structured data, core metrics you can compute include: per-trade P&L distribution, the relationship between holding days and returns, win rate and risk-reward ratio across instruments, the share of commissions and stamp duty in total costs, and whether a “averaging down on losses” behavior pattern exists. Reports should provide both overall conclusions and group-level details, rather than a single aggregate number.

    9. Common Issues and Mitigation Strategies

    • Model response stalls: during long tasks, output may pause for a long time. Interrupt and resume, combined with a resumable checkpoint mechanism to reduce losses.
    • Field misinterpretation: run a small-sample trial first, confirm parsing is correct, then process the full dataset.
    • Insufficient data permissions: confirm API field coverage in advance, and fill gaps with backup sources.
    • Over-interpreting conclusions: when the sample size is small, describe phenomena only and avoid inferring causation.

    10. Conclusion

    Turning trading records into a computable asset is essentially a small data engineering exercise. The value lies not in the model itself but in workflow decomposition, data validation, and observability design. Only when every step is verifiable and reproducible do the analysis conclusions carry real reference value.