Building LLM-Driven Quantitative Data Pipelines: A Practical Guide

    This article presents a practical workflow for building quantitative data pipelines with large language models (LLMs). Instead of handing a full specification to a model in one shot, the approach splits the work into independently verifiable steps: symbol extraction and human confirmation, data source prioritization with credential safety, normalized and extensible storage design with idempotent writes, structured progress logging, timeout and resume handling, and automated data quality checks. Each stage includes concrete examples and common pitfalls, offering a reusable engineering pattern for market, financial, and alternative data ingestion.

    1. The Starting Problem: Why “One-Shot Requirements” Get Out of Control

    In day-to-day development, many people hand a complete requirement to an LLM in a single prompt and expect end-to-end delivery. This can work for small scripts, but once a task involves external data APIs, persistent storage, long-running orchestration, and state management, the failure rate rises sharply. There are three root causes:

    1. Context overload: The requirement mixes business goals, data fields, storage structures, error handling, and presentation needs. A model cannot satisfy all of these constraints in a single generation.
    2. No intermediate checkpoints: Generated output goes straight into production, so there is no chance to correct course at critical points. Errors propagate downstream and get amplified.
    3. Invisible state: Long-running tasks lack progress feedback. When something breaks, it is hard to tell whether the cause is API rate limiting, missing fields, or a failed write.

    A more reliable approach is to split responsibilities: humans own process design and acceptance criteria, while the model owns single-point implementation. Break the “big task” into “small tasks that can be verified independently,” and make every step produce a checkable artifact.

    2. Methodology: A Process-First, Stepwise Collaboration Model

    It helps to fix the collaboration into four stages that form a closed loop.

    • Stage 1: Goal clarification. Define the business objective (building a buy/sell backtesting analysis system), the data scope (symbol list, daily and intraday bars), and non-functional requirements (extensibility, observability, recoverability).
    • Stage 2: Process decomposition. Break the goal into: confirm the symbol list → verify data source capabilities → design the storage schema → implement the fetch tasks → add progress and logging → validate and reconcile.
    • Stage 3: Single-step generation with human confirmation. Give the model one clear responsibility per step, review the output manually, then move on.
    • Stage 4: Regression and consolidation. Turn validated prompts, scripts, and table schemas into templates that become reusable assets.

    A simplified orchestration sketch is shown below. The point is not the syntax but the clear stage boundaries and per-step acceptance:

    1. steps = [
    2. ("extract_symbols", "Extract and deduplicate stock names from trade records"),
    3. ("confirm_symbols", "Human confirmation of the symbol list"),
    4. ("design_schema", "Output DDL and index notes"),
    5. ("build_fetcher", "Implement batched fetching with rate limiting"),
    6. ("add_progress", "Output progress and failure retry information"),
    7. ("validate", "Validate row counts, date ranges, and nulls"),
    8. ]
    9. for name, goal in steps:
    10. artifact = llm.generate(goal) # single-point generation
    11. review(artifact) # human confirmation
    12. run(artifact) # execute and observe

    3. First Step in Practice: Symbol Extraction and Human Confirmation

    The first task should be as simple and verifiable as possible, for example “extract the stock names involved in existing trade records and deduplicate them.” The value of this step is establishing trust and a baseline: the output is a finite set that can be checked by eye.

    Practical points:

    • Ask the model to output both the “result” and the “evidence,” so the source rows can be traced;
    • Normalize names (full-width vs. half-width characters, spaces, alias unification);
    • Freeze the list as a configuration file after human confirmation, and have later steps read only from that list to avoid repeated changes.

    4. Data Source Strategy: API Priority and Credential Safety

    When local data API access is available, declare the priority explicitly to reduce the uncertainty introduced by the model “improvising.” Credential safety must also be emphasized:

    • Never put credentials in prompts; use environment variables or a local config file, and exclude it from version control;
    • Define the strategy “prefer the authorized API, fall back only on failure”;
    • Require rate limiting and retries to avoid triggering throttling.

    Configuration example:

    1. [data_source]
    2. priority = local_api, fallback_public
    3. rate_limit_per_min = 300
    4. retry = 3
    5. credential_env = DATA_API_TOKEN

    5. Storage Design: Standards and Extensibility Are Hard Requirements

    Database design cannot be “get it running first and fix it later,” because migration costs become extremely high later. Recommended principles:

    1. Separate metadata from market data: Decouple the symbol table, data source table, fetch task table, and market data table.
    2. Unified primary key and unique constraint: Use “symbol + trade time + period” as the unique key, which naturally supports idempotent writes.
    3. Reserve partitioning or sharding: Intraday data is large, so partitioning by date or month is better for queries and archiving.
    4. Extensible fields: Reserve fields such as adjustment factor, currency, and data version to avoid frequent schema changes.

    Reference table definition:

    1. CREATE TABLE market_bar (
    2. symbol VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. period VARCHAR(8) NOT NULL, -- 1d / 1m
    5. open_px DECIMAL(18,4),
    6. high_px DECIMAL(18,4),
    7. low_px DECIMAL(18,4),
    8. close_px DECIMAL(18,4),
    9. volume BIGINT,
    10. adjust_factor DECIMAL(18,6) DEFAULT 1,
    11. data_version VARCHAR(16) DEFAULT 'v1',
    12. PRIMARY KEY (symbol, trade_date, period)
    13. );

    Writes use an idempotent “update if exists” strategy so tasks can be safely re-run:

    1. INSERT INTO market_bar (symbol, trade_date, period, close_px)
    2. VALUES ('600000', '2024-01-02', '1d', 10.25)
    3. ON CONFLICT (symbol, trade_date, period) DO UPDATE
    4. SET close_px = EXCLUDED.close_px;

    6. Progress Observability: Make Execution Visible

    Long-running tasks are worst as black boxes. Require feedback at three levels:

    • Task level: total symbols, completed count, percentage, estimated time remaining;
    • Data level: current symbol, current range, rows written in this batch;
    • Exception level: failed symbols, error type, retry count, whether skipped.

    Logs should be structured output to make later aggregation and alerting easier:

    1. {"ts":"2024-01-02T10:00:00","level":"INFO","symbol":"600000","done":12,"total":50,"rows":720}

    7. Exceptions and Recovery: Hangs, Timeouts, and Resume

    Long periods without a response are common in practice. Response strategies should be built into the process rather than handled ad hoc:

    • Timeout and heartbeat: Set a timeout for each request; if there is no output for a long time, actively abort and restart that batch;
    • Resume from checkpoint: Use the task table to record each symbol’s fetch range and status, so a restart only fills in the missing parts;
    • Idempotent writes: Combined with the unique key, re-runs produce no duplicate data;
    • Failure isolation: A single symbol failure does not affect the whole run; collect the failure list and handle it together at the end.

    8. Quality Validation: The Last Gate for Data Usability

    Completing the fetch does not mean the data is usable. Automated validation must run:

    • Completeness: Do row counts match the trading calendar expectation, and are entire segments missing?
    • Consistency: The high price is not lower than the low price, and the close falls within the range;
    • Timeliness: Does the latest data date cover the end of the target range?
    • Reconciliation: Sample and compare against source data; any discrepancy is zero-tolerance.

    Validation results should be persisted as a separate report and used as an admission condition before backtesting.

    9. Common Pitfalls and Improvements

    • Pitfall 1: Trying to generate a complete system in one shot. Switch to “small steps, fast iterations, verify each step.”
    • Pitfall 2: Hard-coding credentials in prompts or code. Switch to environment variable injection and include them in secret management.
    • Pitfall 3: Writing business logic before storage design. Define the schema and unique keys first, then write the fetch logic.
    • Pitfall 4: Looking only at results, not the process. Add structured logs and progress metrics; problem localization becomes noticeably faster.

    10. Conclusion

    LLMs are good at implementing local logic; humans are good at defining processes and standards. Splitting a quantitative data pipeline into a chain of extract → confirm → design → implement → observe → validate, with a clear artifact and acceptance criterion at every step, keeps development fast while holding the risk of losing control within acceptable bounds. This method does not depend on any specific tool or platform and can be carried over as a general engineering pattern to market data, financial data, alternative data, and other data ingestion scenarios.