LLM-Powered Backtesting System for Securities Trading: A Practical Guide
This article walks through building a personal backtesting system for securities trading with large language model (LLM) assistance. It covers a five-layer architecture, converting broker-exported spreadsheets into structured text, relational schema design with fixed-point arithmetic, breaking engineering work into verifiable steps for the model, honest assumptions in the simulation engine, common statistical biases, and how to interpret results without treating model output as investment advice.
1. Background and Problem Definition
Many individual investors face the same puzzle: their account swings up and down over the long run, losses outnumber gains, and yet they cannot say whether the problem lies in stock selection, market timing, or position sizing. A common piece of advice on social platforms is to review your own trade history repeatedly and extract stable trading patterns from it. The direction is right, but manually reading through hundreds or thousands of fill records makes an objective conclusion nearly impossible. The settlement statement therefore has to become structured data, handed to a reproducible program for statistical testing.
One boundary needs to be stated up front: backtesting is a statistical tool, not a promise of returns. Any conclusion drawn from historical data describes only the statistical properties of the past sample; it does not predict future returns, and it is not investment advice. Treating an LLM’s natural-language output directly as an investment judgment is the most common and most dangerous mistake in this kind of project.
2. Overall Architecture
A usable personal backtesting system usually has five layers:
- Data ingestion: convert the spreadsheet files exported by brokerage software into a machine-friendly plain-text structure;
- Data storage: hold both market data and trade data in a properly normalized relational database;
- Data service: expose daily bars, intraday bars, and adjustment factors to upper layers through a unified interface;
- Backtesting engine: matching, fees, slippage, positions, and equity curve calculation;
- Reporting: metrics, charts, and attribution conclusions.
The key benefit of layering is replaceability. Once the data source, the database, and the backtesting logic are decoupled, switching to a different data provider or a different matching assumption does not require rewriting the whole system.
3. Data Preparation: From Spreadsheets to Structured Text
Settlement statements exported by brokers are usually spreadsheet files with fields such as fill time, security code, name, side, filled quantity, fill price, commission, stamp duty, and net amount. Letting a model read a binary spreadsheet directly tends to produce misaligned rows and columns, truncated numbers, and skipped fields, especially with large volumes or when merged cells and multi-level headers are present.
A safer approach is to normalize the format first: use a document conversion tool or your own script to turn the spreadsheet into a plain-text markup structure, then hand that to the model. The conversion has to deal with three kinds of dirty data: empty values and placeholders, thousands separators and percent signs, and the multiple ways dates and times can be written. Illustrative code:
import refrom decimal import Decimaldef normalize_amount(text: str) -> Decimal:if text in ("", "-", "--", None):return Decimal("0")cleaned = re.sub(r"[,\s¥¥%]", "", str(text))return Decimal(cleaned)def normalize_code(raw: str) -> str:digits = re.sub(r"\D", "", raw)return digits.zfill(6)
Using fixed-point decimals rather than floating point for amounts is a hard requirement in financial and trading systems; otherwise accumulated error distorts the last digits of the equity curve.
4. Database and Table Design
The storage design has to satisfy two goals: extensibility and queryability. At minimum, four core tables are recommended: trade details, security reference data, daily bars, and minute bars. Key design points:
- The trade detail table uses fill time plus security code plus trade number as a unique constraint, preventing duplicate imports;
- Bar tables use a composite primary key of security code and trading date, with fixed-point types for prices;
- Adjustment factors live in a separate table, so adjusted and raw prices are never mixed;
- Every table keeps a data version or import batch field for traceability and recomputation.
CREATE TABLE trade_detail (trade_id VARCHAR(64) PRIMARY KEY,symbol CHAR(6) NOT NULL,trade_date DATE NOT NULL,trade_time TIME NOT NULL,side CHAR(1) NOT NULL, -- B/Sprice DECIMAL(12,4) NOT NULL,volume INT NOT NULL,fee DECIMAL(12,4) NOT NULL,batch_no VARCHAR(32) NOT NULL);CREATE INDEX idx_symbol_date ON daily_bar(symbol, trade_date);
5. Breaking Engineering Tasks Down with an LLM
Handing the entire requirement to a model at once usually produces output that fails to converge, particularly for personalized, context-heavy tasks. A more reliable pattern is to think the workflow through yourself first, split it into small steps, and deliver step by step, requiring a verifiable artifact at each step.
The first step does entity extraction only: pull the list of security codes and names involved in the settlement statement, confirm it manually, and only then move on. The second step has the model write the data-fetching script, with an explicit requirement to prefer already-authorized data interfaces, persist results to the database, and print progress to the console. A reusable prompt skeleton:
Goal: build a stock trading backtesting and analysis system.Current step: fetch daily and intraday data for the symbol list.Constraints:1. Use the locally configured data interface and credentials; credentials must not be written into code;2. Schema must be normalized and extensible, with unique constraints and indexes;3. Console must print total, completed, failed retries, and remaining estimate;4. Failed requests must retry with exponential backoff and must not be skipped silently.
Three more points matter in practice: inject credentials through environment variables or a local config file so they never enter version control; batch fetching must be rate-limited and support resuming from a checkpoint; and insist on small-step verification of generated code, running a single symbol end to end before the full batch. If an AI coding tool stops responding for a long time, interrupt it and ask the model to continue from the current progress instead of starting over.
6. Key Details of the Backtesting Engine
Whether backtest results are trustworthy depends on whether the assumptions are honest. At minimum, you need explicit settings for: trading costs (commission, stamp duty, transfer fees), a slippage model, the fill rule (executed at the next bar’s open or close), limit-up/limit-down and trading-halt handling, and capital and position caps.
def simulate(trades, bars, init_cash, fee_rate, slippage):cash, position, equity = init_cash, {}, []for bar in bars:for t in trades.get(bar.date, []):price = bar.open * (1 + slippage) if t.side == "B" else bar.open * (1 - slippage)amount = price * t.volumecash += -amount if t.side == "B" else amountcash -= amount * fee_rateposition[t.symbol] = position.get(t.symbol, 0) + (t.volume if t.side == "B" else -t.volume)equity.append((bar.date, cash + sum(position.get(s, 0) * p for s, p in bar.close.items())))return equity
7. Common Biases and How to Avoid Them
- Look-ahead bias: using information that was only available after that day’s close;
- Survivorship bias: running statistics only on symbols that still exist today;
- Overfitting: tuning parameters repeatedly until they fit the historical sample alone;
- Insufficient sample: with too few trades, no metric is statistically significant.
Countermeasures include strict time alignment, holding out an out-of-sample period for validation, limiting the number of tunable parameters, and benchmarking against a random baseline.
8. Interpreting Results and Common Pitfalls
Reports should focus on explainable metrics: cumulative return, maximum drawdown, win rate, profit/loss ratio, turnover, and average holding period, plus an attribution breakdown that separates stock-selection contribution from timing contribution. When a model produces a conclusion such as “this trading pattern will lead to a catastrophic outcome,” treat it as a signal rather than a factual judgment: it reflects the statistical properties of in-sample losses and calls for a manual review of data quality and assumption validity. The technical system does the calculation; responsibility for the decision always stays with the person.
