Building a Financial Backtesting System with LLM-Assisted Development: A Practical Guide

    This article walks through how to use large language models (LLMs) and AI coding tools to build a stock trading backtest analysis system, covering task decomposition, prompt engineering for data API integration, handling model response failures with resume mechanisms, and designing a normalized, scalable database schema for financial time-series data. Readers will learn a step-by-step workflow for turning LLMs into reliable development partners on complex, data-intensive projects.

    As large language models continue to advance, their role in software engineering has evolved from simple code completion to building complex systems. For developers and enterprises, a key challenge is how to efficiently and controllably harness these general-purpose models for code generation in specific business scenarios. Using a stock trading backtest analysis system as an example, this article explores how to combine scientific task orchestration and prompt design with AI coding tools and LLMs to complete the full engineering workflow—from requirement breakdown to data collection and storage.

    1. Task Orchestration: From “One-Shot” to Step-by-Step Execution

    Developers often try to hand an entire complex requirement to an LLM in a single prompt, expecting a complete, runnable codebase in return. However, for personalized, multi-step tasks, this “all-at-once” approach easily spirals out of control. Constrained by the attention mechanisms over the context window, feeding in too many requirements at once often causes the model to lose focus, produce code with serious logical errors, or miss critical business steps.

    A better strategy for improving accuracy and controllability is to “think through the workflow first, then execute step by step.” Developers should first map out the system’s core data flow, then break the large task into small, independently verifiable subtasks.

    For a financial backtesting system, the first step should not be writing the entire system, but having the LLM extract the list of stock symbols involved from existing trading records. The developer then manually verifies this list, ensuring the foundational data for subsequent steps is correct. This chain-of-thought-style guided approach not only reduces the chance of model hallucinations but also lets the developer stay in control of project progress and direction.

    2. Integrating Data Fetching APIs and Prompt Design

    Once the target stock list is confirmed, the next step is fetching historical market data for those stocks. This typically requires calling a third-party financial data API. To keep the LLM on track, you need to provide precise, structured prompts.

    A well-designed prompt should include the following key elements:

    1. A clear task objective: explicitly state that you need daily and intraday (minute-level) data.
    2. Specified input parameters: provide the confirmed list of target stocks.
    3. External resource paths: point to the local file path of the API documentation, and remind the model that the doc contains an authentication token.
    4. Storage and architecture requirements: specify that the data must be stored in a local database, and emphasize a “well-structured and extensible” design principle.
    5. Process visibility: require the fetching process to print concrete progress, so you can monitor execution status and troubleshoot issues.

    For example, you might write a prompt like this:

    “I need to build a stock trading backtest analysis system. The first step is to fetch all daily and intraday data for the stocks listed above. Using the provided stock list as targets, read the local API documentation file (which contains my token), and start fetching the data, storing it in my local database. The database must be designed to be well-structured and extensible. During the fetching process, I want to see detailed progress so I can understand how you are executing.”

    With this approach, the LLM can accurately parse the API documentation, automatically generate the authentication logic, and write HTTP request code that meets your requirements.

    3. Handling Interruptions During Model Inference

    While LLMs typically generate code quickly, exceptions can occur when the generated code actually calls data APIs and processes responses. For example, you may encounter a “hang” phenomenon—the AI coding tool or model API becomes unresponsive for a long time with no output.

    This hang can be caused by several factors: server-side inference queue congestion, or a timeout triggered while processing a very long context. Developers need a fault-tolerance mindset for such situations. The simplest remedy is to manually pause the current task and restart it.

    However, to avoid duplicated effort and potential data inconsistency from retries, when instructing the LLM to write the data-fetching script, you should explicitly require a “checkpoint and resume” (resumable transfer) mechanism. Specifically, after each stock’s data is successfully fetched and stored, the progress state should be recorded to a local file or a log database. Then, even if a retry is triggered by a model hang or network interruption, the program can resume from the last recorded position—greatly improving the robustness and fault tolerance of the data collection system.

    4. Database Normalization and Extensibility in Practice

    When asking the LLM to generate database schemas and storage logic, “normalized and extensible” is the core architectural requirement. For financial time-series data, a well-designed table structure directly affects the execution efficiency of subsequent backtesting strategies.

    You can instruct the LLM to follow these design principles:

    1. Separate basic info from market data: create an independent stock basic info table (for static attributes such as code, name, and sector) alongside market data tables.
    2. Table partitioning strategy: create separate tables for daily and intraday data. Since intraday data volumes are enormous, use time-based partitioned tables—for example, partitioning by month or by day—to improve query and cleanup efficiency.
    3. Index optimization: given the nature of time-series queries, create composite indexes on the timestamp and stock code columns to avoid full table scans.

    Here is an example of a well-structured schema the LLM might generate:

    1. CREATE TABLE stock_basic_info (
    2. stock_code VARCHAR(20) PRIMARY KEY,
    3. stock_name VARCHAR(50) NOT NULL,
    4. industry VARCHAR(50)
    5. );
    6. CREATE TABLE daily_market_data (
    7. stock_code VARCHAR(20),
    8. trade_date DATE,
    9. open_price DECIMAL(10, 2),
    10. close_price DECIMAL(10, 2),
    11. volume BIGINT,
    12. PRIMARY KEY (stock_code, trade_date)
    13. );
    14. CREATE TABLE minute_market_data (
    15. stock_code VARCHAR(20),
    16. trade_time TIMESTAMP,
    17. price DECIMAL(10, 2),
    18. volume INT,
    19. PRIMARY KEY (stock_code, trade_time)
    20. );

    With these explicit constraints, the LLM can generate production-grade database initialization scripts and data insertion logic.

    5. Conclusion and Outlook

    Leveraging LLMs for development is not just an upgrade in tooling—it is a shift in how developers think. By decomposing complex tasks into clear steps, writing high-quality prompts, and combining them with human confirmation and course correction, developers can effectively harness LLMs to build complex systems such as financial data backtesting platforms. And by designing fault tolerance and retry mechanisms into the architecture, you can keep the project on track despite occasional model response failures.

    In today’s era of deep convergence between cloud computing and AI, combining the code generation capabilities of LLMs with a stable, reliable cloud foundation (such as the relational database, object storage, and message queue services offered by Baidu AI Cloud) will further accelerate the engineering of data-intensive systems, providing strong technical support for enterprises to reduce costs and improve efficiency.