Building a Large Language Model-Powered Backtesting System for Securities Trading: A Practical Guide

    This article walks through the practical steps of turning personal trading execution records into structured, computable data for backtesting with the help of large language models. It covers standardizing trade statements, breaking requirements into verifiable steps, designing local market data storage, making long-running data pulls observable and recoverable, and moving from data to backtest metrics. The core idea is that the model handles repetitive work while the human defines the workflow and acceptance criteria. Readers will learn a reusable methodology for building a sustainable personal trading review pipeline.

    1. The Starting Point: Why Turn Execution Records into Computable Data

    Many individual investors face a similar frustration: their account swings repeatedly from the start of the year into spring, losing trades outnumber winning ones, and reviews rely on memory and emotion, making conclusions hard to reproduce. A piece of widely shared advice in the industry is to repeatedly review your own trade records and extract stable trading patterns from them. To put this advice into practice, the prerequisite is converting non-computable paper or spreadsheet records into structured data that can be computed, counted, and backtested.

    The problem chain this article addresses is clear: export trade details → unify them into a machine-friendly text format → use a large language model to generate data-fetching and ingestion code → validate the results → move into metric calculation and backtesting. The core of the whole process is not “letting the model make decisions for me,” but letting the model take on repetitive labor while the human defines the process and acceptance standards.

    2. Step One: Standardizing the Execution Records

    Most trading software can export spreadsheet files, but spreadsheets are not friendly to large language models: merged cells, multi-level headers, mixed date-and-time columns, and floating-point errors in trade amounts and fees all cause the model to “miss rows or misalign rows” when reading. A common approach is to first use a document-conversion solution to turn the spreadsheet into structured markup text, then hand it to the model.

    Three points to note during conversion:

    • Header uniqueness: flatten fields such as “date / time / symbol / name / side / quantity / price / amount / fee / stamp tax” into a single row, avoiding multi-level headers.
    • Explicit typing: unify dates into ISO format, and carry amounts and quantities as fixed-point numbers or strings to avoid precision loss.
    • Missing-value labeling: fill empty cells with an explicit null marker rather than leaving them blank, reducing model misjudgment.

    An illustrative normalized structure:

    1. | trade_date | trade_time | symbol | name | side | qty | price | amount | fee | tax |
    2. |------------|------------|--------|------|------|-----|-------|--------|-----|-----|
    3. | 2025-01-06 | 09:35:12 | 600xxx | SampleA | BUY | 1200 | 12.34 | 14808.00 | 5.00 | 0.00 |

    3. Step Two: Break Requirements into a Process, Not One Big Prompt

    A repeatedly validated lesson is that describing a personalized, long-chain task all at once and letting the model improvise produces output that easily spirals out of control. A more reliable approach is to think the process through yourself first, break it into small, verifiable steps, do only one thing per step, and manually confirm intermediate outputs.

    Recommended breakdown order:

    1. Extract the list of symbols from the trade details, and manually verify that codes and names match;
    2. Design the local storage structure (tables, primary keys, indexes, partitioning strategy);
    3. Implement the market data fetching module, supporting resumable fetching and progress output;
    4. Ingestion validation: row counts, date coverage range, consistency of adjustment methods;
    5. Calculate metrics such as returns, win rate, profit/loss ratio, and maximum drawdown;
    6. Output visualization reports and conclusions.

    This “small steps, fast iteration + manual checkpoints” approach significantly reduces rework costs and makes it easier to pinpoint which layer a problem lies in.

    4. Step Three: Fetching Market Data and Designing the Local Database

    For data acquisition, prioritize mature financial data interface services (which usually require points or a permission tier). Organize the interface documentation into a local reference file, and provide it together with access credentials as context to the model, so it generates calling code according to the documentation rather than guessing parameters from memory.

    The database design is recommended to follow extensibility principles:

    1. CREATE TABLE daily_bar (
    2. symbol 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. amount DECIMAL(18,2),
    10. adjust_flag VARCHAR(8) DEFAULT 'qfq',
    11. PRIMARY KEY (symbol, trade_date, adjust_flag)
    12. );
    13. CREATE INDEX idx_daily_date ON daily_bar (trade_date);

    Key points: the primary key includes the adjustment flag to prevent multiple adjustment variants of the same symbol from overwriting each other; indexing by date makes it convenient to batch-read by range during backtesting; amounts use high-precision fixed-point types; table and field names stay semantic to ease later extension with intraday data tables, financial data tables, and factor tables.

    5. Step Four: Observable Progress and Stability Fallbacks

    Long-running fetch tasks fear the “black box” most. Feasible practices include: printing progress and the number of records fetched per symbol in the console; writing completed symbols to a watermark table to enable resumable fetching; applying exponential backoff retries for interface rate limiting and timeouts; landing raw responses to a raw layer first, then cleaning into a detail layer to ensure traceability.

    For stability, in practice you may encounter tool-chain hangs (long periods of no response). A general fallback strategy is: set a timeout for single-step execution; interrupt on no output and restart from the checkpoint; keep logs and intermediate outputs for critical steps to avoid starting over. These practices are independent of any specific tool and are general engineering practices for long-running tasks.

    6. Step Five: From Data to Conclusions

    Once the data is complete, the core of backtesting is to clarify assumptions: buy signals, sell signals, holding period, position management, and trading costs (commission, stamp tax, slippage). At the metric level, cover at least annualized return, win rate, profit/loss ratio, maximum drawdown, and number of trades, and compare by year and by symbol to avoid overall data masking structural losses.

    It is important to emphasize that backtest conclusions only reflect the historical sample and cannot be extrapolated as a guarantee of future returns; over-optimizing in-sample introduces overfitting, so it is recommended to keep an out-of-sample period for validation.

    7. A Reusable Methodology Summary

    • Data first: unified formatting sets the ceiling on analysis quality;
    • Process breakdown: every step is verifiable, and the model is only the executor;
    • Context standardization: interface documentation and credentials are managed centrally to reduce fabrication;
    • Observability and recoverability: the trio of progress, logs, and checkpoints;
    • Cautious conclusions: distinguish in-sample from out-of-sample and control overfitting.

    Once this methodology runs end to end, execution records are no longer a “dismal” stream of transactions, but a sustainable, iteratively improvable personal trading health report. If the data volume grows later, you can introduce object storage for raw data archiving, a message queue for task decoupling, a container platform for scheduling, and logging and monitoring alerting services for runtime observability, forming a complete cloud data pipeline.