LLM-Powered Backtesting System for Securities Trading: A Practical Guide

    This article walks through building an LLM-assisted backtesting system that turns exported brokerage trade records into verifiable statistics. It covers a five-layer architecture, a step-by-step workflow, converting trade files into structured text, extracting and reviewing a symbol list, probing market data APIs, designing storage with batch loading, and running backtests with visual reports. Readers will learn how to validate LLM-generated code, document assumptions, and use objective results to improve trading discipline.

    1. Why: Moving from Gut Feeling to Verifiable Evidence

    Many individual investors have had a similar experience: account equity swings unpredictably over the long run, losing trades outnumber winning ones, and it is hard to tell whether the losses come from stock selection, market timing, or position sizing. Rules of thumb shared on social media—“review your trade confirmations repeatedly and develop your own trading pattern”—sound reasonable, but manually scanning hundreds of fills is tedious and invites subjective bias.

    A more practical path is to treat trade confirmations as first-hand experimental data, replay them against historical market data, and let statistics answer three questions: What are my win rate and profit/loss ratio? Are losses concentrated in certain market conditions or certain types of symbols? What happens if I change the holding period or stop-loss threshold?

    This article documents a complete practice: exporting trade confirmations from trading software, then using an LLM to progressively generate functions for data retrieval, storage, backtesting, and reporting. One conclusion needs to be stated upfront: once the model sees the full trading record and behavior patterns, its judgment can be quite direct, even blunt. That is exactly the value of the tool—it does not offer psychological comfort; it only presents things objectively.

    2. Overall Architecture and Stepwise Strategy

    The system is split into five layers: data export, format conversion, data acquisition, storage, and analysis.

    The key lesson is: do not hand all requirements to the model at once. In personalized tasks, delivering requirements all at once can easily make the generated results go out of control—messy directory structures, unclear dependencies, and missing error handling. A safer approach is to think the workflow through yourself first, then deliver it step by step, manually confirming each intermediate artifact.

    Recommended workflow:

    1. Export and convert trade confirmations, and confirm the fields are complete;
    2. Have the model extract the symbol list, then review it manually;
    3. Probe data API availability and produce a test report;
    4. Set up a well-structured database and pull market data in batches;
    5. Implement backtesting and a visualization report.

    3. Step 1: Exporting and Converting Trade Confirmations

    Most mainstream trading software supports exporting spreadsheet files. Spreadsheet files are not friendly to LLMs: merged cells, multi-level headers, and mixed date and amount formats can cause the model to miss rows or columns during parsing, leading to incorrect statistical calculations.

    The solution is to convert them first into a structured plain-text markup format. Several document conversion tools in the industry can transcribe spreadsheets, presentations, and audio/video into unified markup text, making it easier for the model to read section by section. After conversion, manual spot checks are essential: are all fields present, are trade dates and amounts misaligned, and are buy/sell directions lost?

    At a minimum, trade confirmations should retain the following fields:

    1. Trade Date | Symbol | Security Name | Side | Quantity | Price | Commission | Stamp Duty

    Missing fields directly affect later profit/loss calculations. It is better to spend more time checking than to let erroneous data flow into the backtesting stage.

    4. Step 2: Extracting the Symbol List and Manual Review

    After connecting an LLM in an AI coding tool, the first task should be designed to be small enough: extract all symbols and names from the converted text, deduplicate them, and output a list.

    This step looks simple, but its value lies in establishing a human-AI collaboration rhythm. The model handles mechanical extraction, and the human handles business confirmation—for example, removing delisted symbols and merging records for the same security across different accounts. Once confirmed, the list is fixed as a configuration file, and all later stages use it as the source of truth, preventing the model from “memory drift” in a long workflow.

    In practice, you may encounter cases where the model response stalls for a long time. The handling is simple and effective: manually abort and rerun the same instruction, which usually restores normal behavior. This phenomenon is more common in the early days after a new model is released; there is no need to over-interpret it, but the workflow should support interruption and rerun at any time.

    5. Step 3: Probing Data APIs and the Test Report

    Market data is the foundation of backtesting. Common options fall into two categories: one is points-based financial data API services that open different data frequencies based on contribution or paid quota; the other is open-source financial data collections covering quotes, fundamentals, and basic information.

    Do not assume an API is available. The correct approach is to have the model first fetch the API documentation and save it as a local markup document, then generate test code for each API one by one, recording call status, returned fields, and failure reasons, and finally summarizing everything into a test report. Example code:

    1. results = []
    2. for name, fn in candidates.items():
    3. try:
    4. df = fn()
    5. results.append({"interface": name, "status": "ok", "rows": len(df)})
    6. except Exception as exc:
    7. results.append({"interface": name, "status": "fail", "reason": str(exc)})

    With the report, the project starts with a clear boundary of available capabilities, avoiding repeated trial and error during later development. If the documentation contains access credentials, move them out of the code directory and manage them with environment variables or a local configuration file; never commit them with the code.

    6. Step 4: Storage Design and Batch Loading

    The database design should be well-structured and extensible. The core idea is to “separate market data from trades”:

    • Market data table: symbol, trade date, open/high/low/close, volume, turnover, adjustment type;
    • Trade table: trade date, symbol, side, quantity, price, fees;
    • Metadata table: symbol list, loading batch, update time.

    Using symbol plus trade date as a composite primary key, with adjustment type distinguishing the price basis, avoids duplicate writes. The loading process must output progress, for example “processed 37/120, succeeded 35, failed 2”, so you can tell at any time where the model is in execution. Failed symbols should be recorded and support resumable loading from breakpoints rather than being silently skipped.

    7. Step 5: Backtesting and Reporting

    Backtesting requires explicit assumptions: whether the fill price uses the next day’s open or the signal day’s close, whether commissions and stamp duty are included, and how limit-up/limit-down situations that prevent fills are handled. Different assumptions can lead to vastly different conclusions, so the report must state the parameters clearly.

    The output should include win rate, profit/loss ratio, maximum drawdown, average holding days, and return distribution by symbol and by month. Visualizations are more convincing than numbers: an equity curve, a drawdown curve, and a histogram of profit/loss distribution.

    8. Risks and Boundaries

    LLM-generated code must be verified section by section, especially numerical calculations and boundary conditions. Backtest results do not equal future returns, and historical data has errors from adjustment and delisting handling. Data APIs have call frequency limits, so batch loading should add throttling. Finally, there is the mindset issue: the tool will objectively point out behavioral flaws, and accepting the conclusions and adjusting trading discipline is the true purpose of using this system.