Strategies and backtests

How to backtest a trading strategy: the steps, the mistakes and a real example

A backtest replays a trading rule on past prices to show what it would have done. Here is how to run one properly, the mistakes that make backtests lie, the tools, and a real backtest on a year of NVDA prices, including the parts that did not work.

[

Updated November 16, 2026

]
•
[

19

 

min to read

]

The short answer

To backtest a trading strategy, write the rule precisely enough for a computer to follow, run it on past prices with trading costs included, and read the return, max drawdown, number of trades and time in the market next to buy and hold. Then test it again on data it has never seen, and on paper, before risking money.

What is backtesting, and what can’t it tell you?

A backtest is a simulation. You take a trading rule, run it over past prices, and record every trade it would have made: when it bought, when it sold, what each trade earned or lost, and how the account grew or shrank along the way. TradingView’s documentation describes backtesting as a way to evaluate “the past performance of a trading strategy or model by simulating and analyzing its results on historical market data.”

Done well, it is the cheapest way to kill a bad idea. In minutes it shows what you would otherwise learn with real money: how often the rule trades, how deep its losing stretches go, and whether it did any better than simply buying and holding the same market over the same dates.

What it can’t do is tell you the future. A backtest measures one path the market already took, under assumptions you chose. Change the dates, the market or the costs and the answer can flip, as the real example below shows. TradingView’s own docs warn that simulated results may not fully account for real-world factors, and that no strategy’s past performance can be counted on to continue. Asking an AI assistant to run one adds its own wrinkle: our guide to AI backtesting covers when ChatGPT or Claude actually runs the numbers, and when they just describe a plausible result.

Backtesting terms
TermWhat it means
BacktestRunning a fixed rule on past prices to see what it would have done.
Buy and holdBuying on the first day and holding to the last. It is the plain benchmark a rule has to beat to be worth the effort.
Out-of-sample testRunning the same rule, unchanged, on data you did not use to build or tune it.
Forward test, or paper tradingRunning the rule on live prices as they arrive, with simulated money.

How do you backtest a trading strategy, step by step?

Seven steps, in this order. The first is where most backtests go wrong.

  1. Write the rule precisely.

    “Buy when it looks oversold” is not a rule. “Buy at the next day’s open when the daily RSI(14) closes below 30” is. Write down the market, the timeframe, the entry, the exit, the position size and any stop, so a computer could follow it with no judgment calls.

  2. Pick the market, the data and the period.

    Use the data you would actually trade on, and know what it is: which venue, which time zone, whether it includes weekends, whether stock prices are adjusted for splits. Choose a period with rises, falls and flat stretches, not one clean rally.

  3. Set costs and slippage before you run.

    Every buy and sell pays a fee and usually a spread. Slippage is the gap between the price you wanted and the price you got. Perpetual futures also pay or receive funding while you hold them. TradingView’s strategy tester charges no commission and no slippage unless you set them.

  4. Run it without peeking.

    Each decision may only use data that existed at that moment. If the signal comes from a day’s close, the trade happens after that close, at the next open. That is also how TradingView fills orders on past bars by default.

  5. Read the results next to buy and hold.

    Total return, max drawdown, number of trades, win rate and time in the market, all compared with what holding the market did over the same dates. The table below says what each one tells you.

  6. Test it out of sample.

    Run the unchanged rule on a later period and on other markets. If you tuned anything in the steps above, this is the test that counts. Our guide to quantitative trading shows a rule that looked fine on the data it was fitted on, then failed this test.

  7. Forward test before real money.

    Paper trade it on live prices for a while. TradingView’s docs point out that a forward test can’t suffer from look-ahead bias, because there is no future data to leak into it. Our paper trading guide covers testnets, demo accounts and a 30-day plan.

What each number tells you

What each backtest number measures
NumberWhat it measuresWhat to watch for
Total returnHow much the account grew or shrank over the test.Compare it with buy and hold over the same dates, not with zero.
Max drawdownThe worst fall from a peak to a low, in percent.Ask whether you could sit through it. A live drawdown can be deeper than any in the past.
Number of tradesHow many times the rule bought and sold.With a handful of trades, one lucky trade decides the result.
Win rateThe share of closed trades that made money.Means little alone: many small wins can be erased by one large loss.
Time in the marketThe share of days the rule held a position.A rule that sits in cash looks good in a falling market and lags in a rising one.
Buy and holdBuying on day one and holding to the end.The benchmark. If a rule can’t beat it, ask what the rule is for: a smaller drawdown can be a reason, but say so.

What does a real backtest look like?

Here is one backtest, run start to finish on real prices. The rule is a textbook one: the RSI, or Relative Strength Index, a 0 to 100 gauge of how strongly a market has moved up or down over its recent closes. J. Welles Wilder published it in his 1978 book New Concepts in Technical Trading Systems and treated readings under 30 as oversold and over 70 as overbought, as StockCharts’ ChartSchool explains.

The rule, written so a computer can follow it

  • Market: xyz:NVDA, a perpetual futures contract (a “perp”, a futures contract with no expiry date) on trade.xyz, an exchange built on Hyperliquid. trade.xyz lists it as referencing one NVIDIA share, quoted in US dollars.
  • Data: daily candles from Hyperliquid’s public API, November 12, 2025 to November 13, 2026, taken on November 14, 2026. We dropped the November 14 candle, which was still open.
  • Signal: RSI over 14 daily closes, with Wilder’s smoothing.
  • Entry: when not holding and RSI closes below 30, buy at the next day’s open.
  • Exit: when holding and RSI closes above 70, sell at the next day’s open.
  • Size: the whole account, $10,000 at the start. Long only, no leverage, no stop.
  • Costs: 0.1% of the trade’s value on every buy and every sell, to stand in for fees and slippage. Funding is not included.
  • Test window: November 26, 2025 to November 13, 2026, 353 days, starting once RSI had its first 14 days of data.
$8k$10k$12k$14kNov 2025May 2026Nov 2026BuySellBuyRSI ruleBuy and hold$8k$10k$12k$14kNov 2025Nov 2026RSI ruleBuy and hold
Value of $10,000 following the RSI rule (solid line) and buying and holding (dashed), November 26, 2025 to November 13, 2026. Dots mark each buy and sell. A simulation on past data.Daily candles of xyz:NVDA from Hyperliquid’s public API, taken November 14, 2026; Ethy’s calculation.
Results of the RSI rule against buy and hold on xyz:NVDA
RSI ruleBuy and hold
Return, including costs+2.2%-10.5%
Return with no costs+2.5%-10.4%
Max drawdown, on daily closes-16.6%-33.2%
Trades2 (1 still open at the end)1 buy
Winning trades1 of 1 closedNot applicable
Time in the market21.5% of days100% of days
Every trade the RSI rule made
TradeSignalBoughtSoldResult
1RSI closed at 27.7 on Feb 5Feb 6 at $170.32Apr 15 at $196.08, after RSI closed at 70.4+14.9%
2RSI closed at 22.8 on Nov 5Nov 6 at $180.82Still open, valued at the Nov 13 close of $160.94-11.1%

What the result says, and what it doesn’t

On the headline number the rule won: +2.2% against -10.5% for buy and hold, with half the drawdown. It would be easy to stop there. Look at what produced that number first:

  • Two trades. RSI closed under 30 on only 9 of 353 days, so the rule traded twice in a year. One closed trade can’t tell a pattern from luck.
  • Cash did most of the work. The rule held a position on 21.5% of days, so it sat out most of the October and November slide. A rule that is mostly in cash will look good next to holding whenever the test happens to end after a fall.
  • No stop means long waits. The first trade was up about 15% on February 25, gave all of it back, and was about 4% under water at the March 30 close. It only came back because NVDA rallied before RSI closed above 70 on April 14.
  • It missed the rally. After the April exit, the NVDA perp climbed to $240.19 by October 5 while the rule waited in cash, because RSI didn’t close under 30 again until November 5.
  • Oversold got more oversold. The second trade bought into a fall that kept going: RSI sank to about 21 on November 11. StockCharts makes the same point: momentum readings can stay oversold in a strong downtrend.
  • Costs barely mattered, this time. With no costs the rule shows +2.5% instead of +2.2%, only because it traded twice. A rule that trades every week pays costs every week.
How the end date changes the result
Stop the test onRSI ruleBuy and hold
Oct 5, 2026+14.9%+33.6%
Nov 6, 2026+19.4%+4.6%
Nov 13, 2026+2.2%-10.5%

Same rule, same data, and the verdict flips with the day you stop counting: buy and hold wins by a mile on October 5, the rule wins on November 6, and both shrink by November 13. That isn’t a flaw of this example. It is what any backtest with two trades looks like.

Does the same rule hold up on other markets?

Testing on data the rule wasn’t built on is the out-of-sample step. We tuned nothing (14, 30 and 70 are Wilder’s textbook settings), so the honest next check is to run the identical rule, over the same dates and with the same costs, on other markets from the same snapshot.

The RSI(14) 30/70 rule on seven markets, Nov 26, 2025 to Nov 13, 2026, 0.1% per buy and per sell
MarketTradesRSI ruleBuy and holdRule max drawdownTime in market
NVIDIA2 (1 open)+2.2%-10.5%-16.6%21.5%
Tesla2+37.7%-9.3%-20.2%53.4%
XYZ100 index2 (1 open)+19.2%+9.6%-2.5%7.1%
Bitcoin2 (1 open)-16.1%-24.6%-28.7%56.9%
Ether2 (1 open)-13.8%-36.3%-36.1%57.5%
Solana3 (1 open)-14.3%-45.4%-26.2%54.4%
HYPE1+40.3%+97.5%-25.7%11.9%

The same rule and costs as above, on Hyperliquid daily candles taken November 14, 2026, with RSI computed from the first candle each market has in that data: October 2025 for the crypto markets and XYZ100, November 2025 for NVIDIA and Tesla (Tesla’s test starts a day later, on November 27, 2025, its first full RSI reading; XYZ100 is trade.xyz’s index of 100 large US non-financial stocks). Read it slowly:

  • The rule beat buy and hold in 6 of 7 markets, and still lost money in 3 of them (Bitcoin, Ether and Solana). Losing less than a falling market is not the same as making money.
  • In the market that roughly doubled, HYPE, the rule made +40.3% against +97.5% for holding.
  • Across all seven markets it made 14 trades, and 5 were still open at the end. That is far too few to call any of this an edge.
  • Had we shown you only Tesla (+37.7% against -9.3%), the rule would look brilliant. Picking the market that worked after the fact is selection bias, and TradingView’s docs warn against it: test on “multiple, ideally diverse datasets” and avoid “cherry-picking” testing ranges.

The lesson is the method, not the rule. A year of daily data shows how a slow signal like this behaves; it can’t show whether it works. To judge it you would need many more trades: more years, more markets, or a faster timeframe, each with its own costs. For more rules tested this way, see six automated Hyperliquid strategies, backtested.

Which mistakes make a backtest look better than it is?

These are the classic ones. Each makes the past look kinder than trading the rule will be.

Overfitting, or curve fitting

Overfitting means tuning a rule until it fits the noise of the past instead of a pattern that repeats. Try enough settings and one will look great by chance. David Bailey and Marcos López de Prado, with Jonathan Borwein and Qiji Zhu, worked out how fast this happens. Their yardstick is the Sharpe ratio, a strategy’s average return divided by how much that return swings. With five years of data, trying 45 independent variations of a rule with no real edge is enough to expect the best one to show a Sharpe ratio of 1 in the backtest, while its expected result on new data is zero. With two years of data, 7 variations are enough. Their conclusion: a backtest that doesn’t say how many variations were tried can’t be judged.

Real strategies show the same gap. Researchers at Quantopian, a platform where users wrote and tested trading algorithms, compared the backtests of 888 algorithms with at least six months of results after them. The backtest Sharpe ratio explained almost none of what came next (an R² under 0.025), and the more a strategy had been backtested, the bigger the gap between its backtest and what followed.

Look-ahead bias

Using information the rule could not have had at the time: buying at the same close that produced the signal, using a day’s high or low before the day is over, or reading a higher timeframe’s candle before it has closed. TradingView calls it the leakage of future data into the past and lists it among the common causes of unrealistic strategy results. Act on the next bar, and forward test, where there is no future to leak.

Survivorship bias

Testing only what still exists today. Backtest a stock rule on today’s index members and you leave out the companies that collapsed and were dropped, so the past looks better than it was. Edwin Elton, Martin Gruber and Christopher Blake documented the same effect in mutual funds: funds that disappear tend to do so because of poor performance, which flatters any study that looks only at the survivors. In crypto, the same goes for coins that were delisted. Use lists of what existed at each point in time, dead names included.

Too few trades

As in the example above. A handful of trades can’t separate skill from luck. Get more trades from more history, more markets or a faster timeframe, and look at the spread of results, not the best one.

Ignoring costs

Fees, spreads, slippage and funding come out of every trade. Pierre Bajgrowicz and Olivier Scaillet tested technical trading rules on the Dow Jones Industrial Average from 1897 to 2011 and found that, even in sample, their performance was “completely offset by the introduction of low transaction costs.” TradingView’s docs show the same thing on a small scale: adding a 1% commission to their demo strategy significantly cut its net profit and deepened its drawdown.

Changing the rule after seeing the results

Each time you tweak a rule because the last result disappointed, you run a new test on the same data, and the version you keep inherits every try before it. That is the trial count Bailey and his co-authors say a backtest must report. Write the rule down first, run it once, and if you change it, test the new version on data it has never seen.

Backtesting mistakes, how to spot them and how to fix them
MistakeThe signThe fix
OverfittingGreat results that vanish when you nudge a settingFew settings, chosen before you test; count every try
Look-ahead biasFills at prices the rule could not have knownAct on the next bar; forward test
Survivorship biasOnly markets that still exist todayUse lists that include delisted names
Too few tradesOne or two trades decide the resultMore history, more markets or a faster timeframe
Ignoring costsProfits that come from many small tradesCharge fees, spread and slippage on every fill
Editing the rule after the factThe tenth version is the one you keptWrite it first; test any change on fresh data
Cherry-pickingThe one market or period that workedShow every market and period you tried
Synthetic chartsTests on Heikin Ashi or Renko candlesTest on standard candles; TradingView says the others typically give unrealistic results

Which tools can you use to backtest a strategy?

Pick the tool by how much you want to write yourself. Each can do the job; they differ in what you must supply and what they assume for you. For a longer comparison, see best backtesting software.

Backtesting tools compared
ToolGood forYou needWatch out for
A spreadsheetLearning, and simple daily rulesPrice data and patienceIt is easy to let tomorrow’s price slip into today’s formula
TradingView strategy testerChart traders; built-in and community strategies on many marketsPine Script, TradingView’s language, to write your ownNo commission and no slippage unless you set them; higher bar detail needs a Premium or Ultimate plan
backtrader (Python)Event-by-event simulation in a long-standing open-source libraryPythonIts latest release on PyPI dates from April 2023
vectorbt (Python)Testing many variants at once on pandas data; its site says thousands of strategies in secondsPython and pandasThat speed makes overfitting easy, so count your tries; some features, such as leverage, are in the paid PRO version
No-code buildersClicking a rule together from indicatorsAn account with the providerCheck which data, fills and costs they assume
EthyDescribing a rule in plain English and testing it on Hyperliquid markets or spot tokensNothing to codeWindows depend on the timeframe, up to 365 days

How to backtest on TradingView

  1. Open a standard candle chart of the market and timeframe you want to test (not Heikin Ashi or Renko).
  2. Add a strategy: a built-in one, a community script, or your own in Pine Script, where a strategy script places its simulated orders with commands such as strategy.entry.
  3. In the strategy’s Settings, on the Properties tab, set your commission and slippage (both zero by default), the order size and the starting capital.
  4. Read the strategy report that opens under the chart: the Metrics tab for profit, drawdown and trade counts, and the Trades tab for every simulated trade.
  5. Keep the most recent stretch of history aside, tune on the rest if you must, and check the final settings on the part you kept aside only once. TradingView’s docs describe this in-sample and out-of-sample split.

To have Claude read your TradingView charts instead, see how to connect Claude to TradingView.

Is backtesting accurate, and how much should you trust one?

A backtest is exact about the past and silent about the future. Given the same data, rule and costs, it gives the same answer every time. Whether that answer carries forward depends on things you can check:

  1. How many trades? Dozens across rising, falling and flat markets mean more than two in one year.
  2. How many tries? The best of 50 variations is weaker evidence than one rule written down in advance.
  3. Realistic costs and fills? Fees, spread, slippage and funding, at prices that were really available.
  4. Did it survive data it never saw? Later dates, other markets, then paper trading.
  5. Is there a reason it should work? A rule with a plain explanation is easier to trust than one found by searching thousands of combinations.

If you are weighing whether AI trading tools can make money at all, and how to tell a real one from a scam, read our guide to whether AI trading is legit.

How do you backtest a strategy in plain English with Ethy?

If you would rather not write code, you can describe the rule to Ethy the way you would to a person, for example the NVDA rule above in one sentence. Ethy turns it into rules you can preview, backtests the exact version it would run, and shows every entry and exit on the chart next to buy and hold. It covers Hyperliquid’s perps, trade.xyz’s stocks, indices and commodities included, and spot tokens.

  • Windows: up to 365 days, depending on the timeframe (180 or 365 days on the daily). The free plan runs the shortest window of each timeframe.
  • The numbers in this guide: return and the comparison with buy and hold; trades, wins and losses, win rate, profit factor and average hold; max drawdown, Sharpe, Sortino and Calmar; monthly returns; and the equity and drawdown curves.
  • Out of sample built in: the optimizer tries the rule’s settings, ranks them on a training window and checks each one on a held-out test window.
  • The same reading live: indicator conditions are checked when a bar closes, on the last closed candle, the same way the backtest reads them.
  • A forward test next: a tested strategy can run in paper mode, on live prices, without moving money.

Ethy presents backtest results as estimates on past data, not a promise. Everything above still applies: few trades, the end date and cherry-picking can fool any tool, ours included.

Summary

  • A backtest replays a fixed rule on past prices. It measures the past under your assumptions; it doesn’t forecast.
  • Write the rule precisely, include costs, act on the next bar, and read return, drawdown, trades and time in the market next to buy and hold.
  • Test the unchanged rule out of sample, on later dates and other markets, then forward test it on paper before real money.
  • Our real example, RSI(14) 30/70 on a year of NVDA perp prices, made +2.2% against -10.5% for buy and hold from just two trades, and the verdict flips with the end date. It is a simulation on past data.
  • Overfitting, look-ahead bias, survivorship bias, too few trades, ignored costs and editing the rule after the fact all make a backtest look better than trading.
  • Tools range from a spreadsheet and TradingView to Python libraries such as backtrader and vectorbt, and plain-English backtests in Ethy.

Questions people ask

Can you backtest a trading strategy for free?

Yes. A spreadsheet works for simple daily rules, and backtrader and vectorbt are free Python libraries (vectorbt also sells a PRO version). TradingView’s strategy tester runs built-in and community strategies; some deeper settings need a paid plan. On Ethy’s free plan, backtests run on the shortest window of each timeframe, 180 days on the daily.

How many trades does a backtest need?

There is no magic number, but more is better, and the results should hold across rising, falling and flat periods. One or two trades, as in our NVDA example, can’t separate a pattern from luck. If a slow rule trades rarely, add more history or more markets rather than tuning it until the few trades look good.

What is the difference between backtesting and paper trading?

A backtest runs the rule on past data all at once. Paper trading, or forward testing, runs it on live prices as they arrive, with simulated money. Paper trading is slower but can’t leak future data into the test, and it shows how fills and costs behave now. Do both, in that order, before real money.

Can ChatGPT or Claude backtest a trading strategy?

A chat assistant can write backtest code and explain results, but a number it states is only as good as the code and data behind it. Ask it to show the code, the data source and the full list of trades, then check a few trades by hand against the chart. A return with no trade list behind it is not a backtest.

Is backtesting worth it if it can’t predict the future?

Yes, as a filter. It is the cheapest way to learn that a rule loses money, trades too rarely or has drawdowns you couldn’t live with. What it can’t do is prove a rule will work. Treat a good result as a reason to keep testing, out of sample and on paper.

Should a backtest include funding on perpetual futures?

If you hold perp positions for days, yes: funding is a cost or a credit for as long as you hold. Our example left it out, which is one more reason to treat its numbers as a rough sketch rather than a trading record.

Sources

  1. TradingView, Pine Script User Manual: Strategies (broker emulator, commission, slippage, look-ahead and selection bias, overfitting)tradingview.com
  2. Bailey and López de Prado, How to Spot Backtest Overfitting (summary of Bailey, Borwein, López de Prado and Zhu, Notices of the AMS, 2014)davidhbailey.com
  3. Wiecki, Campbell, Lent and Stauth, All That Glitters Is Not Gold: Comparing Backtest and Out-of-Sample Performance on a Large Cohort of Trading Algorithms (2016)papers.ssrn.com
  4. Bajgrowicz and Scaillet, Technical Trading Revisited: False Discoveries, Persistence Tests, and Transaction Costs, Journal of Financial Economics (2012)doi.org
  5. Elton, Gruber and Blake, Survivor Bias and Mutual Fund Performance, Review of Financial Studies (1996)doi.org
  6. trade.xyz, Specification Index (NVDA contract and session hours)docs.trade.xyz
  7. Hyperliquid Docs, Info endpoint (candle snapshot)hyperliquid.gitbook.io
  8. StockCharts ChartSchool, Relative Strength Index (RSI)chartschool.stockcharts.com
  9. vectorbt documentationvectorbt.dev
  10. backtrader on PyPI (release history)pypi.org

Trading involves risk, including the loss of your money. Ethy AI is a research and trading tool and does not give investment advice or recommendations. Backtests are simulations on historical data and do not predict future results.

Ethy blog

Read more

The $ETHY ecosystem

Stop watching charts.
Start living.

Deploy your AI trading agent in one click.