Backtesting Trading Strategies
Table of Contents
When you’re backtesting trading strategies, the same trades can show a small gross profit and a net loss after costs. To find out whether a rule would have been practical, start with the information available at the time, simulate orders you could have placed, and put a price on getting those orders filled. Then test the rule on a later period that you set aside before tuning it.
What Is Backtesting a Trading Strategy?
Backtesting is a historical simulation of a trading rule. It takes the signals that would have been available at each decision time and turns them into orders, positions and account returns. A chart showing that a signal preceded a price rise tells you where to look. The trade ledger tells you what the strategy could have captured after execution and costs. [1] [2]
For example, a Bollinger Bands rule needs a precise definition of a breach, the time you observe it, and the order you send afterward. A strategy backtest measures the results of those orders. A value-at-risk backtest measures how often realized losses exceed a risk forecast.
Write the Trading Rules Before Testing
- Define what you can trade. Specify the securities, exchanges and dates. If the rule selects stocks from an index, decide when membership takes effect and how to handle names that leave.
- Write the signal and position rules. Give the formula, input timestamps, allowed thresholds, position size, and entry and exit conditions. State whether the account can sit in cash, short stocks or use leverage. A cross-sectional momentum rule also needs a ranking horizon and a rule for dividing capital among the qualifying stocks.
- Define the order and its timing. State when you send it, what price or liquidity data it uses, and how you handle delayed, partial or unfilled orders. Decide how to treat halts and early closes.
- Choose the score and test periods. Pick a benchmark, mark frequency and cost assumptions. Separate the data you will use to develop the strategy from the final holdout. Record every variant you try, including different markets, thresholds and lookback lengths. [1] [3]
Use Point-in-Time Data
Keep an observation date and an availability time for every input. A December financial result might arrive in March. The SEC’s EDGAR example distinguishes a December 31 reporting date from a March 11 acceptance date, and the SEC says its timestamps do not tell you exactly when the filing first became available on sec.gov. For a macroeconomic signal, the St. Louis Fed’s ALFRED database can recover published vintages. A strategy that trades intraday also needs the release time and any delay before the data reached it. [4] [5]
For a stock-selection rule, reconstruct membership as it stood at each decision. S&P Dow Jones Indices announced on September 4, 2026, that Bloom Energy would join the S&P 500 and Molson Coors Beverage would leave before the September 21 open. A screen of current constituents applied to earlier dates would move those changes back in time. Record announcement and effective dates separately so your eligibility rule can distinguish them. If you test the price of an index ETF itself, you need constituent records only when the rule depends on the underlying holdings. [6]
Map securities through ticker changes and retain delisted names. Tyler Shumway’s study of historical CRSP records found that missing delisting returns could omit large losses. A last listed close may leave out the cash or securities ultimately recovered. Record splits, dividends and other corporate actions separately from the price used to simulate a fill. Compare like with like when using adjusted data, and count dividends once when you calculate total return. [7]
Model the Fill and the Cost of Trading
Separate the signal from the fill. A strategy that needs the final closing price cannot use that information to obtain a fill at the same closing auction. In the regular NYSE schedule, the ordinary market-on-close and limit-on-close entry cutoff is 3:50 p.m. Eastern Time and the auction process begins at 4 p.m. Later orders that qualify under the published significant-imbalance exception still arrive before the closing price is known. Use the actual venue and broker rules, and choose a reachable execution time. [8]
Check executable prices and size. Daily open, high, low, close and volume can supply many signals. Suppose a stock opens between your active stop and profit target and later trades at both prices. The daily bar cannot show which level the stock reached first. It also cannot show the bid and ask at the order time, how much your order could fill at each price, or your place in a limit-order queue. A market order can fill at several prices and a limit order can remain unfilled even when a trade prints at its price. Use order and spread mechanics to specify a fill model. Historical trade and quote files such as NYSE Daily TAQ can supply a price reference, with separate depth and order data when the execution model requires them. [2] [9]
Measure the price shortfall and explicit fees. If you start at the bid–ask midpoint, a marketable buy typically pays toward the ask and a sale toward the bid. Allow for further adverse price movement or market impact where warranted. Then subtract commissions and other applicable fees. If your fill price already includes the spread, it has already reduced the trade result. Costs can vary with the stock, order size, venue and time. Short strategies may also need dated borrow availability and fees, and leveraged strategies need financing costs. [2] [10]
How Walk-Forward and Holdout Testing Work
In-sample results come from the data you use to select a rule or its parameters. For a walk-forward test, fit on a historical window, score the selected rule on the next block, and advance both windows. A rolling fit uses a fixed amount of recent data. An expanding fit keeps older data as new data arrive. Check when the training outcomes actually became known. If a five-day trade would still be open at the split, leave its eventual result out of training. [3]
Keep a final chronological holdout outside development. Decide in advance whether any scheduled refitting will occur during it. Each refit can use only outcomes known then and must follow the procedure you already committed to. If you change the rule after looking at the final results, that period becomes part of development. Multiple trials can select noise, and a short holdout has little power to tell you whether the result will persist. Statistical power and false positives matter when comparing many rules or reporting a winning one. [1] [3]
Worked Example With a Final Holdout
Start with $25,000 in cash and one fictional stock. S0 through S16 are consecutive full U.S. trading sessions. S0 closes at $100.00. This example uses a one-session price signal, a fixed 100-share order, no leverage, and no taxes, distributions or interest on cash.
- Decide after the close. Calculate the just-completed close divided by the previous close, minus one. Buy if the result meets the selected threshold and 100 shares are no more than 1% of the completed session’s volume. That means at least 10,000 shares must have traded. Use the unrounded return.
- Trade the following session. Buy at 9:35 a.m. ET and sell at 3:55 p.m. ET, before that session’s final close. For this hypothetical, assume a full fill on each side when the rule triggers. The previous day’s volume is a size screen. In an actual test, you also need a fill model that responds to conditions at the time of each order.
- Charge costs on both sides. Use a separately observed bid–ask midpoint at each trading time for gross P&L. The midpoint is the average of the quoted bid and ask. Assume a four-cent spread, so crossing half the spread costs two cents per share. Add two cents of extra adverse execution per share on each side. The buy model adds four cents to the midpoint and the sell model subtracts four cents. With a $1 fee per order, each 100-share round trip costs 100 × $0.08 + $2 = $10. Those are scenario inputs.
Fit the threshold using completed trades
Allow thresholds of 0% and 1%. At the start of each forward block, choose the threshold with the higher net dollar P&L on the four most recent completed decision rows. A tie goes to 1%. A completed row includes any simulated trade’s next-session exit, which this example assumes is recorded before that session’s closing decision. All first ten decision sessions have 50,000 shares in volume. The midpoints in each row are the following session’s quote references, so that row’s trade result is available only after its exit time.
| Decision | Close ($) | Signal | Next entry midpoint ($) | Next exit midpoint ($) |
|---|---|---|---|---|
| S1 | 100.60 | +0.60% | 100.70 | 100.40 |
| S2 | 102.01 | +1.40% | 102.30 | 102.60 |
| S3 | 102.42 | +0.40% | 103.00 | 102.80 |
| S4 | 101.81 | −0.60% | 102.15 | 102.31 |
| S5 | 102.32 | +0.50% | 102.50 | 102.75 |
| S6 | 103.55 | +1.20% | 103.50 | 103.64 |
| S7 | 104.27 | +0.70% | 104.60 | 104.90 |
| S8 | 104.58 | +0.30% | 104.90 | 104.65 |
| S9 | 106.04 | +1.40% | 106.00 | 106.30 |
| S10 | 105.40 | −0.60% | 105.55 | 105.67 |
The 0% cutoff admits S1, S2 and S3 in the first training window. Their net P&Ls are −$40, +$20 and −$30, for a total of −$50. The 1% cutoff admits only S2 and earns +$20 in that window. Use 1% for decisions S5–S7. After those outcomes become available, the next window rolls forward three rows and the winning cutoff changes to 0%.
Score the next block using the selected threshold
For each block, sum the earlier trades at each candidate cutoff with the same fee and volume rules. Freeze the winner for the next set of decisions. For the final holdout, lock the fitting procedure before opening the holdout results, fit once using S7–S10 and keep the resulting cutoff for S11–S15.
| Earlier decision rows | Fit net at 0% | Fit net at 1% | Selected cutoff | Next decisions |
|---|---|---|---|---|
| S1–S4 | −$50 | +$20 | 1% | S5–S7 |
| S4–S7 | +$39 | +$4 | 0% | S8–S10 |
| S7–S10 | +$5 | +$20 | 1% | S11–S15 (final holdout) |
The first forward block trades S6’s signal and scores +$14 gross and +$4 net. The second trades S8’s and S9’s signals and scores +$5 gross and −$15 net. At the close of S11, the quote references needed to score S10 are already known because S11’s 3:55 p.m. quote has arrived. Any trade triggered by S11’s signal would take place in S12, so its outcome stays outside the final fit.
Reconcile gross and net returns in the holdout
The held-out decisions use the 1% cutoff and the same 10,000-share volume minimum. The close before S11 was $105.40. Measure the holdout on a fresh $25,000 balance, separate from the development results. The following table pairs each decision with its next-session quote references and reports the P&L credited to the hypothetical strategy. Sessions with no trade stay in the account history at zero P&L.
| Decision → next session | Close ($) | Signal | Decision volume | Entry / exit midpoints ($) | Action | Gross P&L | Net P&L |
|---|---|---|---|---|---|---|---|
| S11 → S12 | 105.93 | +0.50% | 50,000 | 106.00 / 105.95 | Below cutoff | $0 | $0 |
| S12 → S13 | 107.20 | +1.20% | 50,000 | 107.00 / 107.16 | Trade | +$16 | +$6 |
| S13 → S14 | 108.59 | +1.30% | 8,000 | 109.15 / 109.45 | Low volume | $0 | $0 |
| S14 → S15 | 110.11 | +1.40% | 50,000 | 110.75 / 110.69 | Trade | −$6 | −$16 |
| S15 → S16 | 109.45 | −0.60% | 50,000 | 110.00 / 110.18 | Below cutoff | $0 | $0 |
| Held-out total | +$10 | −$10 | |||||
On S13, the first trade earns 100 × ($107.16 − $107.00) = $16 before costs. Its modeled buy is $107.04 and sell is $107.12. Including the $1 per order, $10,711 of sale proceeds minus $10,705 of purchase cost leaves $6. At that day’s close the signal clears 1% again, but 1% of 8,000 shares is 80 shares. The fixed 100-share order fails the volume screen, so the favorable next-session move earns the account zero. The second round trip, on S15, returns $11,064 after its sale fee against $11,080 spent including its buy fee, a net loss of $16.
The gross simulation grows $25,000 to $25,010, or +0.04%. The net simulation ends at $24,990, or −0.04%. Both returns use starting account value as the denominator and count exactly the same trades. The two round trips cost $20 in total, a difference of 0.08 percentage points. If the same trades cost $20 per round trip, net P&L would be −$30, or −0.12%. This changes execution cost on the completed trade ledger. Testing the policy under a new cost model calls for applying it during fitting too.
Evaluate Results Beyond the Headline Return
Pair net return with the number of trades, turnover, time in the market and maximum drawdown. Drawdown measures a decline from an earlier account peak. In the example, the highest end-of-session net account value is $25,006 and the later low is $24,990. The drawdown is $16 ÷ $25,006, about 0.064%. End-of-session marks can miss deeper losses while a position is open.
Compare against a benchmark over the same dates and use a consistent return basis. Cash earned 0% in this example. If you use buy-and-hold, account for dividends consistently and disclose the difference in market exposure. To assess robustness, compare nearby thresholds and other preplanned windows, look for dependence on a single trade or regime, and rerun plausible spread and slippage assumptions. Two held-out trades do not provide a reliable estimate of what the strategy can earn. A forward paper test can check the workflow on newly arriving data, with execution still subject to the fill model. [1] [2] [10]
Common Backtesting Mistakes
- Look-ahead bias. Feeding a 10 a.m. order that day’s final volume gives the simulation information unavailable at the time. Later data revisions and trade outcomes that cross the training cutoff can create the same problem. Compare availability time with decision time. [3] [4] [5]
- Survivorship bias. Begin with today’s surviving universe and you can miss companies that delisted or left the index. Use historical eligibility and record what happened to each position when the security changed or left. [6] [7]
- Data snooping. Try enough variants and a profitable one can emerge by chance. Record the full search and keep the final holdout outside it. [1]
- Counting unavailable trades. Charging a cost on top of a midpoint is insufficient if the order would have been too large, too late or unfilled. Track which orders the model would have filled as well as the prices it assigns them. [2] [8] [10]
Frequently Asked Questions
Daily prices can support a signal and a coarse test when you state the next available price reference and fill assumptions. For an intraday rule, an apparent crossing of a stop or limit in a daily bar cannot tell you the sequence of prices or whether your order could fill. A stock-selection rule also needs historical eligibility when the universe changes. [2] [6] [9]
Look for enough decision and trade outcomes across market conditions relevant to the rule. Many price observations can yield only a few trades, and several trades driven by the same market move provide less distinct evidence than their count suggests. Report dates, sample size and trade count for the holdout. [1] [3]
Sources
- Bailey, Borwein, López de Prado and Zhu, The Probability of Backtest Overfitting, author manuscript, November 2014.
- SEC Investor.gov, Understanding Order Types, updated August 18, 2026.
- Hyndman and Athanasopoulos, Forecasting: Principles and Practice, §5.10.
- SEC, EDGAR Timestamps.
- Federal Reserve Bank of St. Louis, FRED and ALFRED Real-Time Periods.
- S&P Dow Jones Indices, September 2026 S&P 500 Constituent Changes, September 4, 2026.
- Shumway, The Delisting Bias in CRSP Data, March 1997.
- NYSE, Auctions and Auction Timelines.
- NYSE, Daily Trade and Quote Data.
- Frazzini, Israel and Moskowitz, Trading Costs, August 23, 2018.
This article is for educational purposes. The worked example uses fictional prices, volumes and fills. Historical simulations do not predict future returns.
