Building an LLM-Driven Stock Trading Backtest System: A Practical Guide

    This article walks through building a stock trading backtest and analysis system driven by a large language model (LLM), using real brokerage trade records as input. It covers a five-layer architecture, converting spreadsheet exports into Markdown, extracting and manually verifying a symbol list, pulling and storing historical market data with idempotent writes, observability and resume-from-breakpoint handling, and designing analysis metrics such as win rate, profit/loss ratio, and drawdown. It also shares reusable lessons on process design, input formatting, and credential isolation. The content is for technical demonstration only and does not constitute investment advice.

    1. Motivation: Starting from a Real Pain Point

    Many individual investors share a similar experience: their account curve swings unpredictably, losses outnumber gains, and when they review their trades, only a few memorable ones stick. There is a piece of conventional wisdom in the industry—“review your trade confirmations repeatedly to identify your own trading patterns”—but putting it into practice rarely works. The reason is simple: trade confirmations are a raw log, not a conclusion. Turning them into a conclusion requires a structured backtest.

    The problem this article addresses is therefore clear: take real brokerage trade confirmations as input, build a stock buy/sell backtest and analysis system, and produce an objective analysis report rather than subjective impressions. The entire process was carried out with an AI coding tool working alongside a large language model, with model capabilities accessed through a public unified interface and tokens managed by the user.

    One prerequisite should be stated up front: this article does not constitute any investment advice, and all data and code are for technical demonstration only.

    2. Overall Solution Design

    Thinking the workflow through before writing any code was the single most important lesson from this project. Many people prefer to hand all requirements to the model at once and wait for a “complete finished product,” which usually leads to runaway output: a messy directory structure, missing dependencies, and the model improvising along the way. A more reliable approach is to break the task into small, verifiable steps, each with a clear deliverable and acceptance criteria.

    The overall pipeline is designed in five layers:

    1. Data acquisition layer: export trade confirmations from the trading software;
    2. Format normalization layer: convert spreadsheet files into a plain-text structure that the LLM can parse more easily;
    3. Symbol identification layer: extract all security names and codes from the records, then confirm them manually;
    4. Data fetching and storage layer: pull historical market data for the symbol list and store it in a database;
    5. Analysis layer: compute metrics such as returns, win rate, holding period, and profit/loss ratio, and generate a report.

    The benefit of layering is that if any single layer fails, it can be rerun on its own without redoing the whole pipeline.

    3. Step 1: Exporting Trade Confirmations and Converting Formats

    The trade confirmation export feature in mainstream trading software typically only provides spreadsheet files. Handing these files directly to a large model often results in incomplete reads: merged cells, date formats, and multi-sheet structures can cause parsing functions to return null values or misaligned data, and the analysis code the model writes from that input is naturally unreliable.

    The solution is to first convert the file into a flat, plain-text markup format. After converting a spreadsheet to Markdown, every row becomes an explicit set of pipe-separated fields, which greatly reduces parsing ambiguity for the model. This step can be done in batch with document conversion tools, or with a few dozen lines of your own script. After conversion, it is worth manually spot-checking the first and last ten rows to confirm that fields have not shifted between columns.

    Illustrative conversion and validation logic:

    1. import pandas as pd
    2. def export_to_markdown(xlsx_path: str, md_path: str, sheet: str = 0):
    3. df = pd.read_excel(xlsx_path, sheet_name=sheet, dtype=str)
    4. df = df.dropna(how="all") # drop fully empty rows
    5. df.columns = [str(c).strip() for c in df.columns]
    6. df.to_markdown(md_path, index=False) # output a flat table
    7. return df.shape
    8. shape = export_to_markdown("delivery.xlsx", "delivery.md")
    9. print(f"rows={shape[0]}, cols={shape[1]}")

    4. Step 2: Extracting the Symbol List and Confirming It Manually

    Do not skip manual confirmation. When extracting names from the records, the model may confuse “security name” with “operation remarks,” and it may also fail to normalize multiple short names for the same stock. The reliable approach is two steps: first have the model output only a candidate symbol list, without writing any business logic; then have a person verify that each code maps one-to-one to the correct name.

    The output of this step should be fixed as a structured file that every downstream stage reads, avoiding hardcoded values in multiple places:

    1. [
    2. {"code": "600000", "name": "Sample Stock A", "market": "SH"},
    3. {"code": "000001", "name": "Sample Stock B", "market": "SZ"}
    4. ]

    5. Step 3: Fetching Market Data and Storing It Cleanly

    Once you have the symbol list, you move on to building the data layer. Here are a few general engineering principles, independent of which data service you use:

    • Credential isolation: write API tokens into a local config file or environment variables, add them to the version control ignore list, and never pass them in plaintext inside code or prompts;
    • Documentation first: organize the data service’s field descriptions into a local document so the model calls the API according to that document instead of guessing parameters from memory;
    • Extensible storage: reserve dimensions such as trading day, adjustment type, and data source in the table schema to avoid schema changes later;
    • Idempotent and rerunnable: use (symbol code, trading day, adjustment type) as the unique key so repeated fetches update existing rows rather than appending duplicates;
    • Rate limiting and retries: control request frequency and apply exponential backoff on timeouts.

    Illustrative table schema and write logic:

    1. CREATE TABLE daily_bar (
    2. code VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open DECIMAL(12,3),
    5. high DECIMAL(12,3),
    6. low DECIMAL(12,3),
    7. close DECIMAL(12,3),
    8. volume BIGINT,
    9. adjust_type VARCHAR(8) NOT NULL DEFAULT 'qfq',
    10. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    11. PRIMARY KEY (code, trade_date, adjust_type)
    12. );
    1. def upsert_daily(conn, rows):
    2. sql = """
    3. INSERT INTO daily_bar(code, trade_date, open, high, low, close, volume)
    4. VALUES (%s, %s, %s, %s, %s, %s, %s)
    5. ON CONFLICT (code, trade_date, adjust_type) DO UPDATE SET
    6. close = EXCLUDED.close, volume = EXCLUDED.volume,
    7. updated_at = CURRENT_TIMESTAMP;
    8. """
    9. with conn.cursor() as cur:
    10. cur.executemany(sql, rows)
    11. conn.commit()

    Progress visibility matters just as much. Have the model print “current symbol / completed count / total count / failure list” during fetching so a person can tell at any moment whether it is actually working or stuck. A simple implementation computes the total workload, refreshes a counter after each completed item, and prints the failure details at the end for a follow-up fetch.

    6. On Stability: A Reality That Must Be Faced

    In practice, the model repeatedly appeared to “freeze”: after a task started, there was no output and no file changes for a long time. The workable response is not to retry over and over, but to establish observability—first check whether the process is still alive, whether the logs have new entries, and whether the database row count is growing. If it is confirmed to be stalled, terminate it manually and resume from the last breakpoint, which usually restores normal operation on the first try. This also reinforces the value of step-by-step execution: the smaller the steps, the lower the rollback cost.

    It should be emphasized that this kind of behavior may relate to the specific model version, concurrency load, and context length. It is a common issue in LLM-assisted development today and should not be attributed to a single product.

    7. Analysis Layer: Turning Records into Metrics

    Once the data is complete, the metric design in the analysis layer determines the quality of the report. It should cover at least: overall profit/loss and return rate, win rate, average profit/loss ratio, maximum drawdown, distribution of holding days, return attribution by industry and by holding period, and the pattern question of “whether losing trades are concentrated in a certain type of operation.” Keep metric computation stateless and unit-testable, and output everything uniformly as tables and charts to make it easy to compare different time periods side by side.

    8. Conclusion and Lessons Learned

    The conclusion from this project was not a pleasant one: the system judged that the current trading pattern would most likely head toward losses. But this is exactly the value of a backtest—it gives you evidence, not comfort.

    Three reusable lessons: first, process before prompts—break the task into small, acceptance-ready steps; second, input format sets the ceiling on model output, so clean up the input first; third, apply isolation and idempotent design to all external credentials and data sources. Once you master this approach, the same pipeline can be adapted with minor changes to fund transaction analysis, expense attribution, inventory turnover, or any scenario that turns tabular records into conclusions—which is where the real general value of LLM-assisted development lies.