Building LLM-Driven Quantitative Data Pipelines: A Step-by-Step Practice Guide

    This article presents a practical, step-by-step framework for building quantitative data pipelines with LLM assistance, using the preparation of daily and intraday stock data for backtesting as the example. It explains why one-shot requirements tend to fail, how to split responsibilities across five architectural layers, and how to deliver each layer incrementally. Readers will find guidance on scoping model tasks to extraction and confirmation, probing data interfaces before implementation, designing normalized and extensible database schemas, building observable and fault-tolerant collection jobs, and running a data quality checklist. The approach keeps engineering output controllable, reproducible, and extensible even when model capability or stability varies.

    1. Background: Why a “One-Sentence Requirement” Goes Off the Rails

    When using LLMs for engineering work, the most common anti-pattern is dumping the entire requirement set at once and expecting a working system in a single pass. In practice, the result is usually a messy directory structure, drifting dependency versions, missing error handling, and irregular data persistence. The rework cost ends up far higher than starting from a clean design.

    A more reliable approach is to separate intent from steps: humans define the workflow, boundaries, and acceptance criteria, while the model produces verifiable code within each individual step. The example below, preparing daily and intraday data for stock buy/sell backtesting, lays out a practical step-by-step framework. Note that the data services and AI coding tools mentioned here are described in terms of general capabilities and do not refer to any specific vendor product.

    2. Overall Architecture: Splitting Responsibilities Across Five Layers

    1. Symbol management layer: maintains metadata such as stock codes, listing status, adjustment methods, and the trading calendar.
    2. Collection adapter layer: wraps the differences between data sources behind a unified interface, hiding field and rate-limit variations.
    3. Storage layer: a structured, extensible local database that separates facts from dimensions.
    4. Scheduling and observability layer: task orchestration, resume-from-checkpoint, real-time progress, and logs.
    5. Quality validation layer: completeness, consistency, outlier detection, and collection reports.

    When delivering incrementally, each layer is shipped and accepted on its own, avoiding the coupling and loss of control that come from generating everything at once.

    3. Step 1: Have the Model Do Only “Extraction and Confirmation”

    The first task should deliberately narrow the scope, for example extracting only the stock names and codes involved from existing trading records, with a human performing a second confirmation. The value of this step is not the output itself, but calibrating how accurately the model understands the context.

    A recommended prompt structure has four parts: role and goal, input location, output format, and prohibitions.

    1. Goal: Extract all symbols from the attached trade details
    2. Input: /data/records/trades.csv
    3. Output: code,name,first_seen_date, deduplicated and sorted by code
    4. Constraints: Do not infer missing fields, do not access the network, do not modify the original file

    4. Step 2: Probe Interface Availability First

    Before formal collection, run an “interface survey.” Hand the data service documentation to the model, have it fetch the content into local structured notes, then generate an independent test for each candidate interface and output a report on availability and field descriptions. The benefit is moving uncertainty forward, so you don’t discover halfway through the main workflow that an interface is unavailable or lacks sufficient permissions.

    Suggested fields for the test report:

    Interface purpose Available Permission/credit requirement Key parameters Returned fields Rate-limit behavior Notes
    Daily quotes Yes Basic permission required Code, range, adjustment Open/high/low/close, volume, amount Minute-level throttling Adjustment must be specified explicitly
    Intraday quotes Partially Higher permission required Code, date Time, price, volume Strict throttling Limited historical depth

    For unavailable interfaces, fall back to a backup source uniformly, and declare the priority explicitly in the configuration.

    5. Step 3: Design Schemas That Are Structured and Extensible

    A “dimension-fact” separation is recommended, avoiding the practice of stuffing changing values such as adjustment factors and name changes into the main table.

    1. CREATE TABLE dim_symbol (
    2. symbol VARCHAR(16) PRIMARY KEY,
    3. name VARCHAR(64),
    4. list_date DATE,
    5. delist_date DATE,
    6. updated_at TIMESTAMP
    7. );
    8. CREATE TABLE fact_daily (
    9. symbol VARCHAR(16),
    10. trade_date DATE,
    11. adj_type VARCHAR(8), -- none/qfq/hfq
    12. open NUMERIC(18,4), high NUMERIC(18,4),
    13. low NUMERIC(18,4), close NUMERIC(18,4),
    14. volume BIGINT, amount NUMERIC(20,2),
    15. PRIMARY KEY (symbol, trade_date, adj_type)
    16. ) PARTITION BY RANGE (trade_date);
    17. CREATE TABLE fact_intraday (
    18. symbol VARCHAR(16), trade_date DATE, ts TIMESTAMP,
    19. price NUMERIC(18,4), volume BIGINT,
    20. PRIMARY KEY (symbol, ts)
    21. );

    Key points: the primary key is the idempotency key, so repeated runs produce no dirty data; partitioning by date supports hot/cold separation and batch cleanup; monetary values use high-precision types to avoid floating-point error accumulating into backtest returns.

    6. Step 4: Make Progress Observable and Design for Fault Tolerance

    Collection is a long-running task, so users must always know “where it is, how much is left, and how many failed.”

    1. def pull(symbol, start, end, sink, state):
    2. done = state.load(symbol) # resume from checkpoint
    3. for d in trading_days(start, end):
    4. if d <= done:
    5. continue
    6. for attempt in range(3):
    7. try:
    8. df = fetch_daily(symbol, d)
    9. sink.upsert(df) # idempotent write
    10. state.mark(symbol, d)
    11. progress.tick(symbol, len(df))
    12. break
    13. except RateLimited:
    14. sleep(backoff(attempt)) # exponential backoff
    15. except Exception as e:
    16. log.error(symbol, d, e)
    17. break # log and continue, do not abort the whole run

    Supporting mechanisms include token-bucket rate limiting, exponential backoff retries, a persisted failure list, and heartbeat logs. If a run appears to hang with no output for a long time, a heartbeat timeout should trigger termination of the current batch and a restart from the most recent checkpoint, rather than waiting indefinitely.

    7. Step 5: Data Quality Validation Checklist

    • Completeness: compare the number of trading days covered per symbol against the trading calendar, and alert when the missing rate exceeds a threshold.
    • Consistency: the high price must not be lower than the lowest of the open and close; volume and amount should be of matching magnitude.
    • Adjustment correctness: sample several ex-dividend dates and verify that the price jumps before and after match the adjustment factors.
    • Duplicates and drift: primary key conflicts should be zero; timestamps must not move backward.
    • Sampled replay: randomly pick several symbols and cross-check them against a backup source.

    8. Abstracted Lessons from Collaboration

    1. Define the process first, then let the model act: humans provide the steps and acceptance criteria, and the model implements within narrow boundaries.
    2. Commit in small steps and accept incrementally: each step can run and roll back independently.
    3. Move uncertainty forward: probe interfaces and permissions before writing the main workflow.
    4. Idempotency and checkpoints are the baseline: any re-runnable collection task should be safely re-entrant.
    5. Observability is peace of mind: progress, logs, and the failure list are all indispensable.

    Following this method, even if the underlying model’s capability or stability fluctuates, the engineering output remains controllable, reproducible, and extensible, providing a trustworthy data foundation for subsequent backtesting and strategy research.