Building a Personal Stock Backtesting System with LLMs: A Practical Guide
This guide describes how an individual investor used large language models to build a personal stock trading backtesting system. It covers the project motivation, a five-layer architecture, converting trade records from Excel to Markdown, a step-by-step prompting workflow, interface availability testing, common pitfalls, and observations on the Pro and Flash model versions.
1. Project Background: Why Build a Backtester
Many individual investors face the same problem. Their account returns swing up and down, losing trades outnumber winning ones, and they cannot pinpoint what is going wrong. A common practice in the industry is to review one’s own historical trade settlement records (transaction statements exported from the brokerage software) and extract quantifiable trading patterns. Manual review, however, is highly subjective and based on a small sample, so it is hard to reach objective conclusions.
The natural next step is to structure the trade settlement data, connect it to historical market data, and run a systematic backtest with a program. This kind of task is highly personalized and involves a long processing chain, which makes it a good test case for how well current large language models collaborate on real engineering work. A major model provider recently released a new generation of models: a Pro version focused on deep reasoning and a Flash version focused on lightweight, fast responses. This project was a chance to run a complete hands-on test with both.
2. Overall Technical Design
Before starting, define the system architecture clearly. Otherwise, letting the model “figure it out freely” from the start can quickly lose control.
- Data input layer: An Excel file of trade settlement records exported from the trading software.
- Data preprocessing layer: Convert the Excel file into structured text that is easier for an LLM to process.
- Market data layer: Pull daily and minute-level data for the relevant stocks through a public market data interface, and store it in a local database.
- Backtesting layer: Replay the trading activity against historical data, and calculate metrics such as win rate, profit-loss ratio, and maximum drawdown.
- Report layer: Generate an objective analysis report to help identify trading patterns.
The key to this layered design is that the input and output of each step must be clear and controllable. This directly determines how efficiently the work proceeds with the LLM.
3. Key Steps
3.1 Preprocessing Trade Records: Why Convert Excel to Markdown
Trading software usually exports records as Excel files. In practice, when an LLM reads and analyzes an Excel file directly, it can miss or misread some rows and columns, because the code that parses the file may not handle boundary cases strictly enough. Table data cannot tolerate any omissions. If a single trade is missing, the backtest conclusions are unreliable.
A proven approach is to first convert the Excel file into a Markdown table. Markdown is plain text, so the model reads it line by line with complete context and less ambiguity. Open-source projects that convert files to Markdown are already mature and inexpensive to deploy, and the converted output is easier to spot-check manually.
3.2 Break Down the Task: Proceed Step by Step, Not All at Once
This was the most important lesson from the project. Many people give an LLM the full requirements at once and wait for a finished product. For highly personalized tasks, this approach easily gets out of control. The model may misunderstand the business context, and errors compound over a long chain of steps.
A safer pattern is to move in small steps and confirm each stage:
- Step 1: Have the model extract the full list of stock codes from the trade records, then review the list manually. This looks simple, but every later data pull depends on it.
- Step 2: After confirming the list, have the model write the data retrieval module. It should store daily and intraday data in a local database, and design a “standardized, extensible table structure.”
- Step 3: Once the data is ready, write the backtesting logic.
An example prompt for Step 2 could look like this:
I want to build a stock trading backtesting analysis system.Step 1: Read the local market data API documentation(path: /home/xxx/Desktop/tushare_api_doc.md),and prioritize the daily and minute-level data interfaces.Step 2: Write a data retrieval module that stores the full historicaldata for the following symbols in a local database.The table schema must be standardized and extensible.Step 3: Print progress information in real time during the retrievalso I can follow the execution status.
A few details are worth noting:
- Have the model read the documentation before writing code. Giving the model the data interface documentation lets it understand the API parameters more accurately than a manual summary would.
- Require progress output. A long task without intermediate feedback makes troubleshooting very costly when something fails.
- Reference sensitive information such as API tokens from a local file, rather than pasting it into the conversation. This is a basic security habit.
3.3 Interface Availability Testing: Test Before Use
Market data interfaces vary widely. Rate limits, field coverage, and historical depth all differ from one interface to another. A practice that has proven effective:
- Have the model organize the interface documentation into a local Markdown file for repeated lookup.
- Have the model write a separate test script for each interface to be used.
- Run each test and compile an interface availability test report.
- In later development, use only the interfaces the report confirms as working.
In essence, this moves interface contract verification to the front. It avoids discovering midway through backtesting development that an interface is unusable, which would force a rewrite.
4. Pitfalls and Solutions
1. The model sometimes hangs. During repeated runs, the model occasionally stopped responding for long periods. Manually interrupting and rerunning the task resolved it. This may be related to stability during periods of high concurrent load. Solution: set timeouts and checkpoint-based resume for long-running tasks, and persist key intermediate results, such as the symbol list and the data already written to the database, so that a single failure does not force a full rerun.
2. Errors accumulate over long task chains. A backtest involves data, logic, and statistics. A silent error in any stage can distort the conclusions. Solution: require the model to output intermediate validation results at each stage. For example, after data retrieval, have it report the row count and time range for each symbol. Check these manually before moving on to the next step.
3. Limits on interpreting backtest results. A personal trade settlement record is a small sample. Backtest results only reflect how the past trading behavior performed in a specific market environment. They cannot be directly extrapolated into a strategy that will work in the future. The most sensible way to frame this project is to treat the LLM as an objective analysis tool, not a tool for predicting profits.
5. Observations on the Two Model Versions
In this project, the lightweight Flash-class model suited high-frequency interaction. It handled task breakdown confirmation, code snippet generation, and small refactors, with fast responses and smooth iteration. The deep-reasoning Pro-class model was better suited to complex logic design, such as the overall architecture of the backtesting engine and reviewing the completeness of edge cases. A practical approach is to use the lightweight model for daily iteration and the reasoning model for a second review at key design points. This balances cost and quality.
6. Summary
This project required a modest amount of work, but it demonstrates a general method for building personalized tools with an LLM:
- Design the layers first, then execute step by step. Do not hand over all requirements at once.
- Verify the data first. Convert file formats and test interface availability before anything else.
- Build in intermediate outputs and manual checkpoints at every step to control error accumulation.
- Keep realistic expectations about model capabilities. An LLM is an efficient engineering assistant, but responsibility for business judgment and interpreting conclusions stays with the person.
For developers, the real value of an LLM is not that it does the thinking for you. Its value is that it turns a process you have already worked through into a working system quickly and reliably.
