LLM-Assisted Development: From Trade Statements to a Backtesting System

    A reliable trading analysis system requires more than generated code. This article explains how to use large language models to help build a workflow for importing brokerage statements, collecting market data, reconstructing account performance, and backtesting strategies. It covers data validation, database design, recoverable task execution, evidence-based reporting, and practical criteria for evaluating an LLM’s engineering capabilities.

    1. Evaluate LLMs Through Real Task Outcomes

    An LLM’s development capabilities should not be judged solely by how quickly it generates code or how professional its analysis appears. In a project involving personal trading records, historical market data, and investment returns, the essential questions are whether all data has been imported, calculations use consistent definitions, failed tasks can recover, and conclusions can be traced to source records.

    Analyzing brokerage trade statements is a representative engineering task. It combines nonstandard file parsing, external data access, database design, time-series processing, and statistical analysis. An error at any stage can make the final report misleading.

    Rather than focusing on a model release or subjective user experience, this article examines how to use an LLM to help build a reliable trade review and backtesting system—and how that process can reveal its engineering capabilities.

    A practical end-to-end workflow is:

    Statement import → Trade normalization → Instrument identification → Historical market data collection → Data quality checks → Account performance reconstruction → Strategy backtesting → Report generation

    One distinction matters from the outset: analyzing trades that have already occurred is trade review, while simulating explicit trading rules against historical market data is strategy backtesting. They can share infrastructure, but their conclusions are not interchangeable.

    2. Define the Problem Before Generating Code

    Giving an LLM every requirement at once can produce a system that looks complete but is difficult to verify internally. It might assume zero transaction fees, drop leading zeros from security codes, or use an unconfirmed market data frequency. These problems may be invisible in the interface while materially changing the results.

    A safer approach is to establish the project’s scope and acceptance criteria first.

    At a minimum, answer these questions:

    • Which dates, accounts, and transaction types do the statements cover?
    • Are opening positions, transferred securities, cash transfers, or dividends included?
    • Is the objective to explain historical profit and loss or test an executable strategy?
    • Is minute-level data necessary, or are daily bars sufficient?
    • Which markets, historical periods, and data frequencies are covered by the available access permissions?
    • What level of accuracy is required, and which known errors are acceptable?

    Opening assets are particularly easy to overlook. Trades from a selected period are not enough to reconstruct a complete account equity curve without the opening cash balance and positions. The system should explicitly flag missing information rather than assume the account started at zero.

    Once the work is divided into stages, each stage should produce observable outputs. File parsing should expose field mappings and exception rows. Market data collection should report successfully covered dates and missing intervals. Return calculations should provide formulas, input data, and reconciliation results.

    3. Statement Processing: Readability Is Not Data Completeness

    Spreadsheets exported by trading software often contain headings, explanatory rows, merged cells, inconsistent date formats, and repeated records. Converting them into Markdown can help an LLM interpret the fields, but that conversion should not become the only data-processing path.

    A more reliable design preserves three layers:

    1. Raw layer: Original files, import timestamps, and file checksums.
    2. Normalized layer: Records converted into consistent fields with explicit data types.
    3. Presentation layer: Table summaries suitable for human and model review.

    The presentation layer supports explanation, the normalized layer supports calculation, and the raw layer supports traceability.

    A normalized trade record can include the following fields:

    Field Meaning Processing requirement
    Trade date Date on which the trade occurred Use a consistent date format
    Trade time Execution time Do not invent a value if the source omits it
    Security code Instrument identifier Store as text and preserve leading zeros
    Market identifier Market to which the instrument belongs Identify the instrument together with its code
    Transaction type Buy, sell, or another event Define explicit mappings
    Executed quantity Quantity actually traded Distinguish direction from absolute quantity
    Execution price Actual price per unit Preserve source precision
    Trade amount Actual transaction value Cross-check against quantity and price
    Fees Commissions, taxes, and other charges Avoid double counting
    Source reference Original file, worksheet, and row number Support tracing back to the source

    Security names should be supplementary information, not the sole identifier: names can change or be shared by multiple instruments. Records with unclear transaction types should enter a review queue rather than automatically become ordinary buys or sells.

    After import, perform basic reconciliation. Do the raw and normalized record counts match? Do aggregate purchase and sale amounts agree? Are fees complete? Is there clear evidence for any records classified as duplicates?

    Two records with the same date, price, and quantity are not necessarily duplicates. They may represent two genuine executions.

    4. Market Data Collection: Verify Access Before Expanding Scope

    “Download all daily and intraday data for every instrument” sounds straightforward, but it is often unnecessary and difficult to control.

    Data frequencies can differ in access permissions, historical coverage, request limits, and volume. Read the official documentation and run a small validation request before collecting data in bulk. Access to one dataset does not establish access to every data type.

    Start with daily data directly relevant to the trade review, covering the necessary window before and after the transactions. Expand to minute-level data only when analyzing intraday timing, execution slippage, or short-horizon signals. Even minute-level prices cannot precisely reconstruct order queues or actual execution conditions.

    The collector should be able to:

    • Create independent tasks for each instrument and date range.
    • Respect the data source’s request-rate limits.
    • Retry temporary network failures a limited number of times.
    • Stop futile retries for insufficient permissions or invalid parameters.
    • Save completed intervals and support incremental updates.
    • Write existing records idempotently.
    • Record failed tasks separately for later collection.

    Credentials should not appear directly in code, logs, version-controlled files, or ordinary documents supplied to an LLM. Programs should retrieve them at runtime from controlled configuration or environment variables, with sensitive values redacted from logs.

    5. Local Databases: Design Matters More Than Simply Storing Data

    A local relational database is usually sufficient for the early stages of a personal trade review project. Lightweight infrastructure still requires clear entity relationships, uniqueness constraints, and data versioning.

    The schema can be divided into these tables:

    • Instrument metadata: Security codes, market identifiers, names, and other basic information.
    • Trade records: Normalized executions, transaction types, and source references.
    • Market data: Prices indexed by instrument, date or timestamp, and frequency.
    • Account events: Cash transfers, dividends, and other asset changes.
    • Collection tasks: Task status, collection intervals, retry counts, and error details.
    • Analysis runs: Data versions, parameters, calculation timestamps, and report locations.

    A market data uniqueness key should account for instrument, timestamp, frequency, and price basis. Raw and corporate-action-adjusted prices must not be stored without distinguishing their basis, or records may overwrite one another or appear as duplicates.

    For daily bars, store the trading date separately from the collection timestamp. For minute-level data, define the market time zone explicitly. Transaction amounts and fees should use fixed-point or decimal representations to reduce the effect of accumulated binary floating-point errors.

    Extensibility does not require complex infrastructure from the beginning. Establish sound schemas, constraints, backups, and migrations first, then adapt the architecture to actual data volumes and concurrency requirements.

    6. Progress Visibility: Distinguish Waiting from Failure

    A long-running task that produces no model output does not necessarily mean the model has failed. An external request may be blocked, a tool may still be running, rate limiting may require a wait, or progress updates may not be refreshing.

    Observability should therefore exist in the task execution layer, rather than depend on the LLM continually describing what it is doing.

    Each collection task should record at least:

    • The current instrument and date range.
    • Completed and pending task counts.
    • Request duration and the latest status-update timestamp.
    • The number of successfully written records.
    • Failure reasons and the next retry schedule.

    Request timeouts, task-level timeouts, and cancellation should be designed separately. A request timeout handles a single blocked call. A task-level timeout limits overall execution time. Cancellation lets the user stop work while preserving completed results.

    When execution resumes, the program should continue from saved task states instead of downloading everything again. This reduces resource consumption and makes it easier to locate the point of failure.

    7. Trade Review and Backtesting Require Different Validation Logic

    Trade Review: Reconstruct Actual Account Changes

    Trade review starts with actual executions. For a completed purchase-and-sale cycle, net profit can be summarized as:

    Net profit = Sale proceeds − Purchase cost − Related transaction fees

    Account-level performance also depends on opening assets, external cash inflows and outflows, dividends, and unrealized gains or losses. Subtracting all purchase amounts from all sale amounts is not equivalent to calculating account returns.

    When an instrument has multiple purchases and sales, define the cost-allocation method and use it consistently throughout the report. If that method differs from the broker’s method, explain the discrepancy rather than immediately declaring either calculation wrong.

    A review can analyze trade-level returns, holding periods, capital concentration, trading frequency, and performance under different trading conditions. However, associations in a small sample do not establish causation.

    Strategy Backtesting: Test Repeatable Rules

    A backtest requires explicit strategy rules, including entry conditions, exit conditions, position limits, execution timing, and a transaction-cost model.

    Avoiding look-ahead bias is a central requirement. A signal derived from information available only after the market closes cannot automatically be assumed executable at that same closing price. Signal availability and execution time must be defined separately.

    The simulation must also account for trading suspensions, applicable price limits, lot-size rules, quantities available for sale, and liquidity constraints. A quoted market price does not guarantee that a simulated order could have executed.

    Adjusted prices are useful for some continuous-return analyses, but actual executions and account cash flows also require raw prices and asset-adjustment events. Actual execution prices should not be compared directly with adjusted market prices on a different basis.

    Finally, separate rule development from independent validation. Repeatedly tuning parameters until the historical equity curve improves can lead to overfitting; it is not reliable evidence of future performance.

    8. Reports Should Explain Evidence, Not Label the Account

    A rigorous report begins with data reliability, not a forceful verdict.

    A useful report has four parts.

    First, describe the data foundation. State the coverage period, missing records, price basis, and major assumptions.

    Second, present the metrics. Include net profit, maximum drawdown, position concentration, transaction costs, win rate, and the average profit-to-loss ratio, with explicit calculation definitions. A high win rate does not necessarily mean overall profitability; the sizes of gains and losses also matter.

    Third, examine behavioral patterns. Discuss whether losses cluster in particular trade categories, frequent trading increases costs, or concentrated positions amplify drawdowns. Every finding should include sample counts and records that can be checked.

    Fourth, propose testable improvements. Examples include reducing exposure to a single instrument, adding pre-trade checks, or recording entry rationales. Subsequent data should be used to assess whether these changes help.

    LLMs are useful for turning structured results into readable prose. They should not generate financial conclusions from impressions alone. Statements such as “continuing this way will inevitably fail” should instead become conditional risk descriptions supported by evidence and explicit uncertainty.

    9. Evaluate the Model’s Development Assistance Objectively

    After completing the project, assess the model across six dimensions rather than relying only on subjective impressions:

    1. Requirements understanding: Did it identify opening assets, data permissions, and the boundary between trade review and backtesting?
    2. Code correctness: Did it handle repeated imports, invalid dates, and consistent fee treatment?
    3. Engineering reliability: Did it support retries, timeouts, resumable execution, and idempotent writes?
    4. Security awareness: Did it avoid exposing credentials and complete personal trading records?
    5. Verifiability: Did it provide tests, reconciliation details, and source traceability?
    6. Collaboration efficiency: Did it follow the staged plan while minimizing unrelated changes and manual rework?

    When comparing models or runtime configurations, use the same inputs, permissions, and acceptance criteria. Record the number of manual corrections, task completion outcomes, and resource consumption.

    A few successful examples show that a model worked effectively on those tasks. They do not establish its capabilities across all development work.

    10. Put the Model Inside a Controlled Engineering Workflow

    An LLM’s value extends beyond writing code. It can help organize requirements, draft implementations, expand test coverage, and explain results. It should not be the final guarantor of data authenticity, return calculations, or investment judgments.

    A trustworthy trading analysis system needs traceable source data, reproducible calculations, recoverable execution, and clearly stated limits on its conclusions.

    Let deterministic programs handle numerical calculations, use the model for development assistance and communication, and require human confirmation of critical assumptions. That division of responsibility turns a one-off experiment into a maintainable engineering practice.