Building a Stock Trade Statement Backtesting System with LLMs: A Practical Guide

    This article walks through building a personal stock backtesting and analysis system powered by large language models (LLMs). It covers converting brokerage statements into structured text, extracting a ticker list with human verification, selecting and validating market data APIs, designing a scalable and idempotent database schema, and generating backtest reports. Key lessons include breaking work into verifiable steps, sanitizing inputs, adding timeout and retry logic for LLM calls, and treating the model as a capable junior engineer rather than an all-knowing expert.

    Introduction: A Review Journey Starting from a Trade Statement

    For individual investors, reviewing past trades is a critical part of improving profitability. Many experienced traders emphasize that repeatedly studying your own trade statements and distilling patterns that fit your personal style is a necessary path toward consistent returns. However, manually reconciling trades one by one is inefficient and prone to emotional bias. A natural idea is to combine your historical trade statements with market data and build an automated backtesting system that objectively answers the question: “Does my trading strategy actually work?”

    As large language models have rapidly improved at code generation and data analysis, work that once required a professional quantitative background can now be done by ordinary developers with the help of AI coding tools. This article retraces the full process of building a personal stock backtesting system from scratch, focusing on engineering methodology and pitfalls to avoid.

    1. Overall Approach: Human-AI Collaboration, Not One-Shot Delegation

    Before writing any code, the most important lesson is: do not dump all requirements onto the model at once and expect a perfect result in a single pass.

    For personalized, multi-stage projects, feeding everything in one prompt usually leads to uncontrolled output—the model may miss key constraints, hallucinate interfaces, or generate code that doesn’t run. A more reliable approach is for the human to decompose the workflow first, then have the model execute step by step, with each output confirmed before moving on.

    This project was divided into four stages:

    1. Exporting the trade statement and converting its format;
    2. Extracting the ticker list and manually verifying it;
    3. Selecting, validating, and persisting market data via APIs;
    4. Writing the backtesting logic and generating the report.

    2. Preprocessing Trade Statement Data

    2.1 Export and Format Issues

    Trading software typically exports statements as spreadsheets. In practice, some LLMs may parse spreadsheets incompletely due to differences in underlying parsing functions—for example, skipping rows or misidentifying numeric types.

    2.2 Converting to Plain-Text Structured Formats

    An effective approach is to convert the spreadsheet into a plain-text structured format such as Markdown before handing it to the model. Plain text is “what you see is what you get” for the model, free of parsing ambiguity, and easy to inspect manually. Several document-conversion solutions can batch-convert spreadsheets to Markdown and integrate into a local toolchain.

    The essence of this step is reducing input uncertainty: rather than hoping the model parses things correctly, proactively shape the data into the format the model understands best.

    3. Step-by-Step Execution: Extract the Ticker List First, Then Verify

    With the structured statement in hand, the first task is deliberately narrow: have the model extract only the stock names and codes from the statement, produce a ticker list, and verify each entry manually.

    This design matters because all subsequent market data retrieval depends on this list. If the list is wrong (a missing stock, a mismatched name and code), all downstream computation is built on a faulty foundation and rework is expensive. Having the model handle small, easily verifiable tasks with human checkpoints is the key to reliability across the whole pipeline.

    3.1 Observations on Model Stability

    During the project, we observed that some newly released model versions may hang without returning a response during peak usage. The workaround is simple: cancel and resubmit the request, which usually returns results quickly. This is a reminder that automated pipelines should include timeout and retry mechanisms for model calls rather than waiting indefinitely. Illustrative code:

    1. import time
    2. def call_llm_with_retry(prompt, max_retries=3, timeout=60):
    3. for attempt in range(max_retries):
    4. try:
    5. response = invoke_model(prompt, timeout=timeout)
    6. return response
    7. except TimeoutError:
    8. time.sleep(2 ** attempt) # exponential backoff
    9. raise RuntimeError("Model call timed out repeatedly; check service status")

    4. Selecting and Validating Market Data APIs

    4.1 Validate First, Then Use

    The project requires historical daily and intraday (minute-level) market data. Multiple public market data APIs exist, each with different availability, granularity, and rate limits. The “validate step by step” philosophy applies here too:

    1. Provide each API’s online documentation to the model and have it organize a local Markdown reference;
    2. Have the model write an independent test script for each candidate API to verify data can actually be retrieved;
    3. Compile an API availability test report documenting which APIs work, which fields they return, and what their rate limits are;
    4. Use only validated APIs in formal development.

    This may seem tedious, but it dramatically reduces downstream uncertainty—you won’t discover a dead API halfway through writing your backtest logic.

    4.2 Prompt Design for Data Retrieval Tasks

    When instructing the model to fetch data, the prompt should include:

    • Clear objective: pull all daily and intraday data based on the confirmed ticker list;
    • Clear priority: specify which data source to prefer and what the fallback is;
    • Clear storage conventions: require a well-structured, extensible local database (partitioned by ticker and period, or with properly designed primary keys and indexes);
    • Clear observability: real-time progress output during retrieval so progress can be monitored at any time.

    A reference progress-output pattern:

    1. total = len(stock_list)
    2. for idx, code in enumerate(stock_list, 1):
    3. fetch_and_store(code)
    4. print(f"[{idx}/{total}] {code} daily bars written")

    5. Database Design Principles

    The backtesting system’s database should follow several basic principles:

    • Extensible: adding new tickers or new data periods (e.g., minute bars, weekly bars) should not require restructuring tables;
    • Traceable: record the data source and retrieval time to help troubleshoot data quality issues;
    • Idempotent writes: re-fetching the same ticker and trading day must not create dirty data; enforce this with a primary key plus upsert semantics.
    1. CREATE TABLE daily_bars (
    2. stock_code VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open DECIMAL(10,3),
    5. high DECIMAL(10,3),
    6. low DECIMAL(10,3),
    7. close DECIMAL(10,3),
    8. volume BIGINT,
    9. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    10. PRIMARY KEY (stock_code, trade_date)
    11. );

    6. Backtesting and Report Generation

    Once the data is in place, the final step is aligning your historical buy/sell points with market data to answer a few core questions: What is the holding period and P&L distribution of each trade? Is there evidence of frequent chase-high/sell-low behavior? What would the outcome be if trades were re-executed under fixed rules (such as take-profit and stop-loss levels)?

    This stage should also be broken into small tasks: first have the model generate a per-stock, trade-by-trade reconciliation, spot-check it manually, and only then extend to all tickers and aggregate statistics.

    7. Key Takeaways

    Looking back at the whole project, several methodological lessons are worth retaining:

    1. Process first: the human decomposes the workflow and acts as gatekeeper; the model executes. Never delegate everything at once;
    2. Sanitize inputs: prefer converting data into plain-text structured formats to eliminate parsing ambiguity;
    3. Validate APIs first: write tests and produce a report for any external data source before formal development;
    4. Design for robustness: add timeouts, retries, and observable progress to model calls;
    5. Database discipline: design the storage layer to be extensible and idempotent from day one.

    To be objective, current LLMs already deliver significant productivity gains in code generation, but they won’t make decisions for you, and they can’t guarantee every output is correct. Treat the model as a junior engineer with strong execution who needs explicit instructions—not an omniscient expert. That is the right posture for success in this kind of project. As for whether the backtest report’s conclusions look optimistic—that depends on your trade statements, not on the model.