Building a Personal Stock Trading Record Backtesting System with LLMs: A Practical Guide

    This article explores how individual investors can leverage large language models (LLMs) to build a personal stock trading record backtesting system. It details the project's goals, technical path, and a step-by-step prompting methodology. Key practices include structuring heterogeneous data before AI processing, designing robust data pipelines with database unique constraints, and addressing model stability issues. The guide serves as a comprehensive methodology for developers looking to use AI for objective trading behavior analysis.

    Many individual investors experience fluctuating account balances and struggle to identify the root causes of their losses. Experienced traders often suggest reviewing trading records repeatedly to summarize behavioral patterns and form verifiable trading models. However, manually reviewing hundreds of transaction records is tedious and prone to subjective bias. Consequently, using programmatic methods to objectively backtest historical trading records becomes a natural technical proposition.

    With the maturity of LLMs and intelligent programming tools, individual developers can now complete projects that previously required strong programming skills in a relatively short time. Using a “trading record backtesting analysis system” as an example, this article systematically outlines the entire practice process and summarizes a reusable methodology.

    1. Project Goals and Technical Path

    The core goals of the project can be broken down into three steps:

    1. Input: Personal trading records exported from trading software (usually in Excel format).
    2. Processing: Extract the tickers involved in the trading records, fetch corresponding historical market data (daily and intraday), and store it in a local database.
    3. Output: Overlay personal buy and sell points onto historical market data for backtesting, generating objective analysis reports, including metrics such as win rate, profit/loss ratio, holding period, and buy/sell point deviation.

    In terms of the technical path, the coding work is delegated to LLMs, while the developer acts as a “Product Manager + QA Engineer,” responsible for decomposing requirements, confirming intermediate results, and correcting deviations.

    2. Step 1: Structuring Trading Record Data

    Trading records are typically exported as Excel files from trading clients. Directly letting an AI read Excel files presents a common pitfall: the model may misalign column recognition, drop rows, or misparse amount fields when invoking table parsing logic, resulting in an analysis that looks complete but actually misses data.

    A more robust approach is to first convert the Excel file into a plain text structured format (such as a Markdown table or CSV) before processing it with the model. Various general-purpose document conversion tools can transform Office documents into Markdown. The converted text is fully readable by the model, with clear field meanings, significantly reducing parsing errors. After conversion, it is recommended to manually spot-check a few rows to ensure key fields like amounts, dates, and buy/sell directions are correct before proceeding.

    The lesson here is: Data cleaning and format standardization often impact the credibility of the final result more than the subsequent analysis logic.

    3. Core Methodology: Step-by-Step Prompting over One-Shot Requests

    Unlike the common habit of dumping all requirements at once for the model to execute end-to-end, this project adopted a step-by-step strategy, which yielded significantly better practical results.

    The problems with one-shot large requirements include:

    • Output can easily spiral out of control, with unpredictable code structures and assumptions.
    • High cost of locating and rolling back errors when a middle step fails.
    • The model may hallucinate implementations that do not meet expectations based on vague requirements.

    The step-by-step approach involves first figuring out the complete process yourself, then asking the model to complete one clear, small task at a time. After manual verification, you proceed to the next step. For example, in this project, the first step only asked the model to “extract all involved stock names and codes from the trading record data and output a list.” Once the list was confirmed correct, the data fetching phase began.

    This “human-machine pairing, step-by-step acceptance” model essentially applies the iterative development concept from software engineering to prompt engineering, which is especially effective for personalized, non-standardized tasks.

    4. Step 2: Historical Market Data Fetching and Database Design

    After confirming the ticker list, the next step is to fetch market data. Various financial data APIs exist (some offer free personal quotas based on a points system). When choosing, priority should be given to: API documentation completeness, data coverage, and rate limits.

    The prompt provided to the model should include the following elements to ensure the generated code is usable:

    • Clear objective: Using the ticker list as input, fetch all daily and intraday data.
    • Specify API documentation path: Inform the model of the local path to the API documentation (including access credentials) so it can read and follow the API specifications.
    • Database design requirements: “Normalized and extensible” — the table structure should distinguish between ticker tables, daily tables, and intraday tables, reserving space for field expansion. The write logic must consider deduplication and incremental updates.
    • Observability requirements: The fetching process must output specific progress logs (current ticker, number completed, retry status on failure) for easy monitoring of the execution state.

    An illustrative table structure design:

    1. CREATE TABLE stock_daily (
    2. id INTEGER PRIMARY KEY AUTOINCREMENT,
    3. ts_code TEXT NOT NULL,
    4. trade_date TEXT NOT NULL,
    5. open REAL, high REAL, low REAL, close REAL,
    6. vol REAL, amount REAL,
    7. UNIQUE(ts_code, trade_date)
    8. );

    Adding a unique constraint combined with INSERT OR REPLACE semantics naturally supports breakpoint resumption and incremental updates, which is a common best practice in data pipeline design.

    5. Model Stability Issues in Practice

    It must be objectively noted that when using new-generation LLMs for longer tasks, occasional “freezing” may occur — requests take a long time to respond with no output on the interface. The solution is to manually interrupt and re-initiate the execution; usually, the second attempt passes quickly. For developers, this highlights two points:

    1. Automated workflows should include timeout and retry mechanisms; do not assume the model service is always stable.
    2. Another benefit of step-by-step execution becomes apparent here — the small granularity of single-step tasks means the cost of interrupting and retrying is very low, without losing overall progress.

    If such a system is deployed to the cloud for long-term operation, general cloud product capabilities can be used to enhance reliability. For example, object storage can be used to archive raw trading records and market data snapshots, logging services can record the inputs and outputs of each backtest, and monitoring and alerting can track task execution status. Mainstream cloud platforms like Baidu AI Cloud offer these general services, making it easy to upgrade personal scripts into sustainable analysis pipelines.

    6. Backtesting Analysis and Boundary of Result Interpretation

    Once the data is ready, the model can be asked to generate backtesting analysis logic: align each buy and sell order with the daily market data, and calculate metrics such as win rate, average profit/loss, maximum drawdown, and deviation of buy/sell points from the daily highs and lows. It is important to note that backtesting conclusions describe “historical behavioral patterns” and do not guarantee future returns; furthermore, the sample size is limited to the individual account’s transaction records, so statistical significance is limited. The analysis report should be viewed as a review tool, not as investment advice.

    7. Conclusion

    This project validates three general experiences: First, standardizing the format of heterogeneous data like trading records before handing it to AI can significantly reduce parsing errors. Second, step-by-step prompting with manual acceptance is a key pattern for LLMs to reliably complete personalized engineering tasks. Third, data pipeline design should emphasize unique constraints, breakpoint resumption, and progress observability. LLMs are significantly lowering the barrier for individual developers to implement data analysis systems, and clear requirement decomposition skills are becoming a more critical core competency than coding itself.