How to Build an LLM-Driven Backtesting System from Brokerage Trade Records
This article walks through building a minimal, LLM-assisted backtesting pipeline that turns exported brokerage trade records into a queryable data asset. It covers converting spreadsheet exports into a model-friendly intermediate format, breaking a large request into verifiable steps, designing a normalized market-data schema with idempotent loading, adding observability to long-running tasks, and running backtesting and attribution analysis. It also highlights common pitfalls such as look-ahead bias and survivorship bias, and closes with data-handling and risk notes. Readers will get a practical, end-to-end workflow they can adapt with AI coding tools.
1. Starting Point: Why Turn Trade Records into a Backtestable Data Asset
Many individual investors share a familiar experience: the account curve swings unpredictably, losing years outnumber profitable ones, and reviews rely on memory and emotion, making conclusions unreliable. A common piece of industry advice is to “review your own trade records repeatedly and identify your trading patterns.” The real challenge behind that advice is an engineering problem: trade records are the only truthful log of your behavior, yet they sit inside brokerage software as spreadsheet files that can be neither queried nor statistically analyzed.
To turn them into an asset you can validate repeatedly, you need three format conversions: from the spreadsheet exported by trading software, to a machine-friendly intermediate format that models can parse, to a structured storage layer for market and trade data, and finally to a runnable backtesting and attribution workflow. The original author’s approach is worth borrowing: with a budget of only about twenty yuan, the goal was not a comprehensive platform but a minimal closed loop that gets the whole chain working.
2. Step 1: Convert Spreadsheet Files into a Model-Friendly Intermediate Format
Trading software usually exports spreadsheet files. Passing such files directly to an LLM often leads to incomplete reading—merged headers, blank rows, thousands separators, and mixed date formats can all cause the model to “see” only part of the data and then generate incorrect analysis code.
A pragmatic approach is to normalize the format first: convert the spreadsheet into a plain-text markup format (for example, a structured Markdown table) before handing it to the model. This has three benefits. First, column names and sample rows are visible at the same time, so the model judges field meanings more accurately. Second, the conversion process itself exposes dirty data, making it easier for you to clean it up front. Third, plain text consumes less context, so long tables can be fed in segments.
After conversion, do a manual check and extract the instrument names separately for verification. This step may look redundant, but it prevents a large amount of rework later: once the instrument list is wrong, everything downstream—fetching, loading, and backtesting—goes wrong too.
3. Step 2: Break a Large Request into Verifiable Steps
The original text highlights a key habit: in the past, the author described the entire requirement at once, and the output easily got out of control; after switching to thinking the workflow through and having the model execute it step by step, stability improved noticeably. This is the core methodology for using AI coding tools.
The reason is that personalized tasks carry many implicit constraints (field definitions, deduplication rules, exception handling, directory structure). Describing everything at once inevitably leaves gaps, and the model can only guess—guesses that compound layer by layer. Step-by-step execution is essentially about setting a verifiable checkpoint at each step.
Recommended breakdown order:
- Extract and confirm the instrument list;
- Design the database schema, specifying primary keys and indexes;
- Implement market-data fetching with progress output;
- Load into the database and run integrity checks (row counts, date ranges, missing trading days);
- Compute trading-behavior metrics (turnover, holding period, P&L distribution);
- Generate backtesting and attribution reports.
Each step’s prompt should contain four elements: goal, input paths, constraints, and acceptance criteria. Example:
Goal: Build a local market database and fetch daily and intraday data for the specified instrumentsInput: The instrument list confirmed in the previous step; API documentation (contains access credentials, do not share externally)Constraints: The database must be well-structured and extensible; market tables split by period; print progress and retry on failure during fetchingAcceptance: Output the record count and start/end dates for each instrument, and list missing trading days
4. Step 3: Storage Design and Fetching Strategy for Market Data
Data loading is the most underestimated part. A few general principles are recommended:
- Use a surrogate key plus a business unique key (instrument, period, timestamp) as dual constraints to keep repeated fetches idempotent;
- Separate market tables from metadata tables, with instruments, periods, and adjustment methods in their own dimension tables for easier extension;
- Standardize time fields to standard types with timezone semantics to avoid local-time ambiguity;
- Index frequently queried (instrument, time) combinations;
- Keep a raw layer and a processed layer, and avoid doing too much computation at load time.
Example schema:
CREATE TABLE daily_bar (id BIGSERIAL PRIMARY KEY,symbol VARCHAR(16) NOT NULL,trade_date DATE NOT NULL,open NUMERIC(12,3),high NUMERIC(12,3),low NUMERIC(12,3),close NUMERIC(12,3),volume BIGINT,amount NUMERIC(18,2),adjust_type SMALLINT DEFAULT 0,UNIQUE (symbol, trade_date, adjust_type));CREATE INDEX idx_daily_symbol_date ON daily_bar (symbol, trade_date);
For the fetching strategy, prioritize a data API you already have quota for, and keep credentials in local configuration or environment variables—never in code or prompts. On rate limits, back off and retry. Intraday data is large, so fetch it in batches with resumable, checkpoint-based loading.
5. Step 4: Make the Execution Process Observable
One line in the original prompt is critical: you should see concrete progress during fetching. This is the dividing line between turning “black-box generation” into “collaborative development.” Observability has at least three layers:
- Task layer: which instrument is being processed, plus success and failure counts;
- Data layer: rows written this run, rows skipped, and elapsed time;
- Exception layer: failure reasons and retry counts, for later diagnosis.
In some AI coding tools, long tasks may appear to “hang,” producing no output for a long time. The response is not to wait but to actively abort and restart from the checkpoint; splitting long tasks into small batches also significantly reduces the chance of getting stuck. Note that this behavior depends on the runtime environment and task granularity and should not be simply attributed to model capability.
6. Step 5: From Data to Conclusions—Backtesting and Attribution
Analysis is only meaningful with a clean database. For personal trading reviews, focus on three categories of metrics. First, behavior metrics such as average holding days, turnover rate, and the ratio of winning to losing trades. Second, return metrics such as cumulative return, maximum drawdown, and per-trade P&L distribution. Third, discipline metrics such as the share of unplanned trades and the proportion of chasing-high buys.
Backtesting has two common traps: look-ahead bias (using information not available at the time) and survivorship bias (an instrument pool containing only stocks that still exist). Avoid them by slicing strictly by time, using only data available as of the decision point, and retaining records for delisted instruments.
7. Conclusion and Risk Notes
The original author’s final verdict was not optimistic, which is exactly what shows the value of the process: only when subjective impressions become verifiable numbers do conclusions become actionable. The technical essentials of the whole chain can be condensed into four sentences—normalize the format first, then break down the requirements, then load data with a proper schema, and finally make it observable and verifiable.
Note that the method described here is for historical data review and trading-behavior analysis and does not constitute any investment advice; historical backtest results do not represent future performance; model-generated code must be reviewed manually before running; and credential-related configuration should always stay local. If data volume or concurrency grows further, you can add object storage for cold-data archiving, a message queue for task decoupling, and a container platform for environment isolation, together with logging and monitoring/alerting services, to smoothly evolve this personal tool into a stable data pipeline.
