Building a Quantitative Data Pipeline with LLMs: A Practical Guide
This article presents a practical approach to building a local market data pipeline with large language models. Instead of handing a complex requirement to the model all at once, it keeps decision-making with the developer and delegates execution to the model through narrow interfaces and short, rollback-friendly steps. It covers a five-layer architecture, symbol list confirmation, prompt constraints for data fetching, extensible storage design, progress observability, exception and idempotency handling, and automated data quality checks. The workflow shows how to combine LLM generation speed with the reliability standards of data engineering, and can be applied to adjacent scenarios such as fund holdings analysis and risk metric calculation.
1. Why “One-Shot Requirements” Get Out of Control
In real data engineering work, handing a complete, complex requirement to a large language model and asking it to produce code end to end rarely yields stable results. The problem is not model capability but task coupling: authentication methods, field definitions, adjustment handling, storage structure, incremental strategies, and retry logic are all interconnected. Any wrong assumption in one area gets amplified in the final output and is hard to trace.
A more reliable approach is to keep decision-making with the developer and delegate execution to the model. The developer defines the workflow and acceptance criteria; the model produces runnable, inspectable code at each step. This “narrow interface, short chain, rollback-friendly” collaboration model significantly reduces the risk of losing control.
2. Overall Architecture: Layering Makes Every Step Verifiable
A usable local market data pipeline can be split into five layers:
- Ingestion layer: wraps the market data service uniformly and hides differences between specific interfaces;
- Parsing layer: normalizes responses into a unified data model;
- Storage layer: persists data partitioned by symbol, period, and time;
- Scheduling layer: handles task orchestration, resumable execution, and rate limiting;
- Observability layer: outputs progress, logs, and data quality reports.
The key benefit of layering is replaceability. When the data source changes its rate-limiting policy or fields, only the ingestion and parsing layers need changes; storage and scheduling remain unaffected.
3. Step One: Confirm the Symbol List Only
The first step should not include any fetching logic. Instead, have the model extract stock names and codes from existing trade records, output them as a structured list, and then review them manually. This keeps dirty input out at the very front: mismatched names and codes, multiple spellings of the same symbol, and delisted or renamed symbols all create hidden costs during later data alignment.
Ask the model to output confidence and source fields as well, so suspicious entries are easy to locate:
symbol, name, source, confidence, need_manual_review600xxx, Example Co., trade_record, 0.98, false
4. Step Two: Generate the Data Fetching Module with Natural Language Constraints
Once the symbol list is confirmed, move on to data fetching. The prompt should include five types of constraints: data scope, interface priority, where authentication information comes from, storage target, and progress output requirements. Example:
Based on the confirmed symbol list, build a market data fetching module:1) Prefer the locally configured market data service, then fall back to a backup public data source;2) Read authentication information from the local configuration file; never hardcode it into the code;3) Fetch daily and intraday data; daily data must include an adjustment toggle;4) Write data into the local database with a well-structured, extensible schema;5) Output real-time progress and failure details while running.
One important engineering principle here: no credential should ever appear in source code or prompt echoes. Inject them through environment variables or a local configuration file, and mask them in logs.
5. Storage Design: What “Well-Structured” and “Extensible” Actually Mean
“Well-structured” and “extensible” are not slogans; they can be turned into concrete conventions:
- Unified primary key: symbol + period + timestamp, naturally idempotent, so repeated writes produce no dirty data;
- Partitioning strategy: partition by time range to make archiving and hot/cold separation of historical data easy;
- Metadata table: record each symbol’s fetched range, last update time, and failure count;
- Separate raw and cleaned layers: keep raw responses for traceability, and let cleaned data be used directly for backtesting.
Example schema:
CREATE TABLE daily_bar (symbol VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,open DECIMAL(18,4),high DECIMAL(18,4),low DECIMAL(18,4),close DECIMAL(18,4),volume BIGINT,adjust_flag SMALLINT DEFAULT 0,PRIMARY KEY (symbol, trade_date, adjust_flag));CREATE TABLE sync_state (symbol VARCHAR(16) PRIMARY KEY,start_date DATE,end_date DATE,last_sync_at TIMESTAMP,fail_count INT DEFAULT 0);
6. Progress Observability: Always Show What It Is Doing
Long-running tasks are worst as black boxes. Ask the model to output three types of information: an overall progress bar, the symbol currently being processed, and failure and retry details. For a command-line program, use standard output with single-line refresh; for a service, expose a lightweight status endpoint for the frontend to poll.
def report(done, total, symbol, failed):pct = done / total * 100 if total else 0print(f"\rProgress {pct:5.1f}% | Current {symbol} | Failed {len(failed)}", end="")
Also write structured logs to a local log file, making it easy to compute success rates and average duration afterward.
7. Exception Handling: Appearing Frozen, Repeated Runs, and Idempotency
In practice, a process often produces no output for a long time. This is usually not the model or program “freezing” but network waiting, interface rate limiting, or an unflushed buffer. Recommended engineering practices:
- Set connection and read timeouts for each request, with exponential backoff retries;
- Use unbuffered output or explicit flushing so progress does not “look stuck”;
- Add a task-level watchdog that actively interrupts and saves a checkpoint when there is no progress beyond a threshold;
- Rely on the database unique key for idempotency, so rerunning after an interruption does not double-count.
When resuming after an interruption, do not paste the entire context again. Provide the “completed range + remaining range” so the model only fills the gap, saving time and reducing ambiguity.
8. Data Quality Checks: The Last Gate of the Pipeline
Finishing the fetch does not mean the data is usable. Run four types of checks automatically: time continuity (missing trading days), price validity (high/low range, zero values), abnormal volume, and adjustment consistency. Write the results into a quality report, and automatically put symbols that fail into a refetch queue.
9. Methodology: A Reusable Collaboration Pattern
Abstracting the above process yields a general pattern: define the data contract first, split it into the smallest verifiable steps, produce inspectable intermediate artifacts at each step, confirm at key points manually, and close the loop with automated checks. The large language model acts as an efficient implementer, while workflow design and acceptance criteria stay with the developer. This division keeps the speed advantage of generative tools while holding the reliability baseline of data engineering, and transfers directly to adjacent scenarios such as fund holdings analysis and risk metric calculation.
