How to Evaluate LLMs in Building a Quantitative Backtesting System
This article explores how to assess the real capabilities of large language models when building a personal trade-history backtesting system. It covers goal definition, trade record normalization, staged development, market data interface validation, local database design, backtesting calculation standards, and the strengths and limitations of LLMs—concluding that models should serve as collaborative developers rather than decision makers.
In recent years, large language models (LLMs) have evolved from chat tools that answer questions into development assistants capable of participating in requirement analysis, code writing, data processing, and result interpretation. For individual investors, a natural application is combining historical trade records, market data, and trading rules to build an analysis system for review and backtesting.
However, the real challenge of such projects is not “getting the model to write a piece of code.” It lies in ensuring data completeness, correct calculation logic, reproducible results, and avoiding the mistake of treating model-generated conclusions as reliable investment advice. Using a “personal trade record backtesting system” as an example, this article discusses how to evaluate the practical capabilities of LLMs in this type of task.
1. Define the Project Goal First: Review, Not Prediction
Individual investors often ask questions like:
- Were my past trades profitable or loss-making overall?
- Which types of trades generated most of the profit?
- Are there fixed patterns in holding periods, entry timing, and exit timing?
- Would historical results have been more stable if a specific set of rules had been followed?
- Does the account drawdown come from a few individual trades or from an overall strategy flaw?
These questions are fundamentally about historical review and strategy backtesting, not about having the model predict future market movements.
Therefore, the first step is not writing programs but defining the analytical boundaries. The system should answer “what happened in the past” and “what would have happened historically under a given set of rules”—it must not package backtest results as promises of future returns. Especially in financial scenarios, every conclusion needs to state the data range, transaction costs, slippage, trading suspensions, price-limit constraints, price adjustment method, and sample size.
A reasonably complete goal can be broken down into four layers:
- Reconstruct the actual trade records;
- Retrieve historical market data for the corresponding securities;
- Calculate returns and risks using a consistent methodology;
- Summarize trading behavior patterns from the statistical results.
2. Step One: Normalize the Trade Records
Most trading software can export spreadsheet files, but raw exports usually have many problems, such as:
- Inconsistent date formats;
- Security codes being interpreted as numbers, causing leading characters to be lost;
- Buy and sell records scattered across different fields;
- Commissions, stamp taxes, and transfer fees not listed separately;
- The same security being bought multiple times and sold in batches;
- Special records such as cancellations, partial fills, and share allotments mixed in.
If you hand the raw spreadsheet directly to an LLM for analysis, the model may read only part of the content, or make inferences based on superficial fields, ultimately producing results that look plausible but cannot be verified.
A more robust approach is to first establish a standardized intermediate format. Each executed trade can be converted into a structure like the following:
trade_idtrade_datesecurity_codesecurity_namesidequantitypriceamountcommissiontaxother_feeaccount
Here, side should clearly distinguish buy from sell, quantity should use the actual executed quantity, amount records the transaction value, and fee fields should preserve the original data as much as possible. If the original record lacks a piece of information, it should be marked as empty rather than letting the model guess.
In addition, data validation rules need to be established:
- Executed quantity must be greater than zero;
- Executed price cannot be negative;
- Sell quantity cannot exceed available holdings;
- Buy and sell timestamps must be sortable;
- Security codes must follow a unified format;
- The same trade must not be imported twice;
- Transaction amount should roughly equal quantity multiplied by price.
These validation tasks may look basic, but they are the prerequisite for the reliability of the entire system.
3. Step Two: Break Complex Tasks into Multiple Stages
When developing with LLMs, a common mistake is describing all requirements at once—for example, asking the model to simultaneously handle data reading, market data fetching, database design, backtesting calculations, chart rendering, and report generation. This tends to cause the following problems:
- The model ignores some requirements;
- Interfaces between generated code modules are inconsistent;
- The database schema changes frequently;
- Errors are hard to trace to the responsible stage;
- Later modifications trigger chain reactions.
A more reliable approach is a staged development process.
Stage 1: Identify and Confirm the Traded Securities
First, have the model extract security codes, names, trade counts, and trading date ranges from the trade records, then confirm them manually. Do not fetch market data or generate conclusions at this point.
The output can include:
| Code | Name | First Trade Date | Last Trade Date | Trade Count |
|---|---|---|---|---|
Manual confirmation matters because it prevents code identification errors. Similar security names, lost code formatting, or historical name changes can all lead to fetching the wrong data downstream.
Stage 2: Validate the Data Interfaces
Market data usually comes from one or more public data sources. Different sources may differ in field names, price adjustment methods, trading day definitions, and access limits, so you cannot assume every interface works out of the box.
You can ask the LLM to first generate an interface test program that verifies, item by item:
- Whether the connection works;
- Whether it can return data for a specified security;
- Whether it covers the target date range;
- Whether daily data includes open, high, low, close, and volume;
- Whether the granularity of minute-level data meets the requirements;
- Whether returned data contains duplicates, gaps, or anomalies;
- Whether the data source’s time coverage and access frequency meet actual needs.
After testing, produce an interface test report recording successes, failures, missing fields, and fallback options. Do not let the model fabricate data when an interface fails, and do not declare an entire data source unusable just because one request temporarily failed.
4. Step Three: Design an Extensible Local Database
For small-scale personal projects, a local relational database is usually sufficient. What matters is not the database type but whether the table structure is clear and the fields are traceable.
The data can be split into the following categories:
1. Security Master Table
Records basic information such as security code, name, market, listing status, and effective dates.
2. Daily Market Data Table
Records trading date, open, high, low, close, volume, turnover, and price-adjustment-related fields.
3. Minute-Level Market Data Table
If you need to analyze intraday entry and exit timing, store minute-level data separately to avoid mixing it with daily data.
4. Trade Record Table
Stores the user’s actual executed trades. All original fields should be preserved as much as possible for future auditing.
5. Data Fetch Log Table
Records request time, data source, security code, date range, number of rows returned, error messages, and retry counts.
6. Backtest Result Table
Records strategy name, parameters, sample range, return metrics, risk metrics, and run version.
Two issues deserve special attention in database design: uniqueness and re-runnability. Fetching data for the same security on the same date repeatedly should not create duplicate records; if the program is interrupted and restarted, it should resume from the last progress point rather than starting over.
5. Step Four: Backtesting Logic Must Define Its Conventions First
Many backtest results are distorted not because of syntax errors, but because the calculation conventions are unclear.
At minimum, the following must be defined in advance:
Return Calculation
A simple return is usually expressed as:
Return = (Ending Assets - Starting Assets) / Starting Assets
But real trading also deducts commissions, taxes, and slippage. Ignoring these costs tends to overstate the performance of high-frequency strategies.
Position Matching
For cases involving multiple buys and partial sells, you need to specify whether to use FIFO (first in, first out), weighted average cost, or calculation based on the actual account holding flow. Different methods affect how returns are attributed to individual trades.
Price Adjustment Method
When analyzing with historical prices, you must state whether forward-adjusted, backward-adjusted, or unadjusted prices are used. Inconsistent conventions between price data and trade records can lead to obvious errors.
Price Limits and Execution Constraints
Historical backtests cannot assume all orders get filled. You should also consider:
- Whether a buy is actually executable when the price hits the upper limit;
- Whether a sell is actually executable when the price hits the lower limit;
- Whether trading is allowed during suspensions;
- Whether minute-level data is sufficient to support execution at a specified price;
- Whether slippage should be added to execution prices.
Capital and Position Sizing
The backtest model should also define initial capital, maximum position per security, whether margin is allowed, whether same-day round-trips are allowed, and how orders are handled when funds are insufficient.
Only when these rules are fixed in advance do results become comparable.
6. Strengths and Limitations of LLMs in the Development Process
LLMs can indeed significantly improve development efficiency in this type of project, mainly in three ways.
First, they can quickly generate foundational code for data cleaning, field conversion, database table creation, and interface testing. Second, they help developers organize requirements, breaking vague ideas into executable steps. Third, they are well suited to generating statistical reports that turn metrics like returns, win rate, maximum drawdown, and holding period into readable prose.
But their limitations are equally clear.
1. Possible “Freezing” or Long Periods of Unresponsiveness
Complex tasks often involve multiple rounds of file reading, code execution, and error fixing. The model may stay stuck on a step for a long time with no visible progress. The solution is to break tasks into smaller pieces and require each stage to output an explicit status, such as “how many records have been read,” “which securities have been completed,” and “what the current failure cause is.”
2. Possible Data Hallucination
When an interface returns empty results or fields are missing, the model may infer results based on common formats. All critical data must be actually read by programs and verified through logs or sampled records.
3. Possible Neglect of Edge Cases
A model can write the main flow but easily overlook suspensions, corporate actions, duplicate trades, partial fills, and transaction fees. Test cases therefore must not cover only normal scenarios—they should deliberately include abnormal records.
4. Possible Confusion of Statistical Correlation with Causation
For example, a high historical win rate for a certain type of trade does not prove the pattern is effective. Sample size, market regime, and survivorship bias all affect conclusions. Model-generated narrative reports must be reviewed by humans and must never be used directly as the basis for investment decisions.
7. How to Evaluate a Model’s Real Capability for This Work
Evaluating whether a model is suitable for financial data projects should not be based solely on whether it can generate code. It should be judged comprehensively across the following dimensions:
- Whether requirement decomposition is clear;
- Whether it consistently adheres to confirmed fields and rules;
- Whether it handles abnormal data correctly;
- Whether it can explain the source of every calculated metric;
- Whether it proactively exposes uncertainty;
- Whether the generated code is easy to test and maintain;
- Whether it can retain context and complete fixes after errors;
- Whether the final results can be reproduced manually.
If a model only quickly produces an interface but cannot explain where the data comes from, how returns are calculated, or how errors are handled, then it is more of a prototype generator than a reliable analysis assistant.
8. Conclusion: Treat the Model as a Collaborator, Not a Decision Maker
LLMs are well suited to participating in the construction of personal trade review systems, but their value lies mainly in improving the efficiency of information organization and software development—not in replacing data validation, financial logic review, and investment judgment.
The recommended workflow is:
- Humans define the goals and rules;
- The model assists in task decomposition;
- Programs handle data reading and computation;
- Logs record the process;
- Tests verify correctness;
- Humans handle interpretation and final decisions.
If you let the model complete everything in one pass, the project may quickly yield a result that “looks like it runs,” but you will struggle to prove whether that result is trustworthy. In contrast, a process of small iterations, item-by-item confirmation, rollback capability, and auditability significantly reduces error risk—even if development is slightly slower.
As for dramatic judgments a model might make based on trading results, treat them as exaggerated risk warnings rather than professional conclusions. A truly valuable answer should tell you which trades caused the losses, which rules fail most easily, which data is still insufficient, and how the next round of review should be improved.
