Building a Backtesting System for Securities Trading with LLM Assistance

    This article walks through the practical engineering of an LLM-assisted securities trading backtesting system. It covers a staged pipeline that keeps humans in the loop, converting raw trade exports into structured text, validating fields, testing data APIs before batch pulls, designing a layered and extensible database, making long-running jobs observable, and fixing backtesting assumptions directly in code. It also explains how to cross-validate model-generated conclusions and avoid common pitfalls such as look-ahead bias, so that trade reviews shift from emotional judgment to reproducible, evidence-based analysis.

    1. Why This Project: Turning Emotional Losses into Quantifiable Questions

    Many individual investors share a familiar experience: account equity oscillates for long stretches, losing trades clearly outnumber winning ones, and post-trade reviews end with vague conclusions like “bad luck” or “the market isn’t for me,” based only on memory. Real improvement comes from systematically revisiting your own historical trade records—laying out the time, price, quantity, and fees of every buy and sell, replaying them against historical market data, and checking whether each decision held up given the information available at the time.

    The engineering essence is not complicated. The difficulty lies in three points: whether the data is clean, whether definitions are consistent, and whether conclusions are reproducible. Using a small LLM-assisted project as an example, this article shows how to turn the idea of “I want to backtest” into a clearly structured, extensible analysis system.

    2. Overall Design: Define the Process Before Automating

    A common mistake in practice is handing the complete set of requirements to the model in one shot and expecting end-to-end delivery. For personalized, heavily constrained tasks, this approach easily spirals out of control: messy directory structures, drifting field definitions, and exceptions silently swallowed. A more reliable approach is to think the process through yourself first, then hand it to the model step by step, with a human confirmation point at each stage.

    A recommended pipeline:

    1. Export raw trade details and convert them into structured text with a unified format;
    2. Extract the list of securities and verify it manually;
    3. Localize the API documentation, run connectivity tests for each endpoint one by one, and keep records;
    4. Set up a standardized, extensible local database;
    5. Pull daily and intraday data in batches, with progress output;
    6. Compute trading statistics and backtesting metrics, and generate a report;
    7. Cross-validate the conclusions.

    3. Data Preparation: Format Conversion Is the Hidden Threshold

    Most trading software exports spreadsheet files, and handing those directly to a model for analysis often results in “only part of it was read,” usually because parsing failed or rows and columns were truncated. Converting them into a plain-text markup format significantly reduces ambiguity and makes version control and diff comparison easier.

    Illustrative flow:

    1. raw spreadsheet file → format conversion tool → structured text → field validation → database

    After conversion, field validation is mandatory. At minimum, confirm that trade date, security code, buy/sell direction, trade quantity, trade price, commission, stamp duty, and transfer fee are all present; that dates follow a single format; and that monetary units are consistent (mixing yuan and ten-thousand yuan is the most common source of error).

    4. Security Extraction and Manual Review

    The first task should be deliberately small: have the model extract only the deduplicated security names and codes from the trade details, output them as a list, and have a human compare it once. The value of this step is not the workload but exposing definition problems early—for example, the same security appearing under multiple codes due to dividends or stock splits, name changes, or missing delisting markers. Confirming the list before pulling data avoids large-scale rework later.

    5. API Selection: Test Connectivity First, Then Batch Pull

    Do not assume a given data API is available. The recommended approach: download the API documentation locally as structured text, have the model write test scripts based on it, run connectivity checks for each endpoint one by one, and finally compile a test report that clearly marks which endpoints are usable, what fields they return, what the per-request limit is, and whether extra permissions or credits are required.

    Engineering essentials for batch pulling:

    • Rate limiting and retries: control request frequency and use exponential backoff for timeouts;
    • Incremental updates: start from the latest date already in the database to avoid full re-runs;
    • Idempotent design: use (security code, date, frequency) as the unique key so repeated writes produce no dirty data;
    • Failure isolation: a single security’s failure does not affect the whole job; record the failure reason for a second backfill pass.

    6. Storage Design: Prioritize Standards and Extensibility

    A layered table design is recommended: a raw layer that keeps API responses as-is, a cleaned layer that unifies types and definitions, and a metrics layer that stores backtesting results. Example:

    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. PRIMARY KEY (symbol, trade_date)
    10. );

    Extensibility shows up in two places: first, the frequency dimension (daily bars, intraday) uses separate tables rather than added columns; second, the adjustment method (for splits and dividends) is an explicit column or a separate table, avoiding mixed adjustment definitions that distort returns.

    7. Visible Progress: Make the Process Observable

    A long-running pull job must let the user know “what it is doing” at any time. Practical means include: printing the current security and completion percentage to the console, writing start and end times to a task log table, and summarizing failed entries separately. If it runs in the cloud, general capabilities such as log services and monitoring alerts can handle log collection and exception notification, preventing a task from failing silently for days without anyone noticing.

    8. Backtesting and Metrics: Write the Definitions into Code

    The credibility of backtesting conclusions depends on whether definitions are hard-coded. At minimum, specify: whether buys and sells include commission and stamp duty, whether the fill price uses the close or the open, position limits and per-trade sizing, whether suspended or limit-up/limit-down securities can be filled, and how ex-dividend dates are handled. For metrics, it is best to report win rate, profit/loss ratio, average holding days, maximum drawdown, equity curve, and number of trades together, since a single metric can mislead.

    1. win rate = winning trades / total closed trades
    2. profit/loss ratio = average profit amount / average loss amount
    3. max drawdown = max(1 - current-day equity / historical peak equity)

    9. Conclusion Validation and Common Pitfalls

    Model-generated conclusions must be cross-validated: manually recompute a sample of trades; switch data sources for the same security and compare differences; check whether the sample size is too small (statistics from a few dozen trades have weak significance). Another frequent pitfall is the look-ahead function—using information that was not available at the time (such as data released only after that day’s close) to explain that day’s decision, which inflates backtesting results.

    As for model unresponsiveness or long periods with no output during the process, simply re-running or shortening the per-task granularity usually restores things, which again confirms the robustness of “small-step delivery.”

    10. Summary

    The real output of this project is not a report but a repeatable analysis infrastructure: clean data, clear definitions, an observable process, and verifiable conclusions. When review shifts from emotional judgment to evidence-based judgment, iterating on trading patterns finally has a foundation. One reminder: historical backtesting can only reveal decision-consistency problems, not predict future returns, so any conclusion should retain ample uncertainty.