Building a Personal Stock Trading Backtest System with LLMs: From Data to Reports
This article presents a practical workflow for using large language models to build a personal stock trading backtest system. It covers converting trade confirmations into Markdown, extracting tickers, pulling historical daily and intraday market data, designing a database, adding progress visibility, and generating a backtest report. It also shares engineering lessons on small-step prompting, feeding API documentation to the model, human verification, retryable design, and checkpoint-based data jobs.
1. Project Origin: Why Build a Backtest System?
Since the beginning of the year, the returns in my personal stock trading account have been volatile, with more losses than gains. Recently, I repeatedly came across a piece of advice from professional traders: review your own trade confirmations over and over, and extract a trading pattern that belongs to you. That advice struck a chord. Instead of trading by feel, why not place historical trades into complete historical market data and run an objective backtest? Let the data speak and show whether my trading pattern is an effective strategy or just random losses.
I also still had some credits left on a model platform from trying out a newly released version. I decided to use them for a small project and test how a newer-generation LLM performs on a real engineering task. That is how this dual experiment—testing the model and reviewing my trading—began.
The short version: after running the whole workflow, the model’s analysis of my trade confirmations was quite blunt. Based on the statistical inference from the backtest, my trading habits are likely to lose money over the long run. It was uncomfortable to read, but it was a valuable technical practice.
2. Overall Technical Design
The project goal was clear: read trade confirmations → structure them → pull historical market data for the tickers → backtest according to actual buy and sell timestamps → generate an objective analysis report.
Technically, the project had four steps:
- Data preparation: Export trade confirmations from brokerage trading software in Excel format and convert them to Markdown so the LLM can understand them more reliably.
- Ticker extraction: Ask the LLM to extract the list of stock names and codes from the trade confirmations, then verify the list manually.
- Market data retrieval: Call public market-data APIs to fetch daily and intraday data, then store it in a local database.
- Backtest analysis: Match actual trades along the timeline, calculate profit/loss, win rate, and other metrics, and output a report.
The workflow looks simple, but each step has details worth discussing.
3. Step 1: Structuring the Trade Confirmation Data
3.1 Why Convert the Data to Markdown?
Trade confirmations exported from trading software are usually Excel files. Letting an LLM read Excel directly has a common problem: when calling a code interpreter’s data-analysis function, the model does not always read all the data completely. It may miss columns, misidentify data types, or handle merged cells incorrectly. I ran into this in a similar analysis before: the AI’s statistics did not match the actual data, and it took a while to discover that data had been lost during reading.
So I took a different approach this time: convert the Excel file to a Markdown table first. Markdown is plain text with a clear structure and intuitive column meanings. When the model reads it, the result does not depend on the behavior of a parsing library, and understanding accuracy improves significantly. Open-source document conversion solutions are already available, and a document conversion service can be deployed to process files in batches. The specific tool name is not important here; the idea is general.
3.2 Data Desensitization Advice
One practical reminder: trade confirmations contain real account information and cash flows. Before sending them to any cloud-based model, desensitize the data first. Remove sensitive fields such as names, account numbers, and cash balances, and keep only the fields required for backtesting: date, ticker code, buy/sell direction, price, and quantity. This protects privacy and reduces irrelevant information that could distract the model.
4. Step 2: Key Practices for Getting the Model to Pull Data
4.1 Do Not Give the Model Every Requirement at Once
I accessed the model through an AI coding tool configured to call the API. I used a lightweight, fast model version suitable for high-frequency coding tasks. Here I should mention an important change in my personal habits.
Early on, I used to give the model every requirement in one long stream and ask it to finish everything in one go. The result was often uncontrolled: bloated code structure, logic that drifted from the goal, and errors that were hard to locate. Later I settled on a lesson: for customized tasks, rather than letting the model improvise freely, think through the workflow yourself first and then direct the model step by step.
For the first step of this project, for example, I gave only one small task:
Please extract all stock names and codes involved in trades from the trade confirmation data.Output a deduplicated list and annotate the number of trades for each stock.
After receiving the result, I manually checked it once to confirm the extraction was correct before moving to the next step. This “small steps plus human verification” mode adds a few rounds of dialogue, but every round produces verifiable output. Overall efficiency is actually higher.
4.2 A Real Experience: The Model’s “Hanging” Behavior
One phenomenon worth recording: during several attempts, the model appeared to hang. After a request was sent, there was no response for a long time. I handled it by interrupting manually and running it again, and the retry returned normally very quickly. This was most likely server-side fluctuation shortly after a new version was released. In daily use, waiting or retrying usually solves similar cases. For engineering work, keep this in mind and make sure critical tasks have retryable idempotent design.
4.3 Example Prompt for Pulling Market Data
The second step was pulling historical market data. I had a market-data service account with credits, so I preferred a credit-based API. The prompt I gave was roughly as follows:
I want to build a stock buy/sell backtest analysis system. The first step is to pull all daily and intraday data for the stock list above. Please:1. Use the stock list above as the ticker list;2. Refer to the API documentation in the local directory (it contains my token);3. Write a retrieval program and store the data in a local database;4. Design the database schema to be standardized and extensible;5. Output concrete progress during retrieval so I can understand the execution status at any time.
Several points in this prompt were deliberately designed and deserve explanation:
- Specify the API documentation path: Let the model read local documentation instead of inventing APIs from “memory.” This significantly reduces hallucinations. A model’s memory of API parameters is often outdated or mixed up, so feeding it authoritative documentation is the safest approach.
- Emphasize database standards and extensibility: Avoid a one-off bare script and leave a solid data foundation for later backtest logic.
- Require visible progress: This is easy to overlook, so I discuss it separately below.
5. API Selection and Data Source Strategy
For market data sources, I prepared two public data APIs at the same time: a credit-based API with high data quality and standardized fields, suitable as the primary source for daily data, and a completely free API as a supplement and fallback for intraday data or missing data.
General considerations for API selection include:
- Field completeness: Does the API include fields required for backtesting, such as adjustment factors and limit-up/limit-down prices?
- Rate limits: Credit-based and free APIs generally have per-minute call limits. The code should include rate limiting and failure retries.
- Data consistency: The same field may have different definitions across sources, such as adjustment methods. When mixing sources, you must unify the treatment; otherwise, backtest results will be distorted.
One practical engineering technique is to abstract the API call layer into a separate adapter module. The main logic then only works with a unified data model, so changing or adding data sources later does not require modifying the backtest core.
6. Database Design Points
After I added requirements, the model’s table design was fairly standard. The core ideas were:
- Market data table: Ticker code, trading date, open/high/low/close, volume, adjustment factor, etc., with “code + date” as the unique key.
- Trade record table: Imported directly from trade confirmations, retaining original execution prices and fees.
- Separate tables for daily and intraday data: Intraday data is large, so store it in a separate table partitioned by ticker to avoid slowing down daily queries.
- Use parameterized writes consistently: Batch inserts improve efficiency and help prevent injection-style issues.
During backtesting, join the trade record table with the market data table by “code + date” to reconstruct how each trade performed in subsequent market data. Then calculate metrics such as holding-period returns and maximum drawdown.
7. Progress Visibility: Do Not Let the Program Run as a Black Box
In the prompt, I specifically required “concrete progress during retrieval.” The reason is practical: pulling daily and intraday data for dozens of tickers can take tens of minutes or even longer. With no output, you cannot tell whether the program is running normally, stuck due to rate limiting, or has already crashed.
A simple and effective approach is to have the model add the following to the code:
- After each ticker is completed, print one line: code, name, record count, elapsed time- On failure, print the specific error and continue to the next ticker (do not stop the whole workflow)- At the end, output a summary: success/failure counts
Combine this with batch retrieval and checkpoint resume logic (recording completed tickers). Even if the process is interrupted midway, it can resume from the checkpoint instead of starting over.
8. Backtest Results and Project Retrospective
Once the data was ready, the backtest logic followed naturally: replay each trade from the trade confirmations in chronological order, and calculate the win rate, average profit/loss ratio, holding-period distribution, and common features of losing trades. The final report was blunt: my trading showed a pattern of “chasing highs, short holding periods, and weak stop-loss discipline,” with a negative long-term expected return. In the model’s words, this set of habits is “likely to lead to ruin over time.”
Uncomfortable as it was, the technical takeaways from this practice were real. A few lessons for readers who want to build similar projects:
- Structured data first: Convert Excel to Markdown before feeding it to the model. Reading accuracy is much higher than direct parsing.
- Submit requirements in small steps: Break large tasks into small, human-verifiable steps to avoid uncontrolled one-shot generation.
- Feed documentation instead of relying on memory: Let the model read local API documentation to eliminate API hallucinations.
- Design for progress and checkpoints: Any long-running data task should have logs, progress output, and checkpoint resume.
- Human verification is indispensable: In the AI era, the most important engineering habit is still “manually check key outputs once.”
The role of the LLM in this project was clear: it is not a magic wand that produces a report in one click, but an engineering assistant with strong execution ability that needs clear instructions. If you think through the workflow, break down the steps properly, and verify the results carefully, it can handle small data engineering projects like this quickly and reliably.
(Note: The above is a personal practice record. The model behavior described reflects my experience at the time and does not constitute investment advice.)
