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

    This guide walks through building a securities trading backtesting and analysis system with the help of large language models and AI coding tools. It covers breaking a broad requirement into verifiable steps, converting exported trade records into structured text, extracting and manually reviewing the symbol list, testing market data API availability before development, designing a normalized and extensible database, making long-running data pulls observable and resumable, and producing reproducible backtest reports. The focus is on methodology and engineering practice rather than product evaluation. Backtesting results reflect history only and do not constitute investment advice.

    1. Introduction: Starting from a Real Pain Point

    Many individual investors have had a similar experience: their account balance swings up and down over the long term, with losses outweighing gains, yet they can never pinpoint which part of the process is going wrong. Advice circulating on social platforms often says to “review your trade confirmations repeatedly and develop your own trading pattern,” but manually going through every past transaction record is both time-consuming and prone to subjective bias. A more practical approach is to load historical transaction data into a market data database and run backtests, replacing intuitive judgment with reproducible statistical results.

    This article follows that need and discusses how to build a securities trading backtesting and analysis system with the help of large language models and AI coding tools. It does not evaluate any specific product; the focus is on methodology and engineering practice.

    2. Overall Approach: Breaking a One-Sentence Requirement into Verifiable Steps

    A common mistake is handing the entire requirement to the model in one shot and expecting it to automatically produce a usable system. For personalized tasks with strong constraints, this approach easily gets out of control: messy directory structures, missing dependencies, and logic that does not match expectations.

    A more reliable strategy is to think through the workflow yourself first, then drive the model step by step:

    1. Export and clean up the raw trade confirmations;
    2. Extract the symbol list and confirm it manually;
    3. Test the availability of data interfaces;
    4. Set up a properly designed database and load the data;
    5. Write the backtesting and reporting modules.

    Each step should have a clear deliverable so it can be verified before moving on to the next.

    3. Data Preparation: From Spreadsheets to Structured Text

    Most trading software exports spreadsheet files. If you hand them directly to the model, it may parse rows and columns incompletely or misidentify numeric types. There are two ways to address this:

    • Use a document conversion tool to convert spreadsheets into structured markup text, reducing parsing ambiguity;
    • Or explicitly instruct the model in the prompt to first output field definitions and sample data, confirm they are correct, and only then process the full dataset.

    An illustrative field convention looks like this:

    1. trade_date | symbol | security_name | side | volume | price | commission | stamp_duty

    Once the fields are settled, have the model write the parsing script with assertion checks, for example whether the total trade amount is consistent with the total fees.

    4. Symbol Extraction and Manual Review

    The first task should be small enough: extract only the deduplicated security names and symbols from the trade confirmations and output them as a list. Manual review cannot be skipped, because name changes, symbol reuse, and delisted securities will all contaminate the downstream data sources. The confirmed list becomes the symbol pool for backtesting.

    5. Interface Availability Verification: Test First, Develop Later

    Market data usually comes from public financial data API services, and different interfaces vary significantly in permissions, rate limits, and field completeness. The recommended approach is:

    1. Save the API documentation as a local structured document for the model to search;
    2. Have the model generate a minimal test case for each candidate interface;
    3. Run them one by one and summarize the results into a test report, marking each as available, restricted, or unavailable.

    The test report is the foundation for subsequent development and avoids repeated rework on interfaces that turn out to be unusable.

    6. Database Design: Prioritize Normalization and Extensibility

    The database loading stage should emphasize extensibility. It is recommended to split the data into at least three tables:

    1. CREATE TABLE trade_detail (
    2. id BIGINT PRIMARY KEY AUTO_INCREMENT,
    3. trade_date DATE NOT NULL,
    4. symbol VARCHAR(16) NOT NULL,
    5. side TINYINT NOT NULL,
    6. volume INT NOT NULL,
    7. price DECIMAL(10,3) NOT NULL,
    8. fee DECIMAL(10,3) DEFAULT 0,
    9. KEY idx_symbol_date (symbol, trade_date)
    10. );
    11. CREATE TABLE daily_quote (
    12. symbol VARCHAR(16) NOT NULL,
    13. trade_date DATE NOT NULL,
    14. open DECIMAL(10,3),
    15. high DECIMAL(10,3),
    16. low DECIMAL(10,3),
    17. close DECIMAL(10,3),
    18. volume BIGINT,
    19. PRIMARY KEY (symbol, trade_date)
    20. );
    21. CREATE TABLE intraday_quote (
    22. symbol VARCHAR(16) NOT NULL,
    23. trade_time DATETIME NOT NULL,
    24. price DECIMAL(10,3),
    25. volume BIGINT,
    26. PRIMARY KEY (symbol, trade_time)
    27. );

    Key design points include: unique primary keys, indexes covering common queries, fixed-point decimals for monetary amounts, and separate storage by time granularity.

    7. Progress Visualization and Long-Running Task Management

    Data pulling is a long-running task, so the process must be observable. You can ask the model to output layered progress: the current symbol, the number completed, the number of failed retries, and the estimated amount remaining. Logs should be written to both the terminal and a log file to make troubleshooting easier afterward.

    If you use cloud resources, you can combine log services with monitoring and alerting to set threshold-based notifications for task failure rates; batch tasks can use a message queue for peak shaving and retries.

    Another practical problem is that tools occasionally “freeze,” meaning they stop responding for a long time. Ways to handle this include: reducing the granularity of each task, limiting the number of symbols processed per run, manually interrupting and resuming from a checkpoint, and implementing idempotent writes in the script to avoid duplicate data.

    8. Backtesting and Reporting: Making Conclusions Reproducible

    Once the data is complete, the backtesting module should fix its parameters and conventions, such as holding period, sell rules, fee model, and whether stamp duty is included. The output report should contain at least: number of trades, win rate, profit/loss ratio, maximum drawdown, annualized return, and attribution breakdown by symbol and by month.

    It is worth emphasizing that backtesting conclusions only reflect history and do not constitute investment advice.

    9. Common Pitfalls Checklist

    • Sending an overly large requirement all at once, leading to uncontrollable output;
    • Skipping interface pre-testing and having to rework midway through development;
    • Incomplete spreadsheet parsing, causing data to be silently lost;
    • No unique constraints in the database, so repeated pulls create dirty data;
    • No checkpoint resume, so a long task has to start over after a failure.

    10. Conclusion

    The key to treating a large language model as a “conversational executor” rather than a “black-box generator” is to own the workflow, keep steps minimal, and make outputs verifiable. Following the path above, individual investors can also build a clearly structured, extensible trading backtesting and analysis system at very low cost, turning a vague sense of loss into a quantifiable basis for improvement.