Building Quant Data Pipelines with LLMs: A Practical Guide

    This article presents a practical approach to building quantitative data pipelines with large language models. Instead of handing a full requirement to the model in one shot, it breaks the work into verifiable stages, uses explicit prompts to lock down constraints, and treats execution observability as a requirement. It covers task decomposition for a backtesting data workflow, prompt structure, database schema design for idempotency and extensibility, progress logging and hang recovery, common failure patterns, and a step-by-step rollout plan. Readers will learn how to turn long-chain data engineering from a gamble into a repeatable, verifiable, and maintainable practice.

    1. Why “One Big Prompt” Tends to Go Off the Rails

    In day-to-day development, many people prefer to hand a complete requirement to a large language model in a single message and expect an end-to-end result. This can produce a working prototype quickly, but the problems surface fast once the task becomes a long-chain workflow such as a data pipeline or a backtesting system: inconsistent field definitions, unhandled edge cases, write logic that does not match the table schema, and an execution process that stays invisible. The final output then becomes hard to accept or verify.

    A more reliable approach is to split the task into workflow nodes, have a human confirm the key intermediate results, and let the model implement one node at a time. The core principle is: the model generates candidate implementations, the human confirms semantics and definitions, and the system provides observable execution feedback.

    2. Task Decomposition: Breaking a Backtesting System into Verifiable Steps

    Take building a stock trading backtesting and analysis system as an example. The first step should not be writing the backtesting engine, but completing the data foundation:

    1. Instrument confirmation: extract stock names and codes from existing trade records and have a human review them, avoiding instrument pollution caused by aliases, delistings, or code changes.
    2. Data source and interface confirmation: decide which market data interface to use, which fields are required, and whether the frequency is daily or intraday.
    3. Fetch task generation: batch-fetch data for the instrument list, with support for resumable transfer and rate limiting.
    4. Storage design: define the table schema first, then write the write logic, ensuring standards compliance and extensibility.
    5. Progress observability: output the current instrument, success/failure counts, and remaining estimates.
    6. Quality checks: sample comparison, missing trading day detection, and duplicate primary key detection.

    The value of this decomposition is that every step has a clear acceptance artifact, so deviations in model output are caught immediately rather than all at once in the final stage.

    3. Prompt Design: Write Constraints into the Instruction, Not into Assumptions

    An executable prompt should contain at least five types of information: goal, input, constraints, output, and acceptance criteria. An example:

    1. Goal: Build market data fetching and storage functionality
    2. Input: instrument list file, interface documentation path (with access credentials)
    3. Constraints:
    4. 1) Use only the interfaces and fields declared in the documentation; do not invent parameters
    5. 2) Provide the table creation statements before writing the write code
    6. 3) Print progress in real time during fetching: current instrument/success count/failure count/elapsed time
    7. 4) Retry on failure and log the reason; do not skip silently
    8. Output: table creation script, fetching script, run instructions
    9. Acceptance: run a trial with 3 instruments and show the table schema and progress logs

    The key is to spell out what must not be done. Models tend by default to produce code that looks complete but lacks exception handling, and explicit constraints significantly reduce rework.

    4. Data Layer Design: Standards and Extensibility First

    A few general principles are recommended for storage design:

    • Primary key uniqueness: use “instrument code + timestamp + period” as a composite unique key, which is naturally idempotent, so repeated fetches do not produce dirty data.
    • Partitioning and indexing: partition by time range and index by instrument and time, balancing writes and queries.
    • Metadata tables: maintain separate instrument, fetch task, and fetch log tables that record status and failure reasons, making reruns easier.
    • Field types: use high-precision numeric types for prices to avoid floating-point errors; use integers or high-precision numerics for volume.
    • Separation of raw and processed layers: land raw market data first, then perform adjustment, alignment, and factor calculation, avoiding irreversible data overwrites.

    Illustrative table creation logic:

    1. CREATE TABLE daily_bar (
    2. symbol VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. period VARCHAR(8) NOT NULL DEFAULT '1d',
    5. open DECIMAL(18,4),
    6. high DECIMAL(18,4),
    7. low DECIMAL(18,4),
    8. close DECIMAL(18,4),
    9. volume BIGINT,
    10. PRIMARY KEY (symbol, trade_date, period)
    11. );

    5. Execution Observability: Progress, Logs, and Hang Handling

    Long-running tasks are most feared for “no movement for hours.” In engineering terms, observability should be treated as a requirement rather than an add-on:

    • Structured logs: each log entry includes the task ID, current instrument, completed/total, and failure reason.
    • Heartbeat output: print a heartbeat periodically even when no data is returned, distinguishing “slow” from “stuck.”
    • Timeout and retry: set a timeout threshold per instrument, interrupt on timeout and move to the next instrument to avoid blocking the whole run.
    • Manual takeover: when there is a long period of no response, pause first, keep the completed state, and resume from the checkpoint instead of starting over.

    Pseudocode example:

    1. for i, symbol in enumerate(symbols, 1):
    2. log(f"[{i}/{len(symbols)}] {symbol} start")
    3. try:
    4. df = fetch_with_timeout(symbol, timeout=30, retries=3)
    5. upsert(df)
    6. log(f"[{i}/{len(symbols)}] {symbol} ok rows={len(df)}")
    7. except Exception as e:
    8. log(f"[{i}/{len(symbols)}] {symbol} failed: {e}")

    6. Common Failure Patterns and How to Avoid Them

    • Fabricated fields: the model may generate parameters that do not exist in the documentation. The workaround is to require it to restate the interface field list before writing code.
    • Silently swallowed exceptions: empty implementations or pass statements that skip errors. The workaround is to enforce that failures must be written to the log table.
    • Non-extensible structure: cramming all fields into one wide table. The workaround is to normalize the raw layer and expand the processed layer as needed.
    • No idempotency design: repeated runs produce duplicate data. The workaround is a unique key plus “update if exists.”
    • Invisible progress: only outputting a summary at the end. The workaround is to write progress printing into the acceptance criteria.

    7. Rollout Recommendations and Summary

    Treating the large language model as an “implementation accelerator” rather than a “requirement replacement” is the core of this method. The recommended rollout order is: first confirm the instruments and field definitions, then define the table schema, then run a small-sample trial and observe the logs, and finally gradually open up full fetching and incremental updates. Data quality checks should be kept as an independent, long-term stage, covering three types of checks: missing trading days, abnormal prices, and duplicate primary keys.

    When the workflow is clearly decomposed, the constraints are written down, and execution is observable, the stability of model-generated code improves markedly, and long-chain data engineering shifts from “leaving it to luck” to a standardized practice that is repeatable, verifiable, and maintainable.