Building a Trading Backtesting System with AI Coding Tools
This article explores how to leverage AI coding tools to transform unstructured trading statements into a robust, repeatable backtesting analysis system. It details a five-stage pipeline architecture, step-by-step prompt engineering strategies, database design for idempotent data fetching, and best practices for observability and evaluation. By focusing on verifiable steps and explicit constraints, developers can turn emotional trading losses into a sustainable engineering asset.
1. The Problem: Trade Logs as Data Assets
Most retail investors only realize after consecutive losses that they know that they lost money, but not where they lost it. Was it a failed stock-picking strategy, a mismatched holding period, or frequent trading costs eating into profits? The only reliable input to answer these questions is not post-trade memory, but the historical trade details exported from brokerage software. It records the time, price, quantity, and fees of every transaction, serving as the raw material for building a trading behavior profile.
The technical problem discussed in this article is: how to use AI coding tools to engineer a non-structured trading statement into a repeatable backtesting analysis system. The key here is not the power of the model, but whether the process is broken down into “verifiable steps”.
2. Overall Architecture: A Five-Stage Pipeline
It is recommended to break the system into five stages with clear boundaries, where each stage has deterministic inputs and outputs and can be rerun independently:
- Export Layer: Export table files (usually spreadsheets) from trading software.
- Normalization Layer: Convert spreadsheets into a plain text structure (Markdown tables) that LLMs can easily parse, performing field alignment and data cleaning.
- Data Layer: Use the ticker list to fetch daily and intraday market data, storing it in a local database.
- Calculation Layer: Match buy/sell pairs, calculate individual trade PnL, and aggregate metrics like win rate, profit-loss ratio, and holding period distribution.
- Report Layer: Output structured analysis reports and charts, retaining a reproducible parameter snapshot.
The reason for introducing the “spreadsheet to Markdown” step is that in practice, directly feeding binary spreadsheets to a model often causes row/column misalignment, value truncation, and summary rows being mistaken for details. Converting to plain text tables clarifies field boundaries, significantly improving the model’s data reference accuracy.
3. Step-by-Step Prompting: From Vague Requests to Verifiable Tasks
A repeatedly proven experience is: do not describe personalized, long-chain tasks all at once. Think through the process first, then let the tool execute and confirm step-by-step.
Step One does only one thing: extract all ticker names from the trade log and deduplicate them for manual review. This step costs very little but prevents all subsequent errors. If the ticker list is wrong, the market data will be wrong, and the backtest conclusions will be meaningless.
Step Two provides a constrained data task. The prompt should include four elements: goal, data source priority, storage requirements, and observability requirements. Example:
Goal: Build a trading backtest analysis system. Currently, execute only the "market data fetching" step.Ticker List: Use my confirmed list. Do not add or remove items.Data Source: Prioritize my authorized financial data API. Credentials are in the local document. Do not hardcode them.Storage: Write to a local database. Table schemas must be standard, extensible, and contain primary keys and unique constraints.Observability: Print the fetching progress and success/failure counts for each ticker in real-time. Failures must be retryable.
The value of this approach is minimizing the model’s room for free interpretation, ensuring each output can be manually verified.
4. Data Layer Design: Schema First, Fetch Logic Second
For the local database, a lightweight relational database is recommended. The core consists of three tables: instrument dimension, market data fact, and fetch task log. The key design point is unique constraints to ensure idempotency, so repeated executions do not generate dirty data.
CREATE TABLE instrument (ts_code TEXT PRIMARY KEY,name TEXT NOT NULL,list_date TEXT);CREATE TABLE daily_bar (ts_code TEXT NOT NULL,trade_date TEXT NOT NULL,open REAL, high REAL, low REAL, close REAL,volume REAL, amount REAL,PRIMARY KEY (ts_code, trade_date));CREATE TABLE fetch_log (id INTEGER PRIMARY KEY AUTOINCREMENT,ts_code TEXT, freq TEXT, status TEXT,rows_ok INTEGER, err_msg TEXT, ts TEXT);
The fetch logic follows “batching + rate limiting + resumable execution”:
for code in codes:if already_done(code, freq="daily"): # Idempotent skipcontinuetry:df = fetch_daily(code, start=START, end=END)upsert_many("daily_bar", df) # Dedup via unique constraintslog(code, "ok", len(df))except Exception as e:log(code, "fail", 0, str(e)) # Log failures for isolated rerunssleep(0.4) # Respect API rate limits
5. Observability and Solving the “Freeze” Problem
A typical anomaly encountered in practice is long task silences with no output. Regardless of whether the root cause is in the toolchain or the API side, the engineering solution is the same: make long tasks have heartbeats, timeouts, and recoverability.
- Log before and after processing each ticker to form a heartbeat.
- Set timeouts for single requests; treat timeouts as failures and route them to a retry queue.
- Write all statuses to
fetch_log; on restart, only processfailand incomplete items. - Execute long tasks in batches, keeping single batch durations within manually observable limits.
6. Backtesting and Evaluation: Don’t Let Conclusions Outrun Data
Once data is ready, the calculation layer must define specific metrics, otherwise conclusions are incomparable:
- Matching Rules: FIFO or netting by ticker—this must be clearly stated in the report.
- Cost Modeling: Commissions, transaction taxes, transfer fees, and slippage must be explicitly modeled. High-frequency trading is extremely sensitive to costs.
- Metric Combination: Win rate, profit-loss ratio, average holding days, max drawdown, and monthly return distribution should be evaluated simultaneously. Relying solely on win rate is highly misleading.
- Out-of-Sample Testing: Reserve a recent period that does not participate in parameter selection to avoid overfitting.
- Parameter Snapshot: Record the data cutoff date, parameters, and code version in the report to ensure reproducibility.
7. Handling Model-Generated “Conclusions”
The most interesting output of such a system is often not the charts, but the model’s judgment based on the data. However, boundaries must be clear: models excel at statistical description and pattern induction, not causal inference or future prediction. The reliable approach is to require the specific numbers and sample sizes underpinning its conclusions for manual review. Any conclusion that cannot be traced back to original records should be downgraded to a hypothesis.
8. Practice Checklist
- Solidify the ticker list before starting any data tasks.
- Convert spreadsheets to plain text structures before feeding them to the model.
- Define table schemas first; use unique constraints to ensure idempotency.
- Long tasks must have heartbeats, timeouts, and failure logging.
- Explicitly model costs and slippage; preserve out-of-sample intervals.
- Conclusions must be traceable to data; archive parameters and versions with the report.
By following this pipeline, the real gain is not an evaluation of a specific model’s capability, but turning a one-time “emotional loss” into a sustainable, iterative engineering asset. This methodology remains valid regardless of the specific AI coding tool used.
