Building a Backtesting System for Securities Trading with LLMs: A Practical Guide

    This article walks through building a local, LLM-assisted backtesting system for securities trading, starting from real exported trade records. It covers the four-layer architecture, data normalization and validation, step-by-step natural language prompting with observability, API availability probing, normalized local database design with idempotent writes, explicit trading rules and performance metrics, and four common pitfalls when coding with large language models. Readers will find a reusable methodology for turning subjective trading habits into measurable, verifiable rules.

    1. Why: Turning “Gut-Feel Trading” into a Measurable Process

    Many individual investors share a familiar experience: account equity oscillates for long periods, losing trades outnumber winning ones, yet it is hard to tell whether the losses come from stock selection, market timing, or position sizing. The only reliable material for answering this question is not market commentary but your own actual trade history. A widely accepted practice in the industry is to repeatedly review execution records, extract stable trading patterns from them, and then use historical market data to verify whether those patterns truly have positive expectancy.

    This article documents a complete individual-level quantitative practice: taking exported real trade details as input, building a localized backtesting and analysis system, and producing objective analysis reports. The whole process was carried out with an AI coding tool paired with a large language model. The specific model version is not the point here; what matters is its capability profile — strong at multi-step tool calls and code generation, and well suited to “scaffolding-style” development work.

    The conclusion up front: the most valuable output of this practice was not the equity curve, but a specification that translates subjective trading habits into computable rules. Once the rules are written down clearly, many losses that previously looked like “bad luck” reveal structural flaws.

    2. Overall Architecture: Four Layers and the Data Flow

    A usable individual backtesting system can be split into four layers:

    1. Data ingestion layer: fetches market and trade data from public data interfaces or local files;
    2. Data storage layer: a local relational database with a well-defined, extensible schema;
    3. Computation engine layer: signal generation, fill simulation, costs and slippage, performance metrics;
    4. Reporting layer: renders results into readable documents and charts.

    The data flow is one-directional: raw trade details → standardized intermediate tables → symbol list → historical market data → backtest results → analysis report. Keeping the flow one-directional means any layer that breaks can be located quickly, without guessing the source of the problem inside a pile of mixed scripts.

    3. Step 1: Converting Exported Spreadsheet Data into a Model-Readable Format

    Trade details exported by mainstream trading software are usually spreadsheet files. Letting a model read spreadsheet files directly often leads to incomplete parsing: merged cells, multi-row headers, mixed thousands separators and percent signs, and inconsistent date formats can all cause the model to “see part and miss part,” producing analysis code that looks reasonable but is built on incomplete data.

    A safer approach is to normalize the format first: use a locally deployed document conversion tool to batch-convert the spreadsheets into a structured plain-text markup format, then hand that to the model. After conversion, manually spot-check three things: whether all fields are present, whether numeric values were truncated, and whether the order of trade dates and times was scrambled.

    A minimal validation example:

    1. import pandas as pd
    2. df = pd.read_excel("trades.xlsx", header=None)
    3. # Key check: row count, column count, and total amount should match the software's summary
    4. print(df.shape)
    5. print(df.tail(3))
    6. assert df.shape[0] > 0, "Trade details are empty; check the header position"

    This step looks trivial, but it determines the credibility of every later conclusion. If the data entry point is not clean, even a powerful model is only amplifying noise.

    4. Step 2: Driving Data Retrieval with Natural Language, but Define the Process Yourself

    One repeatedly confirmed lesson in practice: do not throw all requirements at the model at once and expect it to finish everything in one pass. For personalized, tightly constrained tasks, the right approach is to think the process through yourself first, break it into several verifiable small steps, and deliver them incrementally.

    The breakdown here was:

    • Step 1: extract all symbol names and codes from the trade details, then review them manually;
    • Step 2: fetch daily and intraday data for each symbol and write it into the local database;
    • Step 3: probe data interface availability first, then write the business retrieval logic;
    • Step 4: implement the backtest engine and performance statistics;
    • Step 5: generate the analysis report.

    Instructions handed to the model should include constraints and observability requirements, for example:

    1. Goal: Build a stock buy/sell backtesting and analysis system.
    2. Current step: Using the symbol list confirmed in the previous step as input, fetch all daily and intraday data.
    3. Constraints: Use the locally saved API documentation (including access credentials) as the only interface source;
    4. the database schema must be well-defined and extensible, with table creation scripts and indexes;
    5. the retrieval process must output progress (completed/total, failure list, retry count).
    6. Deliverables: executable script + table creation SQL + run logs.

    On “visible progress”: this is not a nice-to-have. When a long batch retrieval fails silently, you cannot tell whether it is network throttling, rate limiting, or a field parsing error. Requiring the model to print progress and a failure list is like installing a dashboard on a black box.

    5. Step 3: Probe Interfaces First and Produce an Availability Test Report

    Before writing business code, do an interface probe first: hand the documentation URL of the public data service to the model and have it fetch and organize the content into a local document; then generate test code that calls each interface one by one, recording return status, field structure, per-call limits, and failure reasons, and finally summarize everything into an availability report.

    The value of this report is turning “guessing” into a “list.” All later retrieval logic depends only on the few interfaces confirmed as usable in the report, which greatly reduces code branches and lowers maintenance cost. The report should include at least: interface purpose, authentication method, returned fields, constraints, and tested conclusions.

    One reminder: credential information should be kept in local environment variables or a separate configuration file, and should not be committed to any remote repository along with the code.

    6. Step 4: Normalized Design of the Local Database

    The storage layer design follows three principles:

    • Single source of truth: market data is uniquely constrained by “symbol + period + time,” and repeated fetches use idempotent writes;
    • Clear layering: the raw layer keeps interface responses as-is, the intermediate layer standardizes fields, and the result layer stores backtest output;
    • Extensibility: adding a new period or a new data source means adding tables, not changing old ones.

    Sample table creation:

    1. CREATE TABLE daily_bar (
    2. symbol VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open DECIMAL(18,4),
    5. high DECIMAL(18,4),
    6. low DECIMAL(18,4),
    7. close DECIMAL(18,4),
    8. volume BIGINT,
    9. PRIMARY KEY (symbol, trade_date)
    10. );
    11. CREATE INDEX idx_daily_date ON daily_bar (trade_date);

    Pseudocode for idempotent writes:

    1. for bar in bars:
    2. cur.execute("""
    3. INSERT INTO daily_bar VALUES (%s,%s,%s,%s,%s,%s,%s)
    4. ON CONFLICT (symbol, trade_date) DO UPDATE SET
    5. close = EXCLUDED.close, volume = EXCLUDED.volume
    6. """, bar)

    7. The Backtest Engine: Writing Trading Habits as Rules

    The core of backtesting is not returns but the explicitness of rules. At minimum, you must explicitly define: buy trigger conditions, sell trigger conditions, maximum position count, per-trade position size, commissions and stamp duty, slippage assumptions, limit-up/limit-down and trading suspension handling, and what to do when funds are insufficient. Any blank left here makes results lose comparability.

    For performance, it is recommended to output at the same time: annualized return, maximum drawdown, Sharpe ratio, win rate, profit/loss ratio, average holding days, number of trades, and turnover rate. A review that looks only at the equity curve almost inevitably leads to overconfidence.

    8. Four Real Pitfalls of LLM Coding and Countermeasures

    • Unresponsive hangs: in batch tasks the model may produce no output for a long time. The countermeasure is to shrink the granularity of each step, manually interrupt and rerun that step, which usually recovers quickly; also persist each step’s output to disk to avoid redoing everything.
    • Loss of control from sending all requirements at once: switch to “small-step instructions + manual confirmation,” where every step has a verifiable artifact.
    • Incomplete data reading: do format conversion and sampling validation first, then move to the analysis stage.
    • Context bloat: externalize long documents and API descriptions as local files and reference them on demand, instead of stuffing everything into the conversation.

    9. A Reusable Methodology

    Abstracted from this practice, there is a general path applicable to individual developers: material standardization → process breakdown → capability probing → storage normalization → explicit rules → automated reporting. The large language model takes on scaffolding and repetitive labor, while judgment and constraints must still come from the human.

    To push the system toward a more engineered form, you can layer on common cloud capabilities such as containerized deployment, scheduled jobs, logging services, and monitoring alerts, so that data retrieval and backtest tasks run stably and anomalies are traceable. The tech stack can be swapped, but the methodology stays the same: think the process through first, then let the model execute; ensure the data is trustworthy first, then discuss the quality of conclusions.