Building a Stock Backtesting Data Pipeline Step by Step with LLMs
This article explains why large language models fail on data pipeline tasks not because of limited capability but because of how requirements are delivered, and shows a practical workflow: keep process design and acceptance with the human, and let the model handle only clearly scoped single steps. It walks through splitting data collection into four steps, designing an idempotent storage schema, building a collection layer with rate limiting, retries, and checkpoint resume, adding observability, handling model stalls, and running an acceptance checklist. Readers get concrete SQL, pseudocode, and prompt guidance they can apply to most data pipeline tasks regardless of the specific model or tool.
1. The Problem Isn’t Model Capability, It’s How Requirements Are Delivered
Many developers’ first instinct is to write the entire requirement in one shot and hand it to an AI coding tool to “finish in one go.” This works for boilerplate code, but on tasks involving external data APIs, local storage, and long-running collection jobs, it easily spins out of control: inconsistent field naming, silently swallowed exception branches, dirty data from repeated runs, and jobs that produce no output halfway through. The approach that actually stays stable is to keep the responsibility for “thinking the process through” on the human side, and let the model handle only clearly defined single-step implementation and verification.
A practical rule of thumb: can each step be manually verified within a few minutes? If not, the granularity is too coarse and needs to be broken down further.
2. Task Decomposition: Splitting “Pull Data” into Four Steps
- Confirm the instruments: First extract stock names and codes from existing trading records, and have a human verify them. This step costs almost nothing but prevents all downstream data from being built on the wrong instruments.
- Prepare the API and credentials: Gather the API documentation, authentication method, call quotas, and rate-limit rules into a local reference file that the tool can read.
- Design storage: Define the table schema and indexes first, then write the collection code. Reversing this order is the most common source of rework.
- Collect and validate: Pull daily and intraday data in batches, emit progress, and run an integrity check at the end.
3. Storage Layer: Standards and Extensibility First
The key design points are “separate metadata from market data, and model period and frequency explicitly”:
-- Instrument dimension table: adding fields does not affect historical dataCREATE TABLE instrument (symbol VARCHAR(16) PRIMARY KEY,name VARCHAR(64) NOT NULL,market VARCHAR(8) NOT NULL,list_date DATE,is_active BOOLEAN DEFAULT TRUE);-- Market data main table: a unique constraint on (instrument, freq, time) guarantees idempotencyCREATE TABLE market_bar (symbol VARCHAR(16) NOT NULL,freq VARCHAR(8) NOT NULL, -- 1d / 1m / 5mbar_time TIMESTAMP NOT NULL,open_px DECIMAL(18,4),high_px DECIMAL(18,4),low_px DECIMAL(18,4),close_px DECIMAL(18,4),volume BIGINT,adjust_type VARCHAR(8) DEFAULT 'none',src_updated_at TIMESTAMP,PRIMARY KEY (symbol, freq, bar_time, adjust_type));
The unique constraint, combined with an “update if exists” write semantic, makes jobs safe to re-run; src_updated_at is used for incremental detection; putting the adjustment type into the primary key prevents different adjustment conventions from overwriting each other. Partitioning or sharding strategies can wait until the data volume grows, but the primary key design must be right the first time.
4. Collection Layer: Rate Limiting, Retries, and Checkpoint Resume
for each symbol in symbols:cursor = load_checkpoint(symbol, freq) # checkpointwhile cursor < end_date:batch = fetch(symbol, freq, cursor, page_size)if batch is empty: breakupsert(batch) # idempotent writecursor = batch.max_bar_timesave_checkpoint(symbol, freq, cursor) # persist checkpointlog_progress(symbol, cursor, end_date) # progresssleep(rate_limit_interval) # proactive rate limiting
Three engineering constraints are worth emphasizing: proactive rate limiting beats passive retries; exponential backoff should be used only for retryable errors (timeouts, rate limits), while parameter errors must fail immediately; and the checkpoint write frequency determines the worst-case amount of duplicated work.
5. Process Observability: Making “What Is It Doing” Visible
The biggest experience problem with long-running jobs is the black box. The lowest-cost solution is structured progress logs containing the current instrument, the time range covered so far, completion percentage, throughput, failure count, and estimated time remaining, output to both the terminal and a local log file. If a cloud service is used to host the job, logs can be shipped to a logging service, with monitoring and alerting thresholds set for “no new records for a long time”—this kind of capability belongs to general cloud product categories and does not need to be tied to a specific vendor implementation.
6. Exception Handling: What to Do When the Model “Freezes”
Long periods of no response during interactive generation usually come from a stalled toolchain, overly long output, or a blocked environment. The actionable sequence is: first interrupt the current step rather than the entire session; confirm the checkpoint already persisted; re-initiate the same step from the checkpoint; and if the same prompt stalls twice in a row, narrow the scope of that step (for example, process only five instruments at a time). Making “interruptible and resumable” a hard requirement in both prompts and code means a stall is only a delay, not a loss.
7. Acceptance Checklist
- Instrument count and time range match the source, with no silent truncation;
- Trading days are aligned, and missing days have a recorded reason;
- Spot-check prices and volume for non-negativity and abnormal zero values;
- Adjustment conventions are consistent, and original-convention data is preserved when switching conventions;
- Record count is unchanged before and after a repeated run (idempotency verification);
- Failed instruments are summarized into a list that can be retried separately.
8. Prompt Template Essentials
Specify the inputs (instrument list, path to the API reference file), specify the outputs (schema script, collection script, log format), specify the constraints (rate limiting, idempotency, checkpoints, fail-fast on errors), and specify the acceptance method (produce a verification report). Writing these four things clearly makes the model’s output far more controllable than a single long requirement.
Conclusion: Large language models are well suited to “clearly bounded implementation,” while humans own “process design and acceptance.” Break down the steps, define the schema first, make it resumable, add progress, and enable verification—this sequence applies to the vast majority of data pipeline tasks, regardless of which model or tool you use.
