Building a Quant Data Pipeline with LLMs: A Practical Step-by-Step Approach

    This article explains how to build a reliable stock backtesting data pipeline by collaborating with large language models in small, verifiable steps instead of sending one vague prompt. It covers a five-layer architecture, an idempotent database schema with example DDL and UPSERT statements, prompt structures with clear acceptance criteria, progress observability techniques, and engineering fixes for rate limits, data quality, incremental sync, and credential security.

    1. The Problem: Why a One-Sentence Request Rarely Produces a Reliable System

    When engineers delegate work to a large language model, the most common failure mode is not limited model capability but poor input framing. Compressing every requirement into a single natural-language paragraph forces the model to decide the symbol universe, data sources, storage layout, progress reporting, and error handling all in one generation. With that many variables in play, the output tends to drift from expectations: missing fields, messy directory structures, and scripts that cannot be re-run safely.

    A more dependable approach is to break the task into small, verifiable steps. Each step has a defined input, a defined artifact, and explicit acceptance criteria. The developer keeps decision authority; the model handles implementation and boilerplate code.

    This article uses the first step of building a stock backtesting and analysis system—landing market data in a database—to show how that collaboration works in practice.

    2. Overall Architecture: Layering So Future Extensions Do Not Require Rework

    A backtesting data pipeline meant to evolve should be split into five layers:

    1. Symbol management: maintains metadata such as ticker codes, listing status, and industry classification.
    2. Data ingestion: wraps external market data interfaces and handles authentication, rate limiting, and retries.
    3. Cleaning and validation: handles adjustment methods, trading calendar alignment, and missing or anomalous values.
    4. Storage: local database with tables split by subject, keeping daily bars separate from intraday bars.
    5. Scheduling and observability: records task progress, failure reasons, and elapsed-time metrics.

    The main payoff of layering is isolation: swapping a data source touches only the ingestion layer, and backtesting strategies depend solely on storage-layer views without needing to know about upstream changes.

    3. Database Design: Concrete Rules for a Schema That Scales

    Three principles are worth following: primary keys that are unique and support idempotency, a time dimension that can be partitioned, and raw data kept separate from processed data. Illustrative DDL:

    1. -- Symbol metadata
    2. CREATE TABLE symbol_meta (
    3. symbol VARCHAR(16) PRIMARY KEY,
    4. name VARCHAR(64),
    5. industry VARCHAR(64),
    6. list_status VARCHAR(16),
    7. updated_at TIMESTAMP
    8. );
    9. -- Daily bars, partitioned by year for easier archiving
    10. CREATE TABLE daily_bar (
    11. symbol VARCHAR(16) NOT NULL,
    12. trade_date DATE NOT NULL,
    13. open DECIMAL(12,4),
    14. high DECIMAL(12,4),
    15. low DECIMAL(12,4),
    16. close DECIMAL(12,4),
    17. volume BIGINT,
    18. amount DECIMAL(20,4),
    19. adjust_type VARCHAR(8) DEFAULT 'none',
    20. PRIMARY KEY (symbol, trade_date, adjust_type)
    21. );
    22. -- Intraday bars
    23. CREATE TABLE minute_bar (
    24. symbol VARCHAR(16) NOT NULL,
    25. trade_time TIMESTAMP NOT NULL,
    26. price DECIMAL(12,4),
    27. volume BIGINT,
    28. PRIMARY KEY (symbol, trade_time)
    29. );
    30. -- Ingestion jobs and progress
    31. CREATE TABLE ingest_job (
    32. job_id BIGSERIAL PRIMARY KEY,
    33. symbol VARCHAR(16),
    34. data_type VARCHAR(16),
    35. total_cnt INT,
    36. done_cnt INT,
    37. state VARCHAR(16),
    38. message TEXT,
    39. started_at TIMESTAMP,
    40. finished_at TIMESTAMP
    41. );

    Use an idempotent UPSERT for all writes so that re-running an interrupted job never creates duplicates:

    1. INSERT INTO daily_bar(symbol, trade_date, open, high, low, close, volume, amount)
    2. VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
    3. ON CONFLICT (symbol, trade_date, adjust_type) DO UPDATE
    4. SET close = EXCLUDED.close, volume = EXCLUDED.volume;

    4. Step-by-Step Execution: Turning Prompts into Verifiable Work Orders

    The first step extracts only the symbol list. Its artifact is a structured list that the developer reviews manually, so a wrong symbol cannot contaminate the full data load. The second step performs the actual data pull, and the instruction should contain five elements: the goal, the input file location, storage requirements, progress visibility, and termination conditions. An example prompt structure:

    1. Goal: build the data foundation layer for a stock backtesting and analysis system
    2. Symbols: use the list I have already confirmed; do not add or remove entries
    3. Data source: prefer the market data interface whose quota I have configured locally; see the specified path for its documentation
    4. Storage: write to the local database, with separate tables for daily and intraday bars; present the field and type design before implementing
    5. Progress: print [done/total], the current symbol, throughput, and estimated time remaining to the console, and persist state to the job table
    6. Constraints: retry on rate limiting or empty responses and explain what happened; never skip silently

    The value of this style is that it separates “fast” from “correct” during acceptance: review the schema and code skeleton first, then release the full run once they check out.

    5. Progress Observability: Letting Users See What the Model Is Doing

    Long-running tasks need externally visible state; otherwise there is no way to tell computation from a stall. Three mechanisms work well in parallel: a single-line console progress refresh, state persisted to the job table, and a stack trace plus a summary of request parameters emitted on failure. Pseudocode:

    1. for i, sym in enumerate(symbols, 1):
    2. job = create_job(sym, "daily")
    3. for page in iter_pages(sym):
    4. rows = fetch_with_retry(page) # exponential backoff with a cap
    5. upsert_daily(rows)
    6. job.done_cnt += len(rows)
    7. print(f"\r[{i}/{len(symbols)}] {sym} "
    8. f"{job.done_cnt}/{job.total_cnt} "
    9. f"{rate:.1f} rows/s ETA {eta}", end="")
    10. finish_job(job)

    6. Common Problems and Engineering Countermeasures

    • Long periods with no response: usually caused by an oversized single request or synchronous blocking. Reduce page size, set request timeouts, run blocking calls inside a timeout-aware execution context, and keep the ability to resume from a checkpoint.
    • Rate limiting and exhausted quota: control throughput with a token bucket, cache results that already succeeded, and backfill only the missing date ranges once quota recovers.
    • Data quality: trading calendar misalignment, missing days from trading halts, and changes to adjustment factors all distort backtests, so the cleaning layer must record how each case was handled explicitly rather than filling values silently.
    • Incremental sync: start from the latest date already stored, backfill the range, and run periodic consistency checks comparing record counts and hash digests.
    • Security and compliance: read interface credentials from environment variables or local configuration, never from code or logs, and mask sensitive fields in log output.

    7. Conclusion

    Treating the large language model as a conversational implementer rather than a decision maker, constraining its output with a layered architecture, receiving data through a well-defined schema, and earning process trust through observable progress is the lowest-rework path to a backtesting data pipeline. Once the data layer is done, the same rhythm carries forward to factor computation, signal generation, and performance evaluation—each step small, verifiable, rollback-safe, and re-runnable.