Building a Stock Market Data Pipeline with Large Language Models: A Step-by-Step Guide

    Learn how to use large language models as controlled, single-step implementation assistants when building a stock market data pipeline. This guide covers security selection, data-source abstraction, database design, progress monitoring, fault tolerance, resumable processing, and practical validation checks.

    1. Why One-Shot Delivery Requirements Often Get Out of Control

    When large language models are introduced into data engineering, the most common failure mode is not limited model capability. It is uncontrolled task scope. Developers often provide the background, objectives, constraints, and acceptance criteria all at once, expecting the model to deliver a complete, runnable system end to end.

    However, data pipeline tasks have three inherent characteristics:

    • Many external dependencies: APIs may enforce rate limits or change their fields.
    • Long-running state: Data collection may continue for tens of minutes or longer.
    • Strong verifiability: Row counts, date ranges, and data completeness can be checked objectively.

    These characteristics make data pipelines poorly suited to black-box, one-shot delivery.

    A more reliable approach is to use the following division of responsibility: the human designs the workflow and performs acceptance checks, while the model implements individual steps. Break the end-to-end objective into atomic steps with clearly defined inputs and outputs. Each deliverable should be easy for a person to review. Errors are then contained within a single step instead of contaminating every downstream stage.

    2. Step One: Extract and Confirm the Security List

    Every backtesting or market analysis workflow starts with a list of securities. Asking a model to extract stock names and symbols from existing trading records is a typical extraction-and-normalization task. It is also a low-cost way to evaluate model reliability.

    The prompt should require structured output rather than a natural-language explanation:

    1. Extract all securities from the following trading records and return a JSON array.
    2. Each item must contain the fields name, symbol, and market.
    3. Use null for any field that cannot be determined. Do not guess.

    The extracted results must then be reviewed manually. Pay particular attention to three types of issues:

    • Multiple representations of the same security that were not merged
    • A mismatch between the symbol and its market
    • Fields that the model “completed” even though they do not exist

    This step costs very little but can prevent invalid securities from being written to the database. Once dirty data has entered storage, cleanup is usually much more expensive than confirming the input beforehand.

    3. Step Two: Design an Abstraction for Data Ingestion

    Once the security list has been confirmed, the next step is data retrieval. The key decision is not to ask the model to generate a collection of scattered API calls. Instead, define a stable abstraction boundary first, then have the model implement the details.

    1. class MarketDataAdapter:
    2. """Unified data adapter that hides differences between data sources."""
    3. def fetch_daily(self, symbol: str, start: str, end: str) -> list[dict]: ...
    4. def fetch_intraday(self, symbol: str, trade_date: str) -> list[dict]: ...

    This approach provides three benefits:

    1. Credentials, rate limiting, and field mappings are consolidated in one place. If the data source changes, only the implementation class needs to be replaced.
    2. The higher-level retrieval and retry logic can be tested independently.
    3. The model only needs to implement one method at a time, making its output easier to control.

    The engineering design should include four basic capabilities:

    • A token bucket for rate limiting to avoid triggering API throttling
    • Exponential backoff retries for transient failures
    • A field allowlist mapping to prevent newly added upstream fields from polluting the table schema
    • Externalized credentials, with tokens loaded from environment variables or local configuration rather than written into source code or logs

    4. Database Design: Prioritize Normalization and Extensibility

    The storage design determines whether the system can evolve over time. The central principle is to separate the raw layer from the processed layer:

    1. CREATE TABLE daily_bar (
    2. symbol VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open_px DECIMAL(18,4) NOT NULL,
    5. high_px DECIMAL(18,4) NOT NULL,
    6. low_px DECIMAL(18,4) NOT NULL,
    7. close_px DECIMAL(18,4) NOT NULL,
    8. volume BIGINT,
    9. src_updated TIMESTAMP NOT NULL,
    10. PRIMARY KEY (symbol, trade_date)
    11. );

    Important considerations include:

    • The primary key is the business uniqueness key. Combined with INSERT ... ON CONFLICT DO UPDATE, it enables idempotent writes, so repeated retrievals do not create duplicate or inconsistent records.
    • Store raw values without transformation. Adjustments, missing-value filling, and similar processing should be handled in views or downstream jobs to preserve traceability.
    • Record the source update timestamp to evaluate data freshness and determine the starting point for incremental retrieval.
    • Intraday data can use a structurally similar table with an additional bar_time field. Partitioning by security or date helps prevent a single table from growing uncontrollably.

    5. Progress Observability: Make Long-Running Work Visible

    The biggest risk in a long-running task is waiting without knowing what is happening. Observability should have three layers:

    1. Task layer: A task table records the task_id, symbol, status, processed row count, total row count, start time, and end time. This makes it possible to query overall progress at any time.
    2. Logging layer: Structured logs report the current security, batch range, duration, and failure reason, making later troubleshooting easier.
    3. Interactive layer: The console prints a progress bar at a fixed refresh interval, for example:

      1. [=====> ] 62% symbol=xxx 1240/2000

    The pipeline should also support checkpoint-based resumption. At startup, read incomplete tasks from the task table and continue from the last successful position instead of restarting the entire process. This is one of the most effective ways to handle interruptions caused by timeouts.

    6. Reliability: Handling Unresponsive Processes and Apparent Hangs

    In practice, a process may appear to hang for a long time without producing output. Whether the root cause is on the model side or in the execution environment, the engineering response should be the same: do not wait indefinitely, and do not blindly restart the entire workload.

    • Set a hard timeout for each step, such as 120 seconds. Abort on timeout and retry using a backoff strategy, up to a defined maximum number of attempts.
    • Split large retrieval jobs into smaller batches, such as 20 securities per batch. A failed batch should not affect data that has already been completed.
    • Make all database writes idempotent so that interruption and rerunning are safe operations rather than sources of additional risk.
    • If retries continue to fail, mark the task as failed and skip it. At the end, output a consolidated failure list for manual review.

    7. Acceptance Checklist

    Before delivery, verify each of the following items:

    • The total number of securities matches the confirmed list.
    • The requested date range has no gaps. Use SQL to compare the minimum and maximum dates with the expected range.
    • No duplicate primary keys exist.
    • The proportion of null values remains within the defined threshold.
    • Running the pipeline a second time does not change the data volume, confirming idempotency.
    • Credentials do not appear in source code or logs.

    Only after all checks pass can the pipeline be considered usable.

    The proper role of a large language model in data engineering is that of an efficient single-step implementer, not an end-to-end decision-maker. When the workflow is designed clearly, boundaries are well defined, and acceptance criteria are measurable, model output becomes significantly more stable and engineering risk remains within a manageable scope.