Stock Data Backtesting System with AI Coding Assistants: A Staged Development Workflow
This article explains how to use AI coding assistants to build a stock data backtesting system through staged, verifiable tasks. It covers extracting and confirming instrument lists, defining collection jobs, designing normalized database tables, implementing idempotent and resumable collection, reporting actionable progress, handling tool timeouts, and applying security and data governance practices. The goal is to keep AI-generated code within clear boundaries and build an observable, reliable data pipeline before moving on to backtesting and analysis.
1. Why You Should Not Describe All Requirements at Once
When using large language models or AI coding tools to develop a system, many people try to put the business goal, technology choices, database design, API calls, and UI requirements into a single prompt and ask the tool to generate the complete project. This looks efficient, but it often causes several problems:
Unclear requirement boundaries
When requirements include data recognition, API calls, database design, task scheduling, and visualization at the same time, the model has to make decisions at multiple levels simultaneously. If one underlying assumption is wrong, subsequent code may be built on an incorrect foundation.Intermediate results are hard to verify
If the system executes the entire workflow directly, users often see results only at the end. If data is missing, stock names are recognized incorrectly, or field mappings are wrong, it is difficult to determine which step caused the problem.Automatically generated content can easily get out of control
For personalized tasks, the model may add features that were not explicitly requested, such as modifying the existing directory structure, replacing the database approach, or adding unconfirmed business logic. This can quickly increase project complexity.
A safer approach is to split the task into multiple stages, check the result after each stage, and then move to the next stage. For a data analysis system, a recommended workflow is “identify—confirm—design—collect—validate—analyze.”
2. Step 1: Extract the Instrument List from Trading Records
The foundation of a stock backtesting system is not the database. It is a reliable instrument list. If the original trading records contain information such as stock names, codes, buy/sell direction, execution prices, and dates, the first task should ask the AI tool to perform only “recognition and organization.” Do not start downloading data immediately.
The task can be divided into the following goals:
- Extract stock names from trading records;
- Standardize the format of stock names;
- Add securities codes where possible;
- Mark items that cannot be confirmed;
- Remove duplicate instruments;
- Output a structured list for manual review.
A recommended data structure looks like this:
[{"name": "Example Stock A","code": "000001","market": "SZ","confidence": 0.98,"source": "trading record row 12"}]
The confidence field is not intended to create false precision. It is used to indicate which results require priority manual review. For records with similar names, missing codes, or unclear market attribution, the pending-confirmation status must be preserved. The model should not guess on its own.
The Importance of Manual Confirmation
Before starting data collection, manually confirm the following:
- Whether the stock name matches the securities code;
- Whether there are securities with the same name or historical name changes;
- Whether the trading date falls within the valid trading period of the security;
- Whether delisted, suspended, or specially treated instruments should be included;
- Whether different markets and security types need to be distinguished.
The core principle at this stage is: let the model organize, and let humans confirm. The confirmed instrument list should be saved as an independent file, such as symbols.json, or as an instrument table in the database. It should become the single input source for subsequent tasks.
3. Step 2: Split Data Collection Requirements into Executable Tasks
After the instrument list is confirmed, ask the AI tool to build the data collection functionality. The prompt should not merely say “pull all data.” It should clearly define the task scope, data types, storage method, progress feedback, and error handling.
A relatively complete requirement can include the following:
- Use the confirmed instrument list as input;
- Collect historical daily data;
- Collect intraday data where supported by the data source;
- Save raw data to a local database;
- Record the collection status of each instrument;
- Display overall progress and per-instrument progress;
- Support retries after failure and resumable collection;
- Avoid duplicate inserts;
- Validate the format of returned fields;
- Write abnormal results to logs.
It is especially important to emphasize that “all data” is not a sufficiently clear technical requirement. During actual development, further specify:
- The historical start date and end date;
- The adjustment method for daily data;
- The time granularity of intraday data;
- Whether suspension dates are included;
- Whether raw responses are saved;
- Whether real-time progress is required;
- How to handle rate limiting from the data source.
If these details are not specified, the model may use default values, causing the results to differ from the actual research requirements.
4. Database Design: Prioritize Normalization and Extensibility
A stock data system should not simply store all fields in one large table. A more reasonable design usually includes an instrument table, daily quote table, intraday quote table, task table, and error log table.
1. Instrument Table
This table stores basic securities information:
CREATE TABLE instrument (id INTEGER PRIMARY KEY,code VARCHAR(32) NOT NULL,name VARCHAR(128) NOT NULL,market VARCHAR(16),status VARCHAR(16),created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL,UNIQUE(code, market));
The instrument table should not store only names and codes. It can also be extended with listing date, delisting date, security type, and other information as needed. Separating basic information from market data helps with future maintenance.
2. Daily Quote Table
CREATE TABLE daily_quote (instrument_id INTEGER NOT NULL,trade_date DATE NOT NULL,open_price DECIMAL(20,8),high_price DECIMAL(20,8),low_price DECIMAL(20,8),close_price DECIMAL(20,8),volume DECIMAL(24,8),amount DECIMAL(24,8),adjustment_type VARCHAR(32),source VARCHAR(64),PRIMARY KEY (instrument_id, trade_date));
The primary key should consist of “instrument plus trade date” to prevent duplicate inserts for the same instrument on the same day. For prices and volume, floating-point types are not recommended because precision errors can affect subsequent calculations.
3. Intraday Quote Table
Intraday data is usually much larger in volume, so the timestamp should be used as a core field:
CREATE TABLE intraday_quote (instrument_id INTEGER NOT NULL,event_time TIMESTAMP NOT NULL,price DECIMAL(20,8),volume DECIMAL(24,8),amount DECIMAL(24,8),interval_seconds INTEGER,source VARCHAR(64),PRIMARY KEY (instrument_id, event_time, interval_seconds));
For the intraday table, estimate the data scale in advance and create indexes based on query patterns. For example, a composite index on instrument_id + event_time can improve query efficiency for a specified instrument and time range.
4. Task Status Table
The task table supports resumable collection and progress display:
CREATE TABLE collect_task (task_id VARCHAR(64) PRIMARY KEY,instrument_id INTEGER NOT NULL,data_type VARCHAR(32) NOT NULL,start_date DATE,end_date DATE,status VARCHAR(16) NOT NULL,progress INTEGER DEFAULT 0,retry_count INTEGER DEFAULT 0,error_message TEXT,started_at TIMESTAMP,finished_at TIMESTAMP);
Status values can include pending, running, success, failed, and paused. This way, even if the program exits midway, it can continue processing unfinished parts based on task status.
5. The Collection Process Should Be Idempotent
One of the most important engineering capabilities of a data collection program is idempotency. This means that running the same task once or multiple times will not produce erroneous duplicates in the final result.
Implementing idempotency usually includes:
- Using unique constraints to prevent duplicate records;
- Using an insert-or-update strategy when writing;
- Checking the existing data range before each task execution;
- Filling only missing dates or missing time ranges;
- Recording the data source, collection time, and version information;
- Performing incremental retries for partially successful tasks.
For example, if daily data for a certain instrument has already been collected for a date range, running the task again should not download from the beginning and insert unconditionally. Instead, the program should first read the maximum date already present in the database, then determine the range that needs to be filled.
It is important to note that “having records” in the database does not necessarily mean “data is complete.” Therefore, completeness checks should also be performed, including:
- Whether dates are continuous;
- Whether open, high, low, and close prices satisfy basic relationships;
- Whether volume and amount contain abnormal negative values;
- Whether duplicate timestamps exist;
- Whether there are large numbers of null values;
- Whether the number of trading days is roughly consistent with expectations.
6. Progress Display Should Not Be Just a Percentage
When users ask to “see specific progress,” this should not be interpreted as simply outputting a constantly changing percentage. More valuable progress information should include at least:
- The total number of tasks;
- The number of completed tasks;
- The instrument currently being processed;
- The current data type;
- The number of collected data records;
- The number of successes, failures, and retries;
- The latest error message;
- The estimated remaining task volume.
An example log can be designed as follows:
[12/50] Instrument: Example Stock AData type: DailyTime range: 2018-01-01 to 2024-12-31Records written: 1680Status: SuccessFailed tasks: 1Retry count: 2
If a graphical interface is used, tasks can be displayed as a list. If a command-line interface is used, logs should not refresh excessively, so that critical error information is not overwritten. In either case, it is recommended to also write to a persistent log file for later troubleshooting.
7. Handling AI Tool “Hangs” or Long Non-Responses
In practice, when using AI coding tools, it is not uncommon to encounter long periods without output, stalled tasks, or unclear execution states. At this point, do not wait blindly or rerun the entire task directly.
The following approaches can be used:
1. Set Stage-Based Checkpoints
Save results after each stage, for example:
- Save the list after instrument recognition is complete;
- Save migration records after database initialization is complete;
- Update task status after data collection for each instrument is complete;
- Commit transactions after each batch of data is written.
2. Narrow the Execution Scope
First ask the tool to process only one instrument, one day, or one month of data. Verify the API fields and database write logic. After confirming correctness, expand the scope.
3. Add Timeouts and Heartbeats
Collection tasks should set request timeouts, retry counts, and heartbeat logs. If no response is received within a certain period, mark the task as retryable rather than waiting indefinitely.
4. Separate Code Generation from Code Execution
Ask the AI tool to generate the plan and code first, have the developer review it, and then execute it separately. This prevents the model from triggering large-scale data requests directly during code generation and makes it easier to locate problems.
8. Security and Data Governance Requirements
If API credentials are stored in local documents, they should not be hard-coded into source code, logs, or version control. Safer approaches include:
- Using environment variables or local configuration files;
- Adding configuration files to ignore rules;
- Masking credentials in logs;
- Granting only the permissions necessary for the collection program;
- Validating fields in external responses;
- Backing up the database and regularly verifying the recovery process.
In addition, financial data analysis systems should clearly define data usage. Historical market data can be used for research and backtesting, but backtest results do not equal future returns. Missing data, incorrect adjustment handling, ignored trading costs, and unreasonable slippage settings can all cause significant deviations.
9. Recommended End-to-End Development Order
Overall, a more robust development process can be divided into nine stages:
- Read trading records;
- Extract and normalize instruments;
- Manually review the instrument list;
- Design the database schema;
- Collect data for only one instrument for validation;
- Add batch tasks and resumable collection;
- Add progress display and logging;
- Run data completeness checks;
- Proceed to backtesting, statistics, and visualization analysis.
The advantage of this approach is that every step is verifiable, rollback-friendly, and reusable. AI tools are well suited for code generation, field mapping, test case writing, and exception analysis, but key business rules, data definitions, and final results should still be confirmed by developers.
In general, when building a stock data backtesting system, what matters is not how much code an AI tool can generate at once. What matters is whether you can establish clear task boundaries, a reliable data model, and an observable execution process. By breaking complex requirements into small steps and adding manual confirmation and automated validation at each step, you can move AI coding from “rapid code generation” to “reliable completion of engineering tasks.”
