Building a Stock Trading Backtest System with LLMs: A Practical Guide
This article walks through the engineering practice of turning brokerage trade confirmations into a computable dataset for stock backtesting. It covers a five-layer architecture, converting tabular files into a model-friendly intermediate format with validation checks, writing step-by-step prompts instead of one long instruction, database schema design, progress visibility and retry handling, and fixing backtest assumptions upfront. It also lists common pitfalls and explains how to avoid look-ahead and survivorship bias. The output is statistical analysis only, not investment advice.
1. Where the Problem Starts: Turning Trade Confirmations into Computable Data
Most individual investors review their trading by looking at candlestick charts and relying on memory. The genuinely informative source is the complete transaction history in the account: the fill price, quantity, timestamp, commission, and stamp duty for every single trade. Only after these records are structured can you answer a few key questions: What is my win rate? Is my profit-to-loss ratio positive? Is turnover too high? Are profits concentrated in a handful of lucky trades?
The technical difficulty here is not the algorithm but the data pipeline: inconsistent export formats, ambiguous field meanings, missing adjustment and trading-halt handling, and mismatched time zones and trading sessions. Once the upstream data is dirty, no downstream statistical conclusion can be trusted. So the engineering order should be: govern the data first, then compute.
2. Overall Architecture: Five Layers, Single Responsibility
Split the system into five layers that communicate only through explicit data contracts:
- Collection layer: export the transaction history from the brokerage software and normalize it into a structured text format.
- Cleaning layer: standardize fields, flag anomalies, and split out fees.
- Storage layer: a local relational database modeled in three tiers: raw tables, cleaned tables, and feature tables.
- Computation layer: fetch market data, align it, and simulate signals and fills.
- Presentation layer: progress output, metric reports, and a written summary.
The benefit of layering is that any failing layer can be isolated on its own, and it also makes it easy to later move the system to scheduled jobs or a containerized deployment.
3. Step One: Convert Tables into a Model-Friendly Intermediate Format
Handing spreadsheet files directly to an LLM often produces problems: only part of the rows get read, columns shift, and numbers are treated as text. A more reliable approach is to first convert the file into a clean, row-aligned plain-text markup format (for example, a pipe-delimited table syntax) and then pass it to the model.
After conversion, run three checks:
- Row count: does the number of data rows plus the header row equal the total number of rows in the source file?
- Type check: are price and quantity numeric, and can the date be parsed?
- Null check: does the proportion of missing fields exceed the threshold? If so, fall back to manual confirmation.
Illustrative validation logic:
def validate(md_rows, source_rows, required_cols):assert len(md_rows) + 1 == source_rows, "row count mismatch"for r in md_rows:for c in required_cols:assert r[c] not in (None, "", "-"), f"missing field: {c}"return True
4. Step Two: Replace One Long Prompt with Step-by-Step Prompts
A repeatedly confirmed lesson: throwing the entire requirement at the model at once easily leads to runaway output, with a chaotic directory structure, missing dependencies, and constant mid-stream rewriting. A more reliable way is to think the workflow through yourself first, then break it into small, acceptance-testable steps, each doing one thing and confirmed manually right away.
The recommended prompt skeleton has four parts: goal, inputs, constraints, and acceptance criteria.
Goal: Build a stock buy/sell backtest analysis system; for now, only load market data into the database.Inputs: A confirmed list of target symbols; local API documentation (contains access credentials, do not share externally).Constraints: The database schema must be normalized and extensible; the fetch process must print readable progress; failures must be retryable.Acceptance: Provide the table schema, a sample progress log, and three sampled records for cross-checking.
The suggested step order is: confirm the symbol list → design the schema → trial-fetch a single symbol → batch fetch with rate limiting → data quality report. Each step produces a checkable artifact, which prevents errors from accumulating.
5. Step Three: Design Points for Persisting Data
Design the schema for extensibility, not just for the current analysis:
- Daily market data table: symbol, trading date, open/high/low/close, volume, turnover value, adjustment factor.
- Intraday table: symbol, timestamp, last price, cumulative volume, partitioned by date.
- Transaction history table: fill time, direction, price, quantity, commission, tax.
- Feature table: turnover, holding days, and profit/loss flags derived from the first three.
For indexes, a common composite primary key is “symbol + time.” Writes should use batch commits and an idempotency key to avoid duplicated fetches doubling the data. Credentials should be injected through environment variables or local configuration, never committed to the code repository.
6. Step Four: Progress Visibility and Stability
Long-running fetch jobs fear “silent hangs”: the interface stays unresponsive for a long time, and you cannot tell whether it is waiting, rate-limited, or already dead. Engineering should cover three points:
- Structured logs: for each record, output “completed/total, current symbol, rate, failure count.”
- Resume from checkpoint: record the cursor position of completed work and continue from it after a restart.
- Timeout and retry: distinguish network timeouts from business errors, retry with exponential backoff, and skip and flag once the limit is exceeded.
for i, code in enumerate(codes, 1):if is_done(code):continuetry:rows = fetch_with_retry(code, retries=3)bulk_upsert(rows)except Exception as e:log.error({"code": code, "err": str(e)})log.info(f"progress {i}/{len(codes)} symbol={code}")
7. Step Five: Fix the Backtest Rules Upfront
The credibility of a backtest conclusion depends on having a single, unambiguous set of rules. At minimum, document and lock down: trading fees and taxes, slippage assumptions, fill matching rules (next-day open or same-day close), no fills at price limits, trading-halt handling, and the adjustment method. Once the rules change midway through the analysis, all historical conclusions are invalidated.
Also watch for two types of bias: first, look-ahead bias, using information that was not available at the time; second, survivorship bias, a symbol list that only includes symbols still active today. The fixes are point-in-time alignment and a full symbol universe.
8. Common Pitfalls
- Letting the model read raw binary spreadsheets directly, causing data truncation.
- Generating the whole project in one shot, with no acceptance-testable intermediate artifacts.
- No progress output, so problems are diagnosed by guesswork.
- Hardcoding credentials in scripts.
- Tracking only returns, without looking at trade count or the share of costs.
9. Conclusion
Connecting trade confirmations to a pipeline of “structure → ingest → backtest → review” is not valuable because it produces a nice-looking report, but because it makes every trading decision testable against data. On the technology side, a general-purpose LLM with long-context and tool-calling support, paired with a local database and log monitoring, is enough to get this running. If you later need scheduled orchestration and elastic compute, general cloud capabilities such as container platforms, object storage, and monitoring alerts can carry that load. One reminder: the output of such a system is only a statistical description and does not constitute any investment advice. And when a model gives an extreme judgment about your trading behavior, the more reasonable response is not to accept the conclusion but to go back to the data itself and check whether the rules and the sample are adequate.
