LLM-Powered Securities Trading Backtest System: A Practical Engineering Workflow

    This article presents a practical engineering workflow for turning broker-exported trading records into a reproducible backtest system driven by a large language model (LLM). It covers format normalization before model input, splitting requirements into verifiable pipeline steps, validating market data APIs into a capability checklist, designing a layered local database for extensibility, and fixing backtest assumptions as configuration. The output is not a claim about profitability but a statistical report with explicit assumptions, along with three transferable lessons for individual investors.

    1. Starting Point: Why Trade Confirmations Must Become Computable Data

    Many individual investors share a familiar experience: account equity oscillates for long periods, losing trades outnumber winning ones, and reviews end with unverifiable conclusions such as “bad luck” or “be more careful next time.” A common piece of industry advice is to repeatedly review your own execution records and extract stable trading habits from them. But the human eye has almost no statistical power in front of a few hundred rows of a table. The real solution is to structure the execution records, place them against historical market series, and run a backtest so that conclusions come from data rather than emotion.

    This article is not about the profit and loss of a particular instrument. It describes a general engineering workflow: how to convert a table exported from brokerage software into an analysis system that an LLM can understand accurately, use to drive code generation, and ultimately run to produce an objective report. The same workflow applies to any scenario of “personal data + historical time series + statistical validation.”

    2. Data Preparation: Format Conversion Is the First Gate for Accuracy

    Trading software typically exports spreadsheet files. Handing the raw spreadsheet directly to an LLM often produces a “partial read” failure: merged header cells, thousands separators and percent signs, trade amounts mixed with trade quantities, and dates recognized as numeric sequences can all cause the model to read only some columns while believing it has read everything, shifting every downstream conclusion.

    A more reliable approach is to add a format normalization stage that converts every file type into structured markup text before passing it to the model. There are three reasons:

    • Markup text is a plain text stream, and the model’s row-by-row reading completeness is far higher than binary spreadsheet parsing;
    • Headers, delimiters, and hierarchy are explicitly visible, which makes manual verification easy;
    • The conversion is repeatable: the same source file produces identical output every time, which supports version comparison.

    It is worth stressing that after conversion you must manually spot-check the first and last rows and the total row count to confirm no columns or rows were lost. Two minutes here saves two hours of error hunting later.

    3. Delivering Requirements: Replace One-Shot Instructions with a Stepwise Pipeline

    A repeatedly confirmed lesson is that handing all requirements to the model at once makes the output easy to lose control of, especially for personalized tasks. The reliable pattern is to think the workflow through yourself first, then split it into steps with acceptance criteria and advance step by step.

    The breakdown used in this practice is:

    1. Extract the list of instruments involved in the execution records and confirm it manually;
    2. Verify data API availability and produce a test report;
    3. Design and create the local database schema;
    4. Implement batch fetching and persistence, with progress output;
    5. Run buy/sell point backtests on the historical series and output a statistical report.

    Every step requires a “verifiable intermediate artifact” rather than only a block of code. That way, even if a step drifts off course, the rollback cost is only one step.

    A schematic task description looks like this:

    1. Goal: Build a securities buy/sell backtest analysis system (Step N)
    2. Input: Artifact path from the previous step + API documentation path
    3. Constraints: Prefer market data APIs with sufficient quota; the database must be extensible
    4. Requirements: During execution, print the current instrument, number completed, and failure reasons
    5. Acceptance: Provide the list of artifacts for this step and self-check results

    As for the “freeze” phenomenon during execution — long periods with no output and no error, where a manual interruption and rerun restores normal behavior — the engineering response is to treat it as a routine risk: keep single-step task granularity within one or two observable actions, and require staged progress printing in the prompt, so that a stall surfaces early instead of being discovered tens of minutes later.

    4. API Availability Validation: Build a Capability Checklist Before Writing Business Code

    Market data usually comes from more than one source, and sources differ greatly in coverage, field definitions, and rate limits. Writing business code directly drags that uncertainty into the main workflow. A better order is to first obtain the API documentation and persist it as a local structured document, then have the model write a minimal validation case for each API one by one, and after they pass, aggregate the results into an availability report.

    The validation checklist should cover at least these dimensions:

    Dimension What to confirm
    Coverage Whether daily bars, intraday data, adjustment factors, and basic information are complete
    Field definitions Adjustment method, amount units, suspension and price-limit markers
    Time boundaries Historical start point and latest available trading day
    Call constraints Per-request limit, rate limits, retry strategy on failure
    Stability Success rate across repeated consecutive calls

    The value of this report is that it turns “whether an API works” from a guess into a fact, and the main workflow depends only on the verified subset of capabilities.

    5. Storage Design: Leave Room for Extensibility

    The design principle for the local database is to stay close to the analysis dimensions that may be needed later, not to fit the current spreadsheet. A workable layering approach:

    • Raw layer: store raw responses by source and fetch date, for traceability and recomputation;
    • Normalized layer: a unified market data main table (instrument, trading date, open/high/low/close, volume and amount, adjustment marker) plus per-frequency tables;
    • Derived layer: trade record table, position and cash flow table, backtest result table.

    Key constraints include: use instrument plus trading date plus frequency as the unique key and support idempotent writes; use high-precision types for amounts rather than floating point; add a fetch timestamp to every table; keep instrument master information in a separate table to avoid historical breaks caused by name changes. Once these constraints are met, adding a new data source or a new frequency is just adding a table and an adapter, with no changes to existing analysis logic.

    6. The Backtest Stage: Write Down the Assumptions Before the Code

    The easiest place to fool yourself in a backtest is inconsistent assumptions. Before starting, define: whether buys fill at the same day’s close or the next day’s open, whether commissions and stamp duty are included, whether trades can fill on price-limit and suspension days, whether sells are restricted by a holding period, and whether capital can be reused. These settings must be written as configuration items rather than scattered conditional checks; otherwise the report cannot be reproduced.

    For output, beyond total return and maximum drawdown, more attention should go to the distribution of trade counts, the profit/loss ratio, the relationship between win rate and holding period, and a robustness check that removes the single largest winning and largest losing trade. With a sample of only a few dozen trades, no single metric has statistical significance, and this must be noted on the first page of the report.

    7. Conclusion and Boundaries

    The output of this workflow is not an assertion about whether you can make money, but a set of statistical facts with documented assumptions. When the model, working from a limited sample of executions and historical series, produces a somewhat negative path judgment, the right attitude is to treat it as a risk warning rather than a verdict of fate: the sample is small, parameters are sensitive, and future distributions may not repeat history — any backtest can only falsify, never confirm.

    Three transferable takeaways: data must pass format and completeness validation before entering the model; complex tasks must be split into steps with acceptance artifacts and enforced progress visibility; storage and assumption design come before analysis code. Fix these three in place, and individual investors can also have review capabilities close to those of an engineering team.