Building an LLM-Driven Backtesting System for Securities Trading: A Practical Guide

    This article walks through building an automated trading review and backtesting system with the help of large language models. It covers a five-layer architecture, how to preprocess broker trade confirmation files into structured text, how to drive development in verifiable steps using AI coding tools, database schema and ingestion conventions, backtesting and attribution metrics, and common pitfalls such as look-ahead bias and survivorship bias. Readers will find practical validation logic, prompt skeletons, SQL examples, and engineering recommendations for turning subjective trading memory into reproducible statistical evidence.

    1. Why Manual Trading Reviews Are Hard to Automate

    Individual investors’ accounts often show more losses than gains, yet what is truly scarce is not market data but an objective measure of their own behavior. Broker trade confirmation statements only record what happened; they do not explain why it happened or which types of actions are consistently losing money. Manually reading through past executions invites narrative bias: attributing occasional profits to skill and systemic mistakes to bad luck.

    To build reusable trading patterns, subjective memory must be converted into computable data assets, and backtesting turns gut feeling into statistics. This is the value of an automated review system: taking historical executions as input and market price series as a reference, then outputting win rate, profit/loss ratio, maximum drawdown, holding-period distribution, turnover, and attribution breakdowns.

    2. Overall Architecture

    A review system meant to evolve over time is best split into five layers, decoupled through explicit data contracts:

    1. Data ingestion layer: parse trade confirmation files and unify field definitions (execution time, symbol, direction, price, quantity, commission, stamp duty, transfer fee).
    2. Cleaning and standardization layer: handle adjustments for splits and dividends, trading halts, unfillable limit-up/limit-down conditions, missing fields, and duplicate executions.
    3. Storage layer: store structured market data and trade records separately, with extensible table designs and indexes.
    4. Computation layer: signal replay, approximate matching, metric calculation, and attribution analysis.
    5. Presentation layer: report generation, chart visualization, and anomaly lists.

    The key principle is one-way dependency: upper layers depend only on the stable interfaces exposed by lower layers, and no newly generated feature may bypass the storage layer to write business logic directly.

    3. Preprocessing Trade Confirmations: From Spreadsheets to Structured Text

    Trading software typically exports spreadsheet files. Handing a raw spreadsheet directly to an LLM commonly causes long tables to be truncated, numeric columns to be misread, and merged cells to shift rows out of alignment. A more reliable approach is to first convert the data into a structured plain-text markup format (for example, a Markdown table) and then let the model interpret it.

    Three checks are still required after conversion:

    • Whether the row count matches the number of executions;
    • Whether the amount field is approximately equal to quantity × price + fees;
    • Whether the buy/sell direction values form a unique enumeration.

    Illustrative validation logic:

    1. def validate(rows, tol=0.01):
    2. for r in rows:
    3. expect = r.qty * r.price + r.fee + r.tax
    4. if abs(expect - r.amount) > tol:
    5. r.flag = "amount_mismatch"
    6. return rows

    Only by blocking dirty data before computation do all downstream metrics become meaningful.

    4. Driving Development Step by Step with AI Coding Tools

    The pattern most likely to go out of control in practice is handing all requirements to the model at once and letting it improvise. A more reliable approach is to think through the workflow yourself, split it into small verifiable steps, and deliver incrementally.

    Step one: extract the symbol list. Have the model pull every stock code and name from the trade confirmations, then confirm them manually to avoid mismatches caused by delisting, renaming, or code changes.

    Step two: build data-fetching capability. Given local API documentation and a credentials path, require the model to prefer mature market data interfaces and persist results to a database; also require visible progress logs so you can tell at any moment what it is doing.

    Step three: fill in exception handling. Trading halts, delistings, empty fields, and rate limits must all be handled explicitly rather than skipped silently.

    An acceptable prompt skeleton:

    1. Goal: Build a stock trading backtesting and analysis system (Step 1: load market data)
    2. Inputs: symbol list file, path to local API documentation
    3. Requirements:
    4. 1) Prefer the market data interfaces in the documentation; read credentials from a local config file, no hardcoding;
    5. 2) Design the database properly and extensibly, separating market data tables from metadata tables;
    6. 3) Print progress during fetching: completed/total, failure list, estimated remaining time;
    7. 4) Retry failures automatically with rate limiting, and output an ingestion summary report at the end.

    It is worth stressing that newly released large models may stall during long tasks (commonly called “freezing”). The engineering answer is not to wait, but to split tasks smaller, set timeouts, and support resuming from checkpoints so every step is re-entrant.

    5. Data Modeling and Ingestion Conventions

    At minimum, split the schema into four table types: symbol reference data, daily bars, intraday bars, and trade records. Design points include:

    • Use a unified primary key of “symbol + trade date + period”, which is naturally idempotent so repeated fetches produce no dirty data;
    • Use fixed-point or high-precision types for prices and volume to avoid accumulated floating-point error;
    • Keep raw fields and adjustment factors, computing adjusted prices at query time;
    • Build composite indexes for time-range queries;
    • Record the data source and fetch time for traceability.
    1. CREATE TABLE daily_bar (
    2. 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. adj_factor DECIMAL(10,4),
    10. fetched_at TIMESTAMP,
    11. PRIMARY KEY (code, trade_date)
    12. );

    6. Backtesting and Attribution: Let Statistics Carry the Conclusion

    The minimal backtesting loop has four steps: sort by execution time, align with that day’s market data, approximate the fill price with the next day’s open or average price, and compute per-trade profit and loss. Then perform two layers of attribution:

    • Symbol attribution: which codes contributed the largest losses;
    • Behavior attribution: whether patterns such as chasing highs, overtrading, adding to losing positions, and exiting winners too early recur in the data.

    Metrics should be reported with context: win rate, average profit/loss ratio, median holding days, annualized turnover, maximum drawdown, and recovery time. A single metric is easily misleading; only a combination of metrics has explanatory power.

    7. Common Pitfalls and Engineering Recommendations

    • Look-ahead bias: using information known only after the close to decide that day’s execution;
    • Survivorship bias: a symbol list containing only current holdings while ignoring already-closed positions;
    • Ignoring costs: commissions and market impact can materially change conclusions for high-frequency strategies;
    • Non-reproducible results: random seeds, data versions, and code versions must be recorded together;
    • Unreadable reports: state conclusions and confidence first, then details, avoiding piles of charts.

    If data volume grows, market data and trade records can be moved to managed cloud databases and object storage, with a message queue to smooth spikes, a container platform to run fetching jobs, and logging plus monitoring and alerting services to track failure rates, evolving a one-off script into a sustainable pipeline.

    8. Conclusion

    The real value of large language models is not generating a system for you in one click, but translating a clear workflow into executable, verifiable engineering steps. Think the workflow through, keep the data clean, and make every step a re-entrant unit, and the review system grows from a toy into decision infrastructure. As for whether the final conclusion leads to “ruin,” let the statistics and attribution report answer that.