Building a Trading Backtest System with LLMs: A Practical Engineering Guide
This article walks through the engineering practice of building an LLM-assisted trading backtest and review system. It covers a five-layer architecture, converting spreadsheet exports into structured text before model processing, a step-by-step collaboration workflow with human checkpoints, normalized storage design, idempotent data fetching with progress tracking, metric calculation and result validation, and a checklist of common pitfalls. Readers will learn how to turn subjective trading reviews into reproducible, verifiable metrics.
1. The Starting Point: Why Personal Trading Reviews Need Engineering
Most individual investors have had a similar experience: the account curve swings unpredictably, losing trades outnumber winning ones, and reviews rely entirely on memory and emotion, producing unverifiable conclusions such as “just bad luck.” A genuinely useful review must be built on a reproducible data pipeline: every buy and sell must be traceable to its time, price, quantity, and fees, and every strategy hypothesis must be repeatedly testable against historical market data.
The value of engineering is turning “feelings” into “metrics.” Once trade confirmations are structured, metrics such as win rate, profit/loss ratio, maximum drawdown, holding-period distribution, and turnover can be computed automatically. Once market data is stored in a standardized form, the same strategy can be rerun across different time windows and different symbol pools. This is exactly why trading review should be treated as a software project.
2. Overall Architecture
A usable backtest and analysis system can typically be split into five layers:
- Data ingestion layer: exports statements from trading software and converts them into machine-friendly formats.
- Data cleaning layer: handles misaligned fields, missing trade direction, fee splitting, and inconsistent adjustment (split/dividend) conventions.
- Storage layer: persists trade flows, a symbol dictionary, and market data series in a normalized relational structure.
- Computation layer: pulls historical market data, runs matching, and computes metrics.
- Presentation layer: outputs progress, logs, and visual reports.
The key benefit of layering is replaceability. When the data source switches from exported files to an API pull, only the ingestion layer changes; when metric definitions change, only the computation layer is affected.
3. Data Ingestion: From Spreadsheet Files to Structured Text
Trading software exports are usually spreadsheet files, and handing them directly to an LLM carries obvious risk: the model tends to skip or misalign rows and columns when reading multi-row, multi-column content, especially with merged cells and thousands separators. A safer approach is to perform a format conversion first, turning the spreadsheet into a structured plain-text markup format before passing it to the model.
After conversion, keep the original row numbers so entries can be traced back for verification:
| Row | Fill Time | Symbol | Name | Side | Price | Quantity | Fee || --- | --------- | ------ | ----- | ---- | ----- | -------- | ---- || 1 | 09:35:12 | 600xxx | DemoA | Buy | 12.30 | 1000 | 5.20 |
Three things should be done immediately at the ingestion stage: verify that the total row count matches the exported file; verify that the deviation between amount and price-times-quantity stays within tolerance; and isolate rows that cannot be parsed into a separate quarantine instead of silently dropping them.
4. Working with LLMs the Right Way: Process First
One repeatedly confirmed lesson: do not throw a complex requirement at the model all at once and wait for the result. Personalized tasks are especially prone to getting out of control — the model invents fields on its own, skips validation, and generates dependencies that cannot run. A more reliable approach is to think the workflow through yourself first, then break it into small steps and confirm each one.
The recommended rhythm: first have the model extract the symbol list and confirm it manually; then have it define the table schemas; then implement fetching and ingestion; finally implement metric computation and report output. At every step, require it to print what it is about to do and the expected scope of impact.
A sample prompt structure:
Task: Build the market data fetching moduleInputs: confirmed symbol list file, API documentationRequirements:1. Output the schema design first; write code only after my confirmation;2. The fetching process must print the current symbol, number completed, and retry count on failure;3. Failed items go to a separate failure queue without interrupting the overall task;4. Do not add third-party dependencies that were not specified.
As for the “freeze” phenomenon during a run — long stretches with no output — this is usually not a model capability issue but rather buffered output for long tasks, an overly long single-request context, or a blocking tool call. The countermeasures include: split tasks smaller, require staged writes to disk, set timeouts and retries, and keep a progress file so runs can resume from a checkpoint.
5. Storage Design: Normalization and Extensibility First
The storage layer should contain at least four entity types: symbol dictionary, trade flow, daily bars, and intraday bars. The design follows three principles: explicit primary keys, timestamps unified as timezone-aware values, and high-precision types rather than floats for amounts and quantities.
CREATE TABLE trade_flow (id BIGSERIAL PRIMARY KEY,trade_time TIMESTAMPTZ NOT NULL,symbol VARCHAR(16) NOT NULL,side SMALLINT NOT NULL,price NUMERIC(18,4) NOT NULL,quantity BIGINT NOT NULL,fee NUMERIC(18,4) DEFAULT 0,raw_line INT,created_at TIMESTAMPTZ DEFAULT now());CREATE INDEX idx_trade_time ON trade_flow (trade_time);CREATE INDEX idx_symbol_time ON bar_daily (symbol, trade_date);
For market data tables, use a composite unique constraint on “symbol + time” together with idempotent writes, so repeated pulls produce no dirty data and checkpoint resume becomes simple.
6. Market Data Fetching and Progress Visualization
The core of the fetching stage is not speed but observability and idempotency. In practice, separating the producer from progress tracking is recommended: the fetching task only retrieves and writes data, while progress is carried by an independent progress table or logging service that the frontend polls.
for i, sym in enumerate(symbols, 1):if already_done(sym):continuetry:df = fetch_daily(sym, start, end) # unified entry point, easy to swap data sourcesupsert_bars(df)mark_done(sym, rows=len(df))except Exception as e:mark_failed(sym, reason=str(e))print(f"[{i}/{len(symbols)}] {sym} done, failures {fail_count}")
If the data volume is large, tasks can be split into shards, decoupled with a message queue, intermediate results stored in object storage, and failure rates and latency observed through logging and monitoring/alerting services. These are all general-purpose cloud capability categories that can be combined as needed.
7. Metric Computation and Result Validation
Backtest output should include at least: number of trades, win rate, average profit/loss ratio, expected return, maximum drawdown, average holding days, and monthly return distribution. Validation cannot be skipped: manually compute a few trades and reconcile them with the program output; run sensitivity tests on the adjustment method; and check for look-ahead bias, meaning the use of information that was only available after the fill time.
8. Common Pitfalls Checklist
- Feeding spreadsheets directly to the model without format conversion, causing missed reads;
- Sending all requirements at once, with no human confirmation checkpoint;
- Ignoring commissions and stamp duty, inflating returns;
- Storing amounts as floats, producing accumulated error;
- Fetching that cannot resume from a checkpoint, forcing a full restart after failure;
- Looking only at total return, ignoring drawdown and holding-period distribution.
9. Closing
Turning trading review into a small data engineering project pays off far beyond a single conclusion report: the process becomes fixed, definitions become unified, and conclusions can be verified repeatedly. The LLM plays the role of scaffolding, generating and rewriting code, while process design, metric definition, and result validation must remain in human hands. Once this system runs end to end, judging whether you are “heading for ruin” no longer depends on emotion, but on the curve and the metrics.
