An Engineering Practice Guide to Trading Backtesting Analysis with LLMs
Many individual investors struggle to objectively evaluate their trading performance. This guide explores how to build a reproducible trading backtesting analysis system using Large Language Models (LLMs). It covers engineering practices including transforming unstructured trade records, decomposing tasks for LLMs, integrating market data, designing databases, handling exceptions, defining backtesting logic, and generating structured reports. By following a step-by-step approach rather than relying on free-form LLM generation, developers can build a reliable system to objectively analyze trading behaviors and outcomes.
1. Problem Background: From Subjective Reviews to Verifiable Analysis
Many individual investors experience noticeable fluctuations in their account profit and loss over time, but find it difficult to pinpoint whether the issues lie in stock selection, market timing, position management, or trading frequency. Traditional reviews often rely on memory and scattered screenshots, making conclusions susceptible to emotional bias. To form a more objective judgment, it is necessary to convert historical trading records into structured data and perform backtesting analysis combined with market data.
The difficulty of such a project lies not in “whether one can write code,” but in how to connect unstructured trading records, scattered market data, complex calculation logic, and final analysis reports into a stable pipeline. The value of Large Language Models (LLMs) and intelligent programming tools is to help developers quickly complete requirement decomposition, code generation, data cleaning, and report organization. However, the prerequisite is that the user must have a clear design of the process and cannot let the model “freely play” all at once.
2. Overall Goal: Building a Reproducible Trading Analysis System
A viable trading backtesting analysis system typically consists of four layers:
- Data Layer: Stores trading records, market data, basic configurations, and intermediate results.
- Integration Layer: Responsible for fetching market data from external sources and completing field mapping and cleaning.
- Computation Layer: Executes analysis of metrics such as return statistics, drawdown calculations, win rate, and holding period.
- Presentation Layer: Outputs structured reports, including key metrics, charts, and conclusion summaries.
The ultimate goal of the project is not to provide advice on “what to buy or sell,” but to answer several engineering questions: Do historical trades have a stable pattern? Which trades contributed to the main returns? Which trades caused the main drawdowns? If re-executed according to a certain rule, how would the results change?
3. Data Preparation: Converting Trade Records to Machine-Readable Formats
The first step is to export personal trading records. Most trading software can export spreadsheets or text files, but handing them directly to an LLM is not reliable. This is because table files may contain merged cells, hidden columns, inconsistent date formats, and inconsistent descriptions of trade directions. If the model reads them incompletely, subsequent analysis will be biased.
A more reliable approach is to perform a format conversion first, transforming the original tables into structured text. This is convenient for both manual inspection and programmatic parsing. During conversion, focus on the following fields:
- Trade date
- Security code or name
- Buy/Sell direction
- Volume
- Execution price
- Transaction amount
- Commission fees
- Stamp duty or other fees
- Execution time
After conversion, manually spot-check a few rows of data to confirm that fields are not misaligned. This step seems simple but can significantly reduce rework later.
4. Task Decomposition: Avoid Letting the Model Do Everything at Once
In practical use, a common misconception is to give the complete requirement to the model all at once, such as “Please help me build a complete backtesting system.” This approach easily leads to out-of-control output: chaotic code structure, missing dependencies, logical jumps, or even unexecutable pseudo-code.
A more reliable method is to break the task into multiple small steps:
- Extract the list of involved securities from the trading records.
- Manually confirm whether the security codes and names are accurate.
- Design the local database table structure.
- Write the market data fetching module.
- Add progress output and exception retries.
- Write the metric calculation module.
- Generate analysis reports and charts.
After each step is completed, perform small-scale validation. For example, first fetch daily bar data for a small number of securities to confirm that fields, date ranges, and storage results are correct, then expand to the full dataset. This allows quick localization if issues arise.
5. Market Data Integration: Document, Test, Then Encapsulate
Backtesting analysis relies on historical market data. When integrating external market data, it is not recommended to let the model directly “guess the API.” A more reasonable approach is to first organize the API documentation, clarifying the data scope, field meanings, call frequency, and return structure, and then let the model write test scripts.
A typical integration process is as follows:
- Collect the API documentation for market data.
- Organize the documentation locally.
- Have the model generate test requests one by one.
- Check whether the returned fields are complete.
- Record available and unavailable APIs.
- Encapsulate a unified data fetching function.
The illustrative code is as follows:
def fetch_daily_bars(symbol, start_date, end_date):# Call the market data APIraw = request_daily(symbol, start_date, end_date)return normalize_bars(raw)def normalize_bars(raw):result = []for item in raw:result.append({"symbol": item["code"],"date": item["trade_date"],"open": float(item["open"]),"high": float(item["high"]),"low": float(item["low"]),"close": float(item["close"]),"volume": float(item["vol"]),})return result
The key here is not the code itself, but the engineering habit of “test first, then encapsulate.” Only by confirming that the API is available can subsequent backtesting have a stable foundation.
6. Local Database Design: Standardized, Extensible, and Trackable
Once the data is fetched, it needs to be stored in a local database. The table structure design should meet at least three requirements: clear fields, unique primary keys, and easy extensibility.
For example, you can design a trade record table, a daily bar table, and a task log table:
CREATE TABLE trade_record (id INTEGER PRIMARY KEY,symbol TEXT,trade_date TEXT,direction TEXT,price REAL,quantity INTEGER,amount REAL,fee REAL);CREATE TABLE daily_bar (symbol TEXT,trade_date TEXT,open REAL,high REAL,low REAL,close REAL,volume REAL,PRIMARY KEY(symbol, trade_date));CREATE TABLE task_log (id INTEGER PRIMARY KEY,task_name TEXT,status TEXT,message TEXT,created_at TEXT);
Here, daily_bar uses the security code and trade date as a composite primary key to avoid duplicate writes. task_log is used to record data fetching progress and exception information for future troubleshooting.
If you need to add intraday data, financial data, or metric results in the future, you only need to add new tables or extend fields without overturning the existing structure.
7. Progress Feedback and Exception Handling: Keeping Long Tasks Under Control
Data fetching is often a time-consuming operation. If a program runs for hours without any output, it is difficult for the user to determine whether it is running normally or has stalled. Therefore, adding progress feedback to the script is essential.
You can output information similar to this in the console:
[1/50] Processing security A, 120 daily bars[2/50] Processing security B, 98 daily bars[3/50] Security C fetch failed, preparing to retry
At the same time, a retry mechanism should be set up. For example, if a single request fails due to network fluctuations, it can retry after waiting a few seconds; if failures are continuous, log the error and skip it to prevent the entire task from being interrupted.
The pseudo-code is as follows:
for i, symbol in enumerate(symbols, start=1):print(f"[{i}/{len(symbols)}] Processing {symbol}")try:bars = fetch_daily_bars(symbol, start, end)save_bars(bars)except Exception as e:log_error(symbol, str(e))
This design can significantly improve the operability of the system.
8. Backtesting Logic: Avoiding Look-Ahead Bias and Survivorship Bias
Backtesting is not simply running through historical data; it is about simulating a real trading environment as closely as possible. Common issues include:
- Look-ahead bias: Using data that was not available at the time.
- Survivorship bias: Only analyzing securities that currently exist, ignoring delisted or suspended ones.
- Ignoring costs: Not accounting for commissions, stamp duty, and slippage.
- Overly ideal execution assumptions: Assuming trades can always be executed at the closing price.
- Data alignment errors: Inconsistent trading dates across different securities.
Therefore, before calculating, you should unify the timeline and clarify execution rules. For example, you can set a signal to be generated after the close on day T, and executed at the open on day T+1; or you can add a fixed slippage percentage. The clearer the rules, the more reproducible the results.
9. Metric Design: Characterizing Trading Behavior with Data
The analysis report should not only show the total return but also include multi-dimensional metrics:
- Cumulative return
- Annualized return
- Maximum drawdown
- Win rate
- Profit/loss ratio
- Average holding days
- Trading frequency
- Largest single-trade loss
- Largest single-trade profit
- Concentration of return contribution
For example, if a few trades contribute the majority of the returns, it indicates the result may rely on random events; if the maximum drawdown is much higher than expected, it indicates insufficient risk control; if the trading frequency is high but returns are limited, it may indicate overtrading.
The illustrative calculation logic is as follows:
total_return = (final_value - initial_value) / initial_valuemax_drawdown = calculate_max_drawdown(equity_curve)win_rate = winning_trades / total_tradesprofit_loss_ratio = avg_win / avg_loss
These metrics collectively form an objective description of trading behavior.
10. Report Output: From Code Results to Readable Conclusions
The final report should be both machine-readable and human-readable. It can output three types of content:
- Summary Conclusions: Summarize the main findings in a few sentences.
- Metric Tables: List key data such as return, drawdown, and win rate.
- Chart Analysis: Equity curve, drawdown curve, and trade distribution charts.
Report generation can be assisted by the model, but it must be based on real calculation results, and the model cannot fabricate conclusions. The recommended approach is: the program first calculates metrics and saves them as structured results, and then the model generates explanatory text based on the results.
For example:
The cumulative return for this backtest period is 12.4%, with a maximum drawdown of 18.7%, a win rate of 46%, and a profit/loss ratio of 1.8.The main profit comes from 3 trades, accounting for 61% of the total return.The trading frequency is high, but the average holding time per trade is relatively short.
Such conclusions are more valuable than vague generalizations.
11. Common Issues and Coping Strategies
In practice, you may encounter the following issues:
- Model response interruption: Break tasks into smaller pieces to reduce single-turn context length, and save intermediate results.
- Generated code is unexecutable: Ask the model to output the structure explanation first, then generate code segment by segment.
- Inconsistent data fields: Establish a field mapping table first, then clean uniformly.
- API rate limiting: Add request intervals and failure retries.
- Irreproducible results: Fix random seeds, and save the original data and calculation script versions.
- Credential leakage risk: Do not write keys into the code; use environment variables or local configuration files, and restrict access permissions.
12. Conclusion: LLMs are Assistants, Engineering is the Core
With the help of LLMs and intelligent programming tools, individual developers can build trading backtesting analysis systems faster, but what truly determines the quality of the project is still the ability to decompose requirements, govern data, validate processes, and explain results. The most reliable path is not to let the model generate a complete system at once, but to break complex tasks into verifiable small steps: organize trading records first, then integrate market data, and subsequently complete database storage, calculation, and report output.
When the data pipeline is clear, the calculation logic is reproducible, and the metric definitions are explicit, backtesting reports can truly help users understand their trading behavior, rather than creating an illusion of “precise prediction.”
