Building a Quantitative Backtesting System with LLMs: A Practical Guide
This article walks through building a practical quantitative backtesting system driven by large language models (LLMs). Instead of expecting a model to deliver conclusions in one shot, it treats the LLM as a tireless junior engineer that scaffolds code, generates boilerplate, maps fields, and organizes documentation under a clearly defined workflow, while the human owns the process, validates definitions, and makes the final judgment. It covers a five-layer architecture, cleaning broker trade exports, step-by-step prompting with human checkpoints, market data ingestion into a local database, observability for long-running fetch jobs, metric definitions, and security and compliance pitfalls. Readers will learn how to turn subjective trading review into a reproducible data pipeline.
1. Why This Project: A Real Need from a Non-Professional Developer
Most quantitative analysis tutorials assume the reader already has clean data, mature frameworks, and clear factor hypotheses. The reality for an individual investor is often quite different: an account that swings up and down, trade records scattered across exported files from brokerage software, no consistent definitions, and certainly no structured data warehouse.
A typical impulsive question—“Help me analyze my trades and see what patterns are wrong”—almost inevitably gets a generic reply. The reason is simple: the model does not have your data and does not know your definitions. The approach that actually works is to turn “evaluating the model’s capability” into “using the model to drive a reproducible data pipeline.”
The core argument of this article is that, at the current stage, the most reliable value of an LLM is not delivering a conclusion in one shot, but acting as a tireless “junior engineer” that completes scaffolding, boilerplate generation, field mapping, and documentation under clear process constraints—while the human defines the process, validates the definitions, and takes final responsibility for judgment.
2. Overall Architecture: Breaking Subjective Judgment into Verifiable Steps
A minimal viable backtesting analysis system can be split into five layers:
- Data ingestion layer: acquiring trade records (settlement statements) and market data;
- Cleaning and standardization layer: field alignment, time alignment, and adjustment (for splits/dividends) handling;
- Storage layer: a local database with a well-defined, extensible schema;
- Computation layer: metrics such as return attribution, holding-period distribution, profit/loss ratio, win rate, and drawdown;
- Presentation layer: structured reports and conclusions.
The point of layering is that each layer can be verified independently. When the final result is wrong, you can quickly locate whether the data is wrong, the definitions are wrong, or the computation is wrong—instead of repeatedly pressing on a vague “your trading habits are bad.”
3. Step One: Taming the Format of Trade Exports
Brokerage software usually exports spreadsheet files. Feeding one directly to the model has a common failure mode: “only part of the data gets read.” Merged header cells, amounts with thousands separators, buy/sell direction expressed as text rather than an enum, and inconsistent timestamp formats can all cause auto-generated parsing code to silently drop rows.
A more reliable path is to first do a format conversion, turning the binary spreadsheet into a plain-text markup language, and then hand it to the model. Three things matter during conversion: first, preserve the original row count and compare row counts after conversion; second, flatten multi-row headers into a single header; third, normalize amounts and quantities to numeric types.
Illustrative validation logic:
import pandas as pdraw = pd.read_excel("trades.xlsx", header=None)md_rows = count_markdown_rows("trades.md") # count data rows after conversionassert md_rows == len(raw) - header_span, "Rows were dropped during conversion"
This step may seem trivial, but it determines the credibility of every downstream conclusion. The first mile of the data pipeline always deserves extra time.
4. Step Two: Make the Model “Work in Steps” Rather Than “Deliver All at Once”
A repeatedly confirmed lesson: throwing the entire set of requirements at the model at once easily produces out-of-control output—arbitrary directory structure, drifting dependency versions, and missing exception handling. A more effective pattern is to think the process through yourself first, then hand down tasks step by step, with a human confirmation point at each step.
The first step is only to extract the list of instruments, which you verify manually; the second step is to have it write the data-fetching script; the third step is creating the database tables; the fourth step is computation and reporting. Each step’s prompt should include: input path, output path, location of the data-interface documentation, progress-printing requirements, and exception-handling requirements.
A reusable prompt skeleton:
Goal: Build a stock trading backtesting analysis system; execute only step N this time.Inputs: instrument list file, interface documentation (contains access credentials; read locally, do not echo them).Requirements:1) The database schema must be well-defined and extensible; provide the create-table statements and field comments;2) During fetching, print progress and retry counts per instrument;3) Do not modify files I did not specify;4) When done, output the list of all files touched in this step and how to self-test.
The two constraints “do not echo credentials” and “do not modify unspecified files” are critical: the former is a security baseline, and the latter prevents the model from casually refactoring your project structure.
5. Step Three: Fetching Market Data and Storing It Locally
Market data usually comes from two types of sources: one is API-based financial data services that provide daily and intraday data tiered by credits or call frequency; the other is open-source public data scraping solutions. The two are often used together: the former offers good stability and standardized fields, while the latter fills gaps and cross-validates.
For storage design, follow a two-tier “raw layer + processed layer” structure: the raw layer stores only the data as returned, keeping the fetch timestamp for traceability; the processed layer holds adjusted, aligned data. For the table design, use the instrument code, trade date, and period type as a composite primary key to avoid duplicate writes; build an index on the date field, because the vast majority of backtest queries are range scans.
CREATE TABLE daily_bar (ts_code VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,period VARCHAR(8) NOT NULL, -- daily/intradayopen DECIMAL(12,4),high DECIMAL(12,4),low DECIMAL(12,4),close DECIMAL(12,4),volume BIGINT,fetched_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (ts_code, trade_date, period));
Two easily overlooked engineering details: first, rate limiting and retries—every interface has frequency constraints, so you must implement exponential backoff; second, resumable progress—write completed instruments to a local progress file so an interruption does not force you to start over.
6. Step Four: Observability—Make “What Is It Doing” Visible
A long-running fetch task without progress output leaves the user anxious and unable to tell whether it is stuck or just slow. The lowest-cost approach is structured logging: each record includes the current instrument, completed/total count, elapsed time, and failure reason.
log.info("progress", extra={"code": code, "done": i, "total": n,"elapsed": round(t, 1), "fail": err})
A more advanced approach is to run the task on a container platform or task queue, paired with a logging service and monitoring alerts, to enable automatic retries on failure and timeout notifications. For a personal project, a timestamped text log plus a simple progress bar is enough.
Also face one reality: a newly launched model service may stall during peak hours, showing up as long periods with no output. A prudent strategy is to set a client-side timeout, split the task into small batches, and keep intermediate results, so that on a stall you abort and restart from the checkpoint rather than waiting indefinitely.
7. Step Five: Metric Definitions and Conclusion Generation
The value of a backtest report depends on whether the definitions are fixed in advance. At minimum, fix the following: win rate is “number of profitable sell trades / total sell trades”; profit/loss ratio is average profit divided by average loss; holding period distinguishes calendar days versus trading days from buy to sell, and states which; returns state whether fees and stamp duty are included; maximum drawdown states whether it is based on account net value or per trade.
Writing these definitions into the prompt and having the model generate the computation script and report template accordingly significantly reduces conclusions that “look right but can’t be reproduced.” The report should follow a fixed four-part structure: data overview, trading behavior statistics, profit/loss attribution, and actionable improvement hypotheses.
8. Security, Compliance, and Common Pitfalls
- Credential management: keep access tokens in a local config file or environment variables; read them, do not print them, and never commit them with the code.
- Data compliance: use market and trade data only for personal analysis; respect the data service’s terms of use and do not redistribute.
- Boundaries of conclusions: a backtest is based on historical data and can only propose hypotheses, not prove future validity; no output constitutes investment advice.
- Common pitfalls checklist: inconsistent adjustment methods distorting returns; mixing time zones between intraday and daily timestamps; dropped rows during spreadsheet conversion; duplicate writes doubling the metrics.
9. Conclusion
Treating the model as a process executor rather than a conclusion provider is the most important takeaway from this practice. When the data pipeline is broken into verifiable small steps, each with human confirmation and visible progress, the stability of the model’s output improves markedly. As for whether that final analysis report “judges you as heading toward ruin,” it does not really matter—what matters is that you finally have reproducible data assets and your own system of definitions, which is exactly the prerequisite for forming a trading pattern.
