Building a Backtesting System for Securities Trading with LLM Assistance
This article explains how individual traders can build a practical securities trading backtesting system with help from large language models (LLMs). It covers a four-layer architecture (data, storage, computation, and interaction), normalization of unstructured trade export files, local database design, market data ingestion through adapters, and an engineering workflow for collaborating with LLMs. It also discusses backtesting assumptions, key performance and risk metrics, common pitfalls, and best practices for reproducible results.
1. Why Individual Traders Need a Backtesting System
Most individual investors face the same problem when reviewing their trades: records are scattered across export files from trading software, with inconsistent formats and ambiguous field meanings. Without a unified standard for measuring where profit and loss come from, it is easy to mistake occasional gains for skill and systematic bias for luck. The value of backtesting is turning a “feeling” into verifiable metrics, such as win rate, profit/loss ratio, maximum drawdown, holding period distribution, turnover, and return attribution.
A minimal viable personal backtesting system usually has four layers: a data layer (trade confirmations and market data), a storage layer (a normalized local database), a computation layer (backtesting engine and metric calculations), and an interaction layer (reports and visualization). This article follows that layered structure and shows how LLMs can improve build efficiency while keeping the project under engineering control.
2. Data Preparation: Turning Unstructured Exports into Computable Structures
2.1 Normalizing Trade Confirmation Fields
Spreadsheet files exported from trading software often have these issues: inconsistent date-time formats, buy/sell direction mixed between text and signs, inconsistent splitting of fees (commission, stamp duty, transfer fees), and amounts stored as strings. Start by defining a unified schema:
CREATE TABLE trades (id INTEGER PRIMARY KEY AUTOINCREMENT,symbol TEXT NOT NULL,trade_time TIMESTAMP NOT NULL,side TEXT CHECK(side IN ('BUY','SELL')),price REAL NOT NULL,quantity INTEGER NOT NULL,amount REAL NOT NULL,fee REAL DEFAULT 0,source_file TEXT,imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);CREATE INDEX idx_trades_symbol_time ON trades(symbol, trade_time);
2.2 An Intermediate Format Conversion Layer
When spreadsheet files are fed directly to a model, rows and columns can be misaligned and numbers truncated. A safer approach is to first convert them into a structured plain-text markup format (for example, tables to Markdown), then let the model interpret the semantics. Numerical calculations should always be executed by code, while the model only generates and explains code. This division of labor—“the model handles semantics, code handles computation”—is the key to avoiding distorted results.
2.3 Data Quality Checklist
- Time monotonicity: whether trade times are strictly increasing and whether there are cross-market timezone offsets;
- Quantity consistency: whether sell quantity exceeds the position held at that time;
- Amount consistency: whether the difference between price × quantity and amount falls within a range explainable by fees;
- Instrument validity: whether the symbol was suspended, delisted, or adjusted for corporate actions.
3. Storage Design: A Local Database Built for Scaling
For personal projects, start with a lightweight relational database and follow three principles. First, separate the raw layer from the processed layer: raw imports are not cleaned, and cleaning results are written to views or wide tables. Second, store market data partitioned by “symbol + period + date” to avoid repeated fetching. Third, every table carries timestamps and source markers to ensure traceability.
CREATE TABLE daily_bars (symbol TEXT NOT NULL,trade_date DATE NOT NULL,open REAL, high REAL, low REAL, close REAL,volume REAL, adjusted_factor REAL,PRIMARY KEY(symbol, trade_date));CREATE TABLE job_log (job_id TEXT, symbol TEXT, stage TEXT,status TEXT, rows_fetched INTEGER, message TEXT,updated_at TIMESTAMP);
The job_log table is the foundation for observable progress later on. Any data fetching job should write to this table.
4. Common Practices for Market Data Ingestion
Individual developers typically use third-party data APIs that require credits or quotas. In engineering terms, abstract a data access interface and isolate the specific vendor inside an adapter:
class MarketDataAdapter:def fetch_daily(self, symbol, start, end): ...def fetch_intraday(self, symbol, start, end): ...class CachedAdapter(MarketDataAdapter):"""Read from the local database first, fetch only missing ranges, and log the job."""def fetch_daily(self, symbol, start, end):missing = self.db.find_missing(symbol, start, end)if not missing:return self.db.read(symbol, start, end)self.log(symbol, "FETCH", "RUNNING")rows = self.remote.fetch_daily(symbol, *missing)self.db.upsert(rows)self.log(symbol, "FETCH", "DONE", len(rows))return rows
Some general constraints are worth emphasizing: manage API documentation and access credentials as local configuration files, and never commit them to the code repository; apply rate limiting and retries to requests (exponential backoff is recommended); and prefer incremental fetching over full re-fetching to save quota.
5. Engineering Methods for Working with LLMs
5.1 Breaking Down the Workflow Beats One-Shot Instructions
Handing all requirements to the model at once often produces output that is hard to converge on. A more reliable approach is to split the task into small, verifiable steps: first extract the symbol list and confirm it manually; second, build the storage and fetching modules; third, implement the backtest and metrics; fourth, generate the report. Each step needs a clear acceptance standard to avoid “the more you change, the messier it gets.”
5.2 Observable Progress
Require tasks to emit structured progress during execution (current symbol, completed ranges, number of failed retries). This helps humans judge status and helps the model restore context after an interruption.
5.3 Handling Exceptions and Hangs
When a long-running task stops responding, first preserve the on-site logs and already-persisted data, then terminate and resume execution. Because data is already stored incrementally, the cost of re-running is low. This is the direct benefit of an “idempotent + incremental” design.
6. Backtesting and Metric Interpretation
A backtest needs three explicit settings: how trading costs are included, the fill price assumption (next day’s open or the first tradable price after the signal), and whether limit-up/limit-down situations that prevent fills are considered. For metrics, look at both return and risk: annualized return, maximum drawdown, Calmar ratio, win rate, profit/loss ratio, average holding days, and return attribution by symbol and by month.
Be clear about the boundaries of backtesting: in-sample fitting overestimates performance, and with a small personal sample, survivorship bias is obvious. Conclusions should therefore be stated as “how this trading habit performed under the current sample,” not as a universal rule. Out-of-sample validation and rolling-window tests can significantly reduce misjudgment.
7. Common Pitfalls and Best Practices
- Inconsistent adjustment handling causes jumps in returns;
- Ignoring fees and slippage inflates high-frequency strategy results;
- Time misalignment creates look-ahead bias (using data after the signal time);
- Hard-coded credentials and missing logs make jobs non-reproducible.
In summary, the core of a personal backtesting system is not how powerful the model is, but standardized data, scalable storage, and reproducible computation. LLMs and AI coding tools are well suited to scaffolding generation, code explanation, and documentation, while deterministic computation is left to code and judgment is left to the user. Only then can you obtain truly objective review conclusions at a controllable cost.
