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

    This article walks through the practical steps of building a repeatable backtesting system that aligns historical trade records with historical market data. It covers a five-layer architecture, converting broker-exported trade tables into model-friendly text, driving development with step-by-step prompts, designing a normalized and extensible database, handling rate limits and incremental data pulls, and running performance attribution across stock selection, timing, position sizing, and costs. It also highlights common pitfalls such as lookahead bias, survivorship bias, overfitting, data leakage, and model hallucination, showing how disciplined engineering turns vague requirements into verifiable analysis.

    1. Background and Problem Definition

    An ordinary investor with years of experience behind a trading counter, investigating cases, fixing network cables, and running a stall had a poor account performance between the beginning of the year and April, losing more than winning. He repeatedly heard one idea in trading communities: review your own trade records over and over, and extract stable trading patterns from them. This led him to a simple but valuable idea—align historical trade records with historical market data and build a repeatable backtesting analysis system that answers three questions with objective data:

    1. Is my trading behavior statistically significant, or just random fluctuation?
    2. Does my profit and loss mainly come from stock selection, market timing, or position management?
    3. If luck is removed, is my trading pattern sustainable in the long run?

    For model selection, he used a newly released general-purpose large language model (a more capable version for complex reasoning and a lighter, faster version for everyday coding), and connected it to a local development environment through an intelligent coding tool. It should be emphasized that this article does not evaluate any specific model or product, but abstracts a general engineering methodology of “LLM + quantitative analysis.”

    2. Overall Architecture Design

    A usable backtesting system contains at least five layers:

    • Data ingestion layer: exports trade records from broker software and converts them into a text format that the LLM can parse easily.
    • Market data layer: pulls daily and intraday data through a compliant market data API.
    • Storage layer: a local database that is normalized and extensible.
    • Computation layer: the backtesting engine, indicator calculation, and attribution analysis.
    • Presentation layer: progress visualization and report output.
    1. Trade records (table) → document conversion → structured symbol list
    2. ↓
    3. Market data API (daily/intraday) → cleaning and validation → local database
    4. ↓
    5. Backtesting engine → return/drawdown/win rate/attribution → analysis report

    3. Step One: Preprocessing and Format Conversion of Trade Records

    Broker software usually exports table files. Letting the LLM read the table directly tends to cause problems such as “not all data is read, rows and columns are misaligned, and numeric types are misjudged.” A more reliable approach is to first convert it into a structured plain-text markup format (for example, converting the table into a Markdown table), and then hand it to the model for parsing.

    There are three reasons:

    • Plain-text markup is more model-friendly, with clear row and column relationships;
    • It is easy to sample and verify manually, avoiding “model hallucination” contaminating the data;
    • The conversion process is reusable and forms a fixed pipeline.

    After conversion, field completeness needs manual confirmation, at least including: trade date, security code, security name, buy/sell direction, trade quantity, trade price, trade amount, commission, stamp duty, transfer fee, and trade number. Missing fields will directly distort subsequent profit and loss calculations.

    4. Step Two: Driving Model Development with Step-by-Step Prompts

    A common mistake is to throw all requirements at the model at once, resulting in uncontrollable output. A more reliable way is to “think through the workflow first, then hand out tasks step by step.”

    First task: extract the symbol list. Have the model extract all security codes and names from the trade records, then manually review them to confirm there are no omissions, no duplicates, and no code changes caused by delisting or renaming.

    Second task: build the data pulling feature. The prompt should contain six elements: goal, input, output, constraints, observability, and acceptance criteria. Example:

    1. Goal: Build the data pulling module for a stock trading backtesting analysis system.
    2. Input: the confirmed symbol list; local market data API documentation (including access credentials, which must not be written into the code repository).
    3. Requirements:
    4. 1. Prefer the market data API with more sufficient quota;
    5. 2. Pull all daily and intraday data for each symbol;
    6. 3. Store data into a local database, with a normalized and extensible table structure;
    7. 4. Output progress to the console in real time: current symbol, number completed, number of failed retries;
    8. 5. Write failed tasks into a retry queue and support resumable transfer;
    9. 6. Do not hardcode credentials; use environment variables or a local configuration file.
    10. Acceptance: randomly sample 3 symbols and verify that the last 20 trading days of data match the official market data.

    The key to this approach is writing “observability” and “acceptance criteria” into the prompt, so that the model output is verifiable.

    5. Data Layer Design: Normalization and Extensibility

    It is recommended to split into at least four tables:

    • trade_record: trade record details, with trade number as the primary key;
    • daily_bar: daily market data, with (symbol, trade date) as the primary key;
    • minute_bar: intraday market data, with (symbol, trade date, timestamp) as the primary key;
    • adjust_factor: adjustment factors, used to solve return discontinuities caused by ex-rights and ex-dividend events.

    Design points:

    1. Adjustment must be handled upfront. Without adjustment, the return curve shows false gaps and the backtesting conclusions are completely distorted.
    2. Unify time zones and timestamps. Intraday data should be unified to the exchange’s local time to avoid cross-market concatenation errors.
    3. Index first. Build composite indexes by symbol and date, and query performance in the backtesting phase improves by an order of magnitude.
    4. Separate the raw layer from the cleaned layer. Keep the raw stored data and make the cleaning logic a separate layer, which makes it easy to trace problems.

    6. Engineering Details of Data Pulling

    The real pulling process encounters three types of problems: API rate limits, network jitter, and missing fields. Corresponding strategies:

    • Rate limiting and backoff: control concurrency, and use exponential backoff retries when rate limited;
    • Incremental updates: use the maximum trade date as a watermark and pull only increments;
    • Cache first: do not re-request data already stored locally, saving API quota;
    • Data validation: align trading days, ensure non-negative volume, ensure prices fall within the price limit range, and fill or mark missing trading days.
    1. def fetch_incremental(code, start_date, client, db):
    2. last = db.get_max_date(code) or start_date
    3. rows = []
    4. for page in client.iter_pages(code, start=last):
    5. rows.extend(page)
    6. if client.is_rate_limited():
    7. client.backoff()
    8. db.upsert_many(code, rows)
    9. return len(rows)

    7. Backtesting and Attribution: From “Feeling” to “Evidence”

    The backtesting module is recommended to output the following metrics: cumulative return, annualized return, maximum drawdown, Sharpe ratio, win rate, profit/loss ratio, average holding days, turnover rate, and maximum single-trade loss.

    Attribution analysis is the most valuable part of this article, and can decompose returns into:

    • Stock selection contribution: the excess of the symbol portfolio relative to the benchmark;
    • Timing contribution: the difference between buy and sell timing versus random timing;
    • Position contribution: the impact of position changes on volatility and return;
    • Cost contribution: the erosion of commissions and stamp duty on net return.

    A counterintuitive but common conclusion is that most retail investors have negative timing contribution and long-term negative cost contribution, and their final returns depend heavily on a few heavy-position trades. If those trades are removed, the overall result may move toward losses or even “toward ruin.” This is exactly the meaning of systematic review—using data to shatter narratives.

    8. Common Pitfalls and Risk Control

    1. Lookahead bias: placing orders at the open using information only known after the close of the same day is the most hidden and most fatal mistake.
    2. Survivorship bias: only backtesting symbols that still exist, ignoring delisted stocks.
    3. Overfitting: repeatedly tuning parameters until history is perfect, then failing in live trading.
    4. Data leakage: hardcoding credentials and logging sensitive information.
    5. Model hallucination: letting the model “from memory” fabricate market data; the real return of the API must be the source of truth.

    9. Lessons Learned About Using LLMs

    In actual experience, the light and fast version is suitable for code completion and single-file modifications, while the more capable version is suitable for architecture design and complex attribution logic; at the same time, new models may experience response stalls during peak hours, and manually interrupting and retrying usually restores them. The engineering response is: break tasks into small pieces, make each step verifiable, keep context concise, and manually review critical logic.

    10. Conclusion

    The core of this practice is not how powerful a model is, but the ability to “engineer vague requirements”: standardize formats, break workflows into steps, normalize storage, visualize progress, and make conclusions verifiable. When the analysis pipeline is solid enough, tools are just amplifiers; what is amplified is discipline, not luck.