LLM-Driven Backtesting for Securities Trading: A Practical Workflow
This article walks through a practical workflow for turning personal brokerage trade records into a backtestable dataset with the help of a large language model. It covers normalizing exported trade files into plain-text markup, validating fields and derived values, driving the model with step-by-step instructions instead of one large request, verifying market data API availability before writing business logic, designing extensible local storage, formalizing trading behavior into computable rules, and generating layered performance reports. The emphasis is on avoiding look-ahead bias, survivorship bias, and ignored fees or slippage so that backtest results can be reproduced in live trading.
1. Starting Point: Why Turn Trade Confirmations into Computable Data
Most individual investors’ account curves show a familiar shape: long stretches of sideways movement, with drawdowns outweighing gains. The cause is usually not stock-picking ability but a lack of quantitative awareness of one’s own behavior: whether entries and exits cluster around emotional highs, whether holding periods are too short, and whether losing positions are held for far too long. The only reliable material for answering these questions is your own historical trade records, not someone else’s quotes or after-the-fact commentary.
Converting trade confirmations into structured data and backtesting them is essentially upgrading an “experience narrative” into a “verifiable hypothesis.” The pipeline breaks into four stages: data acquisition and normalization → market data completion → strategy rule formalization → metrics and report output. If any stage stays vague, the conclusions cannot be trusted.
2. Step One: Normalizing and Converting the Trade File Format
Trading software usually exports spreadsheet files, and feeding those directly to an LLM carries obvious risk: the model tends to miss or misread content when parsing multiple sheets, merged cells, and mixed thousands separators and percentages, which leads to analysis that “looks reasonable but has wrong numbers.”
A safer approach is to perform a format normalization pass first, converting the spreadsheet into a plain-text markup format (such as a Markdown table) before handing it to the model. After conversion, three things need manual verification:
- Field completeness: trade date, security code, security name, buy/sell direction, quantity, price, commission, stamp duty, and transfer fee are all present;
- Type correctness: amounts and quantities are numeric, dates are in a parseable format, and direction is an enumerated value;
- Record uniqueness: no duplicate imports or canceled-order records.
Illustrative normalization and validation logic:
import pandas as pddf = pd.read_csv("trades.csv", dtype={"code": str})df["date"] = pd.to_datetime(df["date"])df["amount"] = df["price"] * df["qty"]assert df["code"].str.len().ge(6).all(), "Unexpected security code format"assert df.duplicated(["date", "code", "side", "qty", "price"]).sum() == 0
Filling in derived fields such as amount is critical, since every later calculation of returns, position size, and turnover depends on it.
3. Step Two: Drive the Model with Stepwise Instructions, Not One Big Request
One repeatedly confirmed lesson: handing the complete requirement to the model in a single shot makes the output easy to lose control of — messy directory structure, dependencies pulled in arbitrarily, missing error handling. Personalized tasks are especially prone to this, because the requirements implicitly contain many conventions known only to the author.
What works more reliably is process decomposition plus step-by-step confirmation:
- Have the model extract only the instrument list (security codes and names), then verify it manually;
- Have the model build only the data-fetching module, requiring observable progress output;
- Have the model design only the local storage schema, producing the table definitions before any code;
- Have the model implement only the metric calculations, with fixed input and output formats;
- Only at the end, do report rendering.
Each step’s prompt should contain four elements: goal, input path, constraints, and acceptance criteria. Step two, for example, could be written as: “Taking the given instrument list as input, read the local API documentation and implement daily and intraday data fetching, writing results to the local database; the fetching process must print the current instrument, the number completed, and the reason for any failure; do not introduce third-party dependencies that were not specified.”
Engineering-wise, long-running tasks also need stability. Model-driven automated execution occasionally “freezes” with no output for a long time, so it helps to agree on a per-step timeout, failure retries, and resumable checkpoints, writing state to a local file so an interrupted run can continue from where it stopped instead of starting the whole round over.
4. Step Three: Verify API Availability Up Front
Market data is the foundation of any backtest. Rather than writing business logic and debugging as you go, run a round of API connectivity verification first: organize the API documentation into locally readable text, have the model generate a minimal test case for each candidate endpoint, run them one by one, and summarize the results into an availability report that states each endpoint’s fields, rate limits, response granularity, and failure reasons.
This converges uncertainty at the cheapest possible stage. The report should record at minimum: endpoint name, whether authentication succeeded, the per-request return limit, the field list, and the meaning of error codes. All later data-fetching code should reference only “verified working” endpoints, avoiding the discovery at runtime that some category of data simply cannot be retrieved.
Storage design should consider extensibility in advance: partition market data tables by “instrument + interval + date range,” join the trade table to the market data table on security code and trading date, and add a separate data sync log table recording the time range and status of each fetch, which makes incremental updates and idempotent re-runs straightforward.
CREATE TABLE daily_bar (code VARCHAR(8) NOT NULL,trade_date DATE NOT NULL,open DECIMAL(12,3),high DECIMAL(12,3),low DECIMAL(12,3),close DECIMAL(12,3),volume BIGINT,PRIMARY KEY (code, trade_date));
5. Step Four: Formalize Trading Behavior into Backtestable Rules
The credibility of a backtest depends on whether the rules are pinned down. You need to derive computable definitions from the trade confirmations, for example: holding period = sell date − buy date; single-trade P&L = (sell price − buy price) × quantity − fees on both sides; turnover = traded value over the period / average account equity. On top of that, layer behavioral tags such as “averaging down on losses,” “selling as soon as a position is profitable,” and “reversing direction on the same instrument within a day.”
Several types of systematic bias must be watched for: look-ahead bias (using information only available after that day’s close), survivorship bias (backtesting only instruments still in the watchlist), and inflated returns caused by ignoring fees and slippage. Explicitly modeling commission, stamp duty, and reasonable slippage is the dividing line between whether backtest results can be reproduced in live trading.
6. Step Five: Metrics and Reporting
The report should answer questions at three levels: did it make money (cumulative return, annualized return, maximum drawdown), what produced the money (whether returns concentrate in a few instruments or a few trades), and whether the behavior is problematic (holding tendency on losing trades, and whether win rate and profit/loss ratio are consistent). For output, generate the conclusion paragraphs from a fixed template and attach the detail tables, avoiding free-form model output that causes definitions to drift.
7. Conclusion
The value of this method lies not in producing a verdict on “what to buy,” but in turning personal trading into something measurable and iterable. On technology choices, the four points — format normalization, stepwise instructions, up-front API verification, and standardized storage — transfer to any “private data + LLM” analysis scenario. When the final report concludes that “the current trading pattern has a negative long-term expectation,” that is precisely the most valuable output of the whole process: it converts a vague unease into a parameter that can be changed.
