Building a Reproducible Trading Backtest System with LLM Assistance

    This article explains how individual traders can build a reproducible review and backtesting system from their own trade records, with a large language model acting as an engineering assistant rather than an investment decision maker. It covers converting broker statements into a structured intermediate format, breaking requirements into verifiable small steps, designing a layered data schema, keeping long-running data pulls observable, validating model output through contract checks and numerical reconciliation, and avoiding common backtest pitfalls such as lookahead bias and survivorship bias.

    1. The Starting Point: Why Individual Traders Need a Reproducible Review System

    Many individual investors share the same experience: an erratic equity curve, more losing trades than winning ones, and post-trade attribution based on memory and emotion. Changing this does not start with finding a new stock-picking method. It starts with structuring your actual fill records, replaying them against historical market data, and letting objective data answer three questions: what are my real win rate and profit/loss ratio, do my losses come mainly from stock selection or from timing, and under what market conditions does my trading pattern stop working.

    The value of such a system lies in reproducibility: the same statements, the same market data, and the same rules produce the same conclusions for anyone who runs them. The large language model takes on the role of an engineering assistant, translating natural-language requirements into code, documentation, and tests, rather than making investment judgments on your behalf.

    2. Data Preparation: Turning Statements into a Model-Readable Intermediate Format

    Trading software usually exports tabular files. Handing those directly to an LLM creates two typical problems: merged cells, multi-level headers, and mixed-in remark columns cause the model to miss fields; and implicit formats for numbers and dates (cell formatting rather than text) lose precision during parsing.

    The recommendation is to insert a format-conversion layer: first convert the table into a structured plain-text markup format (for example, a Markdown table), then pass it to the model. Three rules should hold during conversion:

    • Flatten headers: combine multi-level headers into unique field names such as trade_date, symbol, side, quantity, price, fee, and stamp_duty.
    • Make types explicit: dates normalized to YYYY-MM-DD, amounts and prices as fixed-point decimals, direction as an enumerated value.
    • Mark missing values: never leave blanks; write NULL and report the missing ratio.

    A sketch of the field constraints:

    1. trade_date DATE NOT NULL
    2. symbol VARCHAR(16) NOT NULL
    3. side ENUM('BUY','SELL')
    4. quantity INT NOT NULL
    5. price DECIMAL(10,3) NOT NULL
    6. fee DECIMAL(10,3) DEFAULT 0

    After this layer, read accuracy improves noticeably, because the model faces a clean, unambiguous structure instead of a formatted composite document.

    3. Interaction Methodology: Splitting a One-Line Request into Verifiable Steps

    A repeatedly confirmed lesson: handing the entire requirement to the model at once easily produces runaway output — wrong file paths, invented field names, missing dependencies, dozens of files changed in one pass. A more reliable approach is to think the workflow through yourself first, then release it step by step, with a clear acceptance artifact for each step.

    The recommended sequence:

    1. Extract the instrument list: pull all security codes and names from the statements, then review them manually. The output is a plain list, the easiest thing to verify.
    2. Probe interface capabilities: have the model fetch the data service documentation locally, generate a documentation copy, then write tests per endpoint and output a test report stating which endpoints work, what fields they return, and what the per-call limit is.
    3. Pull and store data: fetch daily and intraday bars per the list, load them into the database, and print progress.
    4. Compute metrics and run the backtest: implement rules for fees, stamp duty, slippage, and holding period.
    5. Generate the report: output win rate, profit/loss ratio, maximum drawdown, and monthly return attribution.

    Small-step delivery has an additional hidden benefit: every artifact can go into version control, so when something breaks you can pinpoint which step introduced the deviation instead of rolling back the whole project.

    4. Data Layer Design: Define the Spec Before Scaling

    The most common trap in personal projects is an casually created database with messy field naming, so that adding adjustment factors or industry classifications later requires table changes. Start instead with a three-layer split: raw layer, normalized layer, and feature layer.

    • Raw layer: store interface responses as-is for traceability.
    • Normalized layer: unify the primary key (instrument + trade date + frequency), unify time zone, unify the adjustment method, and add a unique index to prevent duplicate writes.
    • Feature layer: derived metrics such as rolling returns, volatility, and moving-average deviation, recomputable at any time.

    Primary key and index sketch:

    1. CREATE TABLE daily_bar (
    2. symbol 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. adjust_type VARCHAR(8) DEFAULT 'qfq',
    10. PRIMARY KEY (symbol, trade_date, adjust_type)
    11. );

    For writes, prefer batch commits, retry on failure, and resumable transfers, and record the start and end time of each pull in a task log table so an interruption does not force you to start over.

    5. Visible Progress: Keeping Long Tasks from Looking Hung

    A data pull can involve thousands of requests, and the worst part is having no feedback. Long stretches without output are common in practice, and most are not model capability problems but buffered streaming output, a blocked single request, or unflushed logs. Three mitigations work:

    • Structured progress: every 50 items, print completed/total/success/fail/elapsed.
    • Timeouts and retries: set connect and read timeouts per request, retry with exponential backoff, and push beyond-threshold failures to a failure queue.
    • External observability: write task status to a logging service or monitoring alert, and watch generic metrics (throughput, failure rate, latency) instead of staring at the terminal.
    1. for i, batch in enumerate(batched(symbols, 50), 1):
    2. ok, fail = pull_and_store(batch)
    3. print(f"[{i}/{total}] ok={ok} fail={fail} elapsed={time.time()-t0:.1f}s", flush=True)

    Details like flush=True are often the real reason something “looks stuck.”

    6. Trustworthy Results: Model Output Must Be Validated

    When you hand engineering work to a model, the biggest risk is not that it cannot write code, but that what it writes looks correct. Validation is mandatory:

    • Interface contract checks: pin each endpoint’s return fields and types with the test report, and assert them in code.
    • Numerical reconciliation: sample several trading days and cross-check stored prices against original fill prices and public quotes.
    • Consistent conventions: fees, stamp duty, slippage, and the adjustment method must be identical in backtest and review, otherwise conclusions are not comparable.
    • Explainable conclusions: every metric in the report must trace back to specific fills and formulas.

    A practical habit is to present analysis and data facts separately: the facts section contains only verifiable numbers, and the conclusions section labels its assumptions. Even if the model’s judgment is too pessimistic or too optimistic, readers can decide whether the basis holds.

    7. Common Pitfalls

    • Using future data: relying on information knowable only after the close when computing metrics.
    • Survivorship bias: backtesting only current holdings or still-listed instruments.
    • Ignoring suspensions and price limits: assuming fills at the close when no trade was possible.
    • Underestimating costs: missing minimum commissions, transfer fees, and impact costs.
    • Overfitting: repeatedly tuning parameters on history, then failing immediately out of sample.

    8. Summary

    The core of the whole pipeline is not letting the model decide for you, but engineering a vague review wish into a verifiable data pipeline: normalize formats first, split requirements into steps, probe interfaces before pulling, define the schema before loading, keep the process visible, and always validate conclusions. Once this flow is stable, you can rerun the same statement repeatedly, observe performance differences across market conditions, and gradually accumulate a trading pattern of your own that is supported by data. Whether the model’s final assessment is reasonable depends on your data quality and how strictly you validate — the tool amplifies a methodology, it does not replace it.