A Step-by-Step Guide to Building a Stock Backtesting System with Large Language Models
This article provides a practical guide on leveraging Large Language Models (LLMs) to build a local stock backtesting system. It covers converting broker trade records into Markdown for accurate parsing, designing step-by-step prompts for data extraction and fetching, and securely managing API tokens to ensure safe and repeatable backtesting analysis.
1. Background and Goals
Many investors face the dilemma of losing more often than they win. Reviewing trade records and summarizing trading patterns is a common method to improve trading skills. The goal of this practice is to use exported historical trade records as a starting point, fetch related daily stock data, build a locally repeatable backtesting analysis system, and ultimately output objective trading statistics.
This article only covers daily line data. Intraday data differs significantly in table structure and fetching logic, requiring separate design that will not be elaborated on here.
2. Converting Trade Records to Markdown
Trade records exported from broker software are usually Excel files. If you let an LLM parse them directly using Pandas, you may easily encounter complex headers, empty rows, and merged cells, leading to incomplete reads or column misalignment.
Converting trade records into Markdown tables allows the LLM to read fields row by row directly, reducing reliance on parsing code. Note that Markdown tables lack a strict alignment mechanism; they merely use pipes and separator rows to describe column structures. Their advantage lies in being plain text, lightweight, and directly insertable into the context window.
There are several conversion methods. You can use Python’s pandas.DataFrame.to_markdown method (which requires installing tabulate) or online conversion tools for office documents. Since trade records contain account information, you should prioritize local tools to avoid uploading data to third-party servers.
After conversion, three checks are recommended:
- Remove empty rows and merged headers, ensuring the first row contains the field names.
- Standardize currency units (e.g., yuan or ten-thousands) and date formats; using YYYY-MM-DD is recommended.
- Check if cells contain pipe
|characters. If so, they must be escaped to prevent column misalignment.
Overly wide tables can be split into multiple files by month or by stock for separate conversion.
3. Step-by-Step Prompt Design
Asking an LLM to fulfill all requirements in one go can lead to uncontrollable output, and the generated code can be difficult to maintain. This task is split into two steps.
The first step is extracting the stock list. The prompt is as follows:
Please read the attached trade record text, extract all unique stock names and their corresponding stock codes, and output them as a JSON array for my confirmation.
After obtaining the list, manual verification is necessary. Focus on checking the code length (e.g., 6 digits for A-shares, ensuring leading zeros are not lost), ensuring no mutual funds or bonds are mixed in, and verifying that names match the codes.
The second step is fetching and storing data. Once the list is confirmed, instruct the LLM to read the API documentation and write the program. The prompt should specify database schema requirements and progress printing requirements, and explicitly forbid hardcoding the API token in the code.
4. Secure API Token Management
The API token in the documentation is an account credential. Common risks include three scenarios: writing it into the code and uploading it to a code hosting platform; keeping it in a workspace document that gets read by models or tools and retained in logs; or pasting it completely to third-party services in a conversation.
It is recommended to store the token in environment variables for the program to read. The documentation should only mention the variable name, not the actual value. An example code snippet is provided below, where fetch_daily needs to be completed according to the API documentation.
import osimport sqlite3import timefrom tqdm import tqdmDB_PATH = "stock_data.db"API_TOKEN = os.environ.get("STOCK_API_TOKEN") # Read from environment variables, do not write into codedef init_db(db_path=DB_PATH):conn = sqlite3.connect(db_path)conn.execute("""CREATE TABLE IF NOT EXISTS daily_data (code TEXT NOT NULL,date TEXT NOT NULL,open REAL,high REAL,low REAL,close REAL,volume REAL,PRIMARY KEY (code
