A Practical Guide to Building an LLM-Assisted Securities Trading Backtesting System
This guide explains how individual investors can build a reproducible backtesting workflow using their own historical trade confirmations as the single source of truth. It covers a five-layer system architecture, normalizing exported trade tables into structured text, driving coding assistants with step-by-step prompts, designing a normalized local database with raw and derived layers, making long-running data pulls observable and recoverable, fixing backtesting assumptions and metrics in advance, and avoiding common pitfalls such as data snooping, survivorship bias, lookahead functions, and ignored costs. It also clarifies the proper role of large language models as coding assistants rather than sources of numerical judgment. Readers will gain a practical engineering blueprint for evaluating historical trading behavior, not predicting future returns.
1. Background: Why Individual Investors Need a Reproducible Backtesting Process
Most individual investors make trading decisions based on intuition and real-time news, with little quantitative examination of their own behavior. A common and low-cost improvement is to treat historical trade confirmations as the single source of truth and build a closed loop of data acquisition, cleaning, feature computation, backtesting, and reporting. This delivers three benefits: it replaces subjective memory with objective records; it turns one-off analysis into repeatable engineering assets; and it exposes real behavioral biases through consistent metrics such as win rate, profit/loss ratio, maximum drawdown, and holding-period distribution.
It is important to stress that the goal of a backtesting system is to evaluate historical behavior, not to predict future returns. Treating it as a promise of returns is a mistake, because historical patterns break down under changes in market rules, liquidity, and style rotation.
2. Overall Architecture
A robust individual-level analysis system is best organized into five layers:
- Data ingestion layer: exports statements from trading software and converts them into machine-friendly text.
- Data storage layer: a local relational database, split by subject, preserving both a raw layer and a processed layer.
- Data service layer: a unified read interface for market and trade data that hides underlying differences.
- Computation layer: factor calculation, fill simulation, portfolio equity, and risk metrics.
- Presentation layer: structured reports and charts, with support for run-over-run comparison.
The core benefit of layering is decoupling: the market data source can be swapped, trade record formats can evolve, and the computation logic stays stable.
3. Step 1: Turn Trade Confirmations into Structured Text
Mainstream trading software usually offers only table export, and large language models tend to drop fields when handling binary or complex composite documents. A more reliable approach is to normalize the format first: convert tables into a plain-text markup language to reduce parsing ambiguity.
Key validation points for normalization include:
- Field completeness: whether date, symbol, side, price, quantity, commission, stamp duty, and transfer fee are all present;
- Type consistency: use fixed-point numbers for amounts and quantities, avoiding floating-point accumulation that causes rounding drift;
- Encoding consistency: standardize on an encoding without BOM to avoid garbled non-English characters;
- Time semantics: distinguish execution time from settlement time to avoid wrong cross-day attribution.
An illustrative directory layout and conversion flow:
data/raw/ original exported filesmd/ normalized markup textclean/ cleaned structured intermediate results
# Pseudocode: normalizing a table into markup textdef normalize(raw_table_path, md_path):rows = read_table(raw_table_path)rows = [normalize_types(r) for r in rows]assert required_fields(rows), "Missing required fields; abort the pipeline"write_markdown(rows, md_path)
4. Step 2: Drive Coding Assistants with Step-by-Step Prompts
Handing all requirements to a model at once often leads to an implementation that spirals out of control: arbitrary directory structures, bloated dependencies, and missing error handling. A more controllable approach is to let the workflow define itself and delegate one step at a time, with each step producing a verifiable intermediate artifact.
A recommended prompt skeleton has five elements: goal, input paths, constraints, acceptance criteria, and progress visibility. Example:
Goal: Build the data-pull module for a trading backtesting analysis system.Inputs: the symbol list above; local API documentation (including access credentials).Constraints: prefer the points-based market data API; the database must benormalized and extensible; each table serves a single subject;all writes must be idempotent.Acceptance: the console prints per-symbol progress and retry counts;print row-count statistics when finished.
A sensible breakdown is: symbol extraction and manual confirmation → database schema definition → daily bar pull → intraday pull → completeness check → backtesting computation → report generation. Confirming each step with a human before continuing significantly reduces rework cost.
5. Step 3: Normalized Design of the Local Database
A two-tier structure of “raw layer plus processed layer” is recommended. The raw layer stores facts only and makes no inferences; the processed layer stores derived metrics that can be rebuilt at any time.
Reference schema:
CREATE TABLE trade_raw (id BIGINT PRIMARY KEY,trade_date DATE NOT NULL,symbol VARCHAR(16) NOT NULL,side SMALLINT NOT NULL,price DECIMAL(12,4) NOT NULL,quantity BIGINT NOT NULL,fee DECIMAL(12,4) NOT NULL,source_file VARCHAR(128));CREATE TABLE daily_bar (symbol VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,open_px DECIMAL(12,4),high_px DECIMAL(12,4),low_px DECIMAL(12,4),close_px DECIMAL(12,4),volume BIGINT,PRIMARY KEY (symbol, trade_date));
Design points: use natural primary keys, use fixed-point numbers for amounts, build composite indexes for common queries, and use batch commits with idempotency keys on writes to avoid data bloat from repeated pulls.
6. Step 4: Visible Progress and Failure Recovery
Long data pulls are worst when they feel like a black-box wait. Engineering practice should do three things: commit in batches and print completed and failed counts; send failed tasks to a retry queue with exponential backoff; and record checkpoints so a restart resumes from the checkpoint.
for batch in chunk(symbols, size=20):ok, fail = pull_daily(batch)log_progress(done=ok, failed=fail)if fail:retry_queue.extend(fail) # retry after exponential backoff
In addition, sensitive information such as credentials should be injected through environment variables or a local configuration file and excluded from version control; never write it into prompts or logs.
7. Step 5: Backtesting Conventions and Metric Definitions
The credibility of backtesting conclusions depends on whether conventions are fixed in advance. Specify clearly: the fill price assumption (closing price or next-day open), the commission and tax model, slippage assumptions, whether intraday round trips are allowed, how suspensions and price limits are handled, and the starting size of the equity curve. Once conventions are set, they must not be changed midway, or comparisons lose meaning.
Core metrics should include: number of trades, win rate, average profit/loss ratio, expected return, maximum drawdown, return volatility, holding-days distribution, and performance grouped by month. Grouped performance often reveals problems better than aggregate numbers, for example, “losses are concentrated in chase trades placed within the first half hour after the open.”
8. Common Pitfalls and How to Avoid Them
- Data snooping: repeatedly tuning parameters until results look good is fitting noise. Keep an out-of-sample period.
- Survivorship bias: using only currently visible symbols and ignoring delisted ones.
- Lookahead functions: using information available only after the close to decide same-day fills.
- Ignoring costs: ignoring taxes and slippage systematically overstates performance.
- Prompt runaway: delivering too large a task at once, producing a chaotic structure. Switch to small deliveries with human confirmation.
9. A Rational View of Model Capability Boundaries
The sensible role of a large language model in this kind of project is a coding assistant and documentation organizer: generating scaffold code, explaining errors, and completing validation logic. Numerical computation and final judgment should be done by deterministic code. Generated code must be reviewed and tested, especially anything involving amounts, ordering, and time. If the model becomes unresponsive for a long time, interrupt it and retry with a smaller task granularity; this usually works better than continuing to wait.
10. Conclusion
Building a backtesting system from personal trade confirmations is essentially a small data engineering exercise: format normalization sets the ceiling, database design determines extensibility, step-by-step prompts determine delivery quality, and fixed conventions determine the credibility of conclusions. For lower operational overhead, storage and computation can be moved to a combination of general-purpose cloud capabilities, for example, object storage for raw files, a container platform for compute jobs, and log and monitoring services for observability, so that effort stays focused on the analysis logic itself.
