How to Build a Stock Backtesting Data System Efficiently with Large Language Models

    This article presents a practical, step-by-step approach to using large language models to build a stock trading backtesting data system. It explains why breaking work into verifiable stages is more reliable than requesting an entire system at once, then covers security and prompt design, market data collection, progress logging, database architecture, incremental updates, and handling stalled or failed tasks. The central principle is to let humans define the workflow and verify results while the model handles code generation and repetitive implementation work.

    1. Why “Describe Everything at Once” Often Fails

    Many developers who begin using large language models for programming share the same habit: they describe the entire requirement in one prompt and expect the model to deliver a complete system in a single pass. This may work for small utilities or example code, but personalized tasks with a certain level of complexity often produce poor results. The generated code may have a confusing structure, inconsistent naming, and logic that differs significantly from the original expectations. In some cases, fixing the result takes longer than rewriting it manually.

    There are two main reasons for this:

    1. Implicit context is not expressed clearly. People may have a complete picture in their minds, but not all of that context is included in the prompt. The model can only infer what is missing from the available text, and inference inevitably introduces errors.
    2. Large one-shot generations lack intermediate checkpoints. When an error appears early in a long code-generation task, it can be propagated and amplified by later code. The farther the process goes, the harder it becomes to identify the original problem.

    A more reliable collaboration model is to first design the workflow yourself, break the task into small and verifiable steps, and have the model execute one step at a time. After each step, review and confirm the output before proceeding.

    This is not a matter of distrusting the model. It is simply the engineering principle of making small changes and continuously validating them, applied to human-AI collaboration.

    2. A Practical Scenario: Building a Stock Trading Backtesting System

    Consider a system that analyzes stock trading performance based on historical transaction records. The overall workflow can be divided into four stages:

    1. Data preparation: Extract the list of securities from the trading records.
    2. Data collection: Retrieve daily and intraday market data for each security.
    3. Data storage: Design a structured local database.
    4. Backtesting engine: Use the data to run strategies and analyze returns.

    This article focuses on the first three stages, which are also the areas where implementation problems most commonly occur.

    Step 1: Extract and Confirm the Security List

    After obtaining the transaction records, do not immediately ask the model to write a data-download program. First, ask it to extract all referenced securities and produce a clear list.

    Although this may seem unnecessary, it is an important control point:

    • The security list is the input baseline for all subsequent work. If it is incorrect, all later data collection becomes unreliable.
    • The output is plain text, so manual verification takes only a few seconds.
    • An explicit list can be referenced in later prompts, reducing the risk that the model misremembers or omits a security.

    A practical approach is to request a standardized format, such as a table containing each security’s unique identifier. Review the entries row by row before moving to the next stage.

    Step 2: Select the Data Source and Design the Prompt

    If you already have credentials for a market data API, use that source first. Many market data services provide daily, minute-level, and financial data, with access controlled by permissions or usage quotas.

    Several general practices are useful:

    1. Define the data-source priority clearly. Tell the model which API should be used and provide the local path to its documentation. Having the model read the documentation is much more reliable than asking it to recall endpoint signatures from memory.
    2. Manage credentials properly. API tokens should not be hard-coded in source files. Store them in a configuration file or environment variable and have the application read them at runtime. This requirement should be stated directly in the prompt.
    3. Specify the time granularity. “Daily and intraday data” is ambiguous. Clarify whether intraday means one-minute, five-minute, or fifteen-minute data. These choices affect data volume, storage requirements, and API permissions.

    A well-structured prompt might look like this:

    1. I am building a stock trading backtesting and analysis system. The first step is to retrieve
    2. all daily and intraday data for the securities listed above.
    3. Use the local API documentation at: xxx/API Documentation.md.
    4. The documentation contains my API token. Read the token through a configuration file rather
    5. than hard-coding it in the source code.
    6. Write a data collection program and store the results in a local database. The database
    7. schema should be structured and extensible. The program must report concrete progress:
    8. log each completed security and each completed data segment so that I can monitor the
    9. execution status at any time.

    The important elements of this prompt are:

    • A clearly limited scope: perform only the first step.
    • A specified data source and documentation path.
    • Engineering requirements for credential management and progress visibility.
    • Acceptance criteria included directly in the request.

    Step 3: Make Long-Running Operations Observable

    Batch data collection can take a long time. Without progress feedback, it is difficult to tell whether the program is still running or has become stuck.

    At a minimum, the logs should include:

    • The current security and its position in the queue, such as “3/20: Example Corp.”
    • The time range and number of records returned for each data segment.
    • Failure and retry details, including how rate limits and missing data are handled.

    These logs provide evidence for both troubleshooting and intermediate data-quality checks. API calls should also be throttled according to the provider’s rate limits. When appropriate, add retries with exponential backoff.

    3. Engineering Guidelines for Database Design

    For a backtesting system, the quality of the data layer directly affects the efficiency and capabilities of later analysis. After asking the model for a “structured and extensible” design, review the implementation manually against the following points.

    1. Separate table structures. Daily and minute-level data should generally be stored in separate tables. Fields should distinguish trading dates or timestamps, open, high, low, close, volume, adjustment factors, and other relevant values. The adjustment method—such as adjusted, reverse-adjusted, or unadjusted prices—must be recorded explicitly because backtesting results depend heavily on the price-adjustment convention.
    2. Use primary keys and unique constraints. A composite key based on the security identifier and date or timestamp can prevent duplicate records when data is downloaded repeatedly. The design should also support idempotent incremental updates.
    3. Use a relational database. Quantitative market data is naturally structured time-series data, so a general-purpose relational database is usually sufficient. Indexes can be added to optimize queries. If the dataset becomes extremely large, a time-series database or columnar storage system can be considered later. Designing with that possibility in mind is part of making the system extensible.
    4. Maintain metadata. Create a separate data dictionary or metadata table to record each security’s coverage period, last update time, and data source. This makes it easier to resume interrupted jobs and maintain incremental updates.

    4. Handling Execution Problems

    During actual execution, the model may occasionally appear to “freeze,” with no output or progress updates for an extended period. Instead of waiting indefinitely, use the following approach:

    • Stop the task manually and run it again. In many cases, the second attempt completes successfully.
    • Break the task into smaller units, such as downloading data for only three securities per run.
    • Preserve intermediate outputs, including the security list and generated source code. When restarting, continue from those outputs instead of beginning from scratch.

    A stalled task may be caused by temporary instability in the model service or by a generation context that has become too large. From an engineering perspective, designing tasks so they can be interrupted and resumed is one of the most effective forms of fault tolerance.

    5. Conclusion

    The core methodology can be summarized in three principles:

    • Design the workflow before asking the model to implement it.
    • Review and confirm the output after every step.
    • Include engineering standards directly in the prompt.

    A large language model can be a highly efficient executor, but it should not be expected to make all requirements and architecture decisions on your behalf. Developers and models should focus on their respective strengths: humans define the process and enforce quality, while models generate code and handle repetitive work.

    The same “break down the task, monitor progress, and verify frequently” approach remains useful when building the backtesting engine and iterating on trading strategies.