Building a Backtesting System for Securities Trading with LLMs: A Practical Guide
This article walks through building a personal securities trading backtesting system with LLM assistance. It covers turning broker-exported trade tables into structured data, decomposing requirements into step-by-step tasks, designing extensible storage with four core tables, making long-running jobs observable, and validating results so backtest conclusions stay reproducible. It also summarizes common failure modes and their fixes.
1. Background: Why Turn Trade Confirmations into a Backtestable Data Asset
Most individual investors’ trading records sit in spreadsheets exported from brokerage software. They support only coarse review such as “checking the return,” and cannot answer the more important question: did my losses come from stock selection, market timing, or position sizing? Answering that requires structuring the trade flow into computable data and reconstructing the decision environment on historical market data.
A complete personal backtesting and analysis system typically has five layers: data ingestion, storage, computation, reporting, and scheduling. LLMs are well suited to the “glue layer” work — generating scaffolding code, writing data-fetching logic, filling in field mappings and exception handling — but they should not replace your own definition of the trading logic. Drawing that boundary clearly is the precondition for keeping the project under control.
2. Data Preparation: From Spreadsheets to Structured Text
Tables exported by brokers often contain merged cells, multi-row headers, separate columns for trade date and time, and mixed representations of buy/sell direction (signs or text). Handing such files directly to a model easily leads to column misalignment and missed fields.
The recommended approach is to first convert the spreadsheet into a cleanly structured plain-text format (for example a Markdown table or CSV), using a local file conversion tool so that sensitive account information is never uploaded to an external service. After conversion, manually spot-check three things:
- Whether headers are unique and semantically clear;
- Whether amount and quantity fields are recognized as numbers rather than strings;
- Whether dates are normalized to ISO format.
An illustrative field specification:
trade_date DATE trade datetrade_time TIME trade timecode VARCHAR security codename VARCHAR security nameside ENUM direction BUY/SELLprice DECIMAL execution pricevolume INT traded quantityamount DECIMAL traded amountfee DECIMAL commission plus stamp duty
3. Requirement Breakdown: Turn One Long Prompt into Stepwise Tasks
Dumping all requirements on the model at once most often results in scope drift: it may invent metrics on its own, switch data sources without permission, or generate paths that cannot run. A more stable pattern is “humans define the workflow, the model fills in the implementation.”
In the first step, have it extract only the list of instruments and output a plain-text list; after you confirm it, move to the next step. In the second step, have it write the data-fetching script. At every step, require it to restate its understanding first, then list the files it will change, and only then execute.
A reusable stepwise prompt template:
Goal: build a securities trading backtesting and analysis system (step N of M)Inputs: instrument list file, local path to the API documentationConstraints:1. Use only interfaces declared in the documentation; do not invent fields;2. Read credentials from environment variables; never write them into code or logs;3. The fetching process must emit structured progress (current instrument, done/total, retry count for failures);4. A single instrument failure must not block the whole job; failed items go into a retry queue;5. When finished, output the table creation statements and run instructions.Give the plan and file list first; write code only after I confirm.
4. Storage Design: Extensibility Is the Core Metric
Backtesting storage must serve two kinds of queries at once: fetching market data by instrument and range, and fetching a whole-market snapshot by time. A four-table structure — metadata table, market data table, trade table, and run log table — is recommended. Partition the market data table by instrument and period, add a unique constraint on (code, trade_date), and pair it with pre-write deduplication or an idempotent upsert so repeated fetches never produce dirty data.
CREATE TABLE daily_bar (code VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,open DECIMAL(12,3),high DECIMAL(12,3),low DECIMAL(12,3),close DECIMAL(12,3),volume BIGINT,amount DECIMAL(18,2),PRIMARY KEY (code, trade_date));CREATE TABLE ingest_job (job_id BIGSERIAL PRIMARY KEY,target VARCHAR(64),status VARCHAR(16),total INT,done INT,failed INT,updated_at TIMESTAMP);
Credential management must be stated up front: sensitive items such as tokens should be injected through environment variables or a local key file and masked in logs; if the API documentation contains credentials, clean them before ingestion and do not leave them scattered across the project directory over the long term.
5. Progress Observability: Stop Long Jobs from Looking “Hung”
When a long-running task appears unresponsive, the cause is usually not model capability but network waits, rate-limit retries, and unflushed buffers. Address it on three fronts:
- Switch line-buffered output to unbuffered or explicit flushing so progress is visible in real time;
- Set connection and read timeouts for every request, with exponential backoff retries;
- Persist task state to a database or a local state file so jobs can resume from a checkpoint after interruption.
Pseudocode example:
for i, code in enumerate(targets, 1):for attempt in range(1, MAX_RETRY + 1):try:df = fetch_daily(code, start, end, timeout=10)upsert_daily(df)mark_done(job_id, i)breakexcept TimeoutError:log_progress(job_id, i, retry=attempt)sleep(2 ** attempt)
6. Result Validation: Backtest Conclusions Must Be Reproducible
The three easiest ways to fool yourself in backtesting are lookahead bias, survivorship bias, and ignoring costs. If a buy signal uses an indicator only available after the close of the same day, returns are systematically overstated; if the instrument list contains only current holdings, delisted securities are missed; without commission, stamp duty, and slippage, high-frequency strategy returns are essentially distorted.
Fix the random seed and the data snapshot version, and output the equity curve, maximum drawdown, win rate, profit/loss ratio, and number of trades, then run rolling validation of the same strategy across different periods. Any conclusion should be reproducible with a single script rerun that yields identical results.
7. Common Failure Modes and Fixes
| Symptom | Root cause | Fix |
|---|---|---|
| Scope drift after giving all requirements at once | Overly long context, vague constraints | Deliver step by step, confirm each step |
| No output for a long time | Missing buffering and timeout handling | Unbuffered output, timeout plus retry |
| Invented fields | No authoritative API description | Allow only fields present in the documentation |
| Duplicate data | No unique constraint | Idempotent writes plus a unique key |
| Overly optimistic conclusions | Lookahead bias, missing costs | Time-based splitting, include costs |
8. Conclusion
The value of LLMs is compressing the distance from “idea to runnable code” into a single conversation, but data standards, task boundaries, and validation criteria must still be owned by the developer. Proceeding in the order of data normalization, stepwise implementation, extensible storage, observable execution, and reproducible validation, individual investors can build their own quantitative review loop at very low cost. If data and compute scale keep growing, you can later add object storage for cold-data archiving, a message queue for task decoupling, a container platform for environment consistency, and logging plus monitoring and alerting for full-chain observability, letting the system evolve smoothly from a single-machine script into a sustainable engineering platform.
