Using Large Language Models to Build a Stock Backtesting Data System: A Practical Workflow
A reliable way to use large language models for stock backtesting is to break the project into small, verifiable tasks rather than asking a model to complete everything at once. This article explains a step-by-step workflow for confirming securities, designing a local database, testing data APIs, tracking progress, handling stalled tasks, and storing daily and intraday market data.
1. Why Large Language Model Tasks Should Be Decomposed
In stock trading and backtesting projects, many developers are tempted to give a large language model the entire specification and ask it to automate the process from start to finish. This may appear efficient during the prototyping stage, but it becomes unreliable when the project involves customized requirements, multiple dependent steps, and external data sources.
The model may silently change field definitions, omit securities, damage the database schema, or drift away from the original objective during a long-running task.
A more reliable approach is to design the overall workflow first, then divide it into small, verifiable steps. Each step should produce an intermediate artifact that can be inspected, such as a security list, a raw data table, or a test report. If a step fails, the rollback cost remains low and the source of the problem is easier to identify.
This article uses the process of retrieving daily and intraday stock data and storing it in a local database as an example.
2. Step One: Generate and Manually Confirm the Security List
The first step in building a backtesting system should not be writing a crawler or calling an API. First, extract the stock names and other securities referenced in the trading records and turn them into a clear, explicit list. Ask the model to output the list for manual review.
This step is valuable for several reasons:
- The security list is the input for all subsequent data retrieval. Incorrect codes, duplicates, or inconsistent names can contaminate the entire workflow.
- Manual verification requires little effort but can prevent the most common category of errors.
- Starting with a small task provides a quick way to check whether the model has correctly understood the context.
For example, the model can be asked to produce a structured list like this:
[{"ts_code": "600000.SH", "name": "Shanghai Pudong Development Bank"},{"ts_code": "000001.SZ", "name": "Ping An Bank"}]
Only proceed to data retrieval after the list has been confirmed. Avoid asking the model to retrieve data and modify the security list in the same step.
3. Step Two: Design a Standardized and Extensible Local Database
Before asking the model to retrieve data, define how the data should be stored. A typical backtesting data layer may include the following tables:
- Security master table: Stock code, name, exchange, listing status, and other basic information.
- Daily market data table: Date, open, high, low, close, volume, turnover, adjustment factor, and related fields.
- Intraday market data table: Trading date, timestamp, price, volume, and other intraday fields. Because this table is much larger than the daily data table, partitioning or separate tables may be necessary.
- Data retrieval job log table: The security, time range, API, status, and duration of each retrieval task, supporting retries and resumable execution.
The prompt should state these requirements explicitly. For example:
Build a stock backtesting data system. First, retrieve all daily and intraday data for the securities listed above. The data API documentation is available at a local path and contains the access token. Build the retrieval functionality based on the confirmed security list and store the data in a local database. The database design must be standardized and extensible, and the retrieval process must show visible progress.
Several engineering practices are important:
- Ask the model to generate the database creation scripts first. Review field types, primary keys, and indexes before executing them.
- Use a unique constraint based on the security and date for market data to prevent duplicate retrievals from creating inconsistent records.
- Because intraday data can be large, consider partitioning it by year or month.
- Do not hard-code sensitive tokens. Read them from environment variables or a configuration file.
4. Step Three: Make Progress Visible and Support Resumable Execution
Long-running tasks should not operate as black boxes. Ask the model to report progress during data retrieval, such as printing one log entry after each security or date range is completed:
[progress] 600000.SH daily data 2018-01-01 ~ 2024-12-31 completed, 1,698 records[progress] 000001.SZ intraday data completed, 23,104 records
This provides three major benefits:
- You can see what the model is doing at any time.
- You can intervene quickly if the task appears to be stuck.
- After a failure, the logs indicate where execution should resume.
When combined with a job log table, the system can skip successful tasks and retry failed ones. This prevents unnecessary repeated requests that could trigger rate limits on the external data service.
5. Handling Apparent Model Freezes
In practice, some model versions may produce no output for an extended period during a long task. This is commonly described as a stalled or frozen execution.
Typical responses include:
- Set a timeout for each task. Stop and restart the task manually if the timeout is exceeded.
- Break the long task into smaller units to reduce the execution time of each individual task.
- Check whether the issue is concentrated around a specific operation, such as parsing a very large document or retrieving data in a large loop. Then optimize the prompt or execute the operation in batches.
- Save existing intermediate results before restarting so the entire workflow does not need to begin again.
If the problem continues, record when it occurs in the task log. This helps determine whether the cause is an occasional issue with the model service or a problem with the task design.
6. Localize the API Documentation and Test Each Endpoint Separately
In financial data projects, a practical approach is to convert the data provider’s web-based API documentation into local Markdown files and provide them to the model for reference. This has several advantages:
- The model can consult the documentation repeatedly without depending on the stability of web-page retrieval.
- Configuration information, including access tokens, can be managed in one place.
- Different documentation versions can be compared more easily.
After localizing the documentation, require the model to create a separate small test for every required API. Test each interface independently and generate a test report containing:
- API name
- Input parameters
- Returned fields
- Whether the request succeeded
- Sample record count
This report has two purposes:
- It confirms which APIs are available before the project begins, preventing the discovery of an unavailable interface or insufficient permissions halfway through implementation.
- It serves as a factual data dictionary for later cleaning and backtesting logic.
This step reinforces the value of incremental execution: test the APIs first, then implement data retrieval, and only afterward write the results to the database. Do not ask the model to generate one large block of code that performs all three tasks at once.
7. Example Prompt Template
The following staged prompt can be used directly:
I want to build a stock backtesting analysis system. Current task: retrieve daily and intraday data for specified securities.Security list: see the confirmed list prepared above.API documentation: /path/to/data_api_doc.md (contains the access token; do not hard-code it).Storage requirements: local database with a standardized and extensible schema; separate tables for daily and intraday data; include a task log table.Execution requirements:1. Provide the table-creation SQL for my review first.2. Print progress for each security during data retrieval.3. Do not retrieve data that already exists.4. After completion, output record counts for each table.
8. Conclusion
The key to using large language models for data-intensive systems is not an elaborate prompt. It is an engineering process based on task decomposition and verification.
Confirm the security list manually before using it. Review the database schema before creating tables. Test APIs before integrating them. Keep progress visible throughout execution, and stop or retry promptly when problems occur.
A large language model should be treated as a highly capable executor that still needs clear boundaries and checkpoints—not as an unattended automation button. This approach preserves the model’s efficiency while producing a system that is more reliable and maintainable.
