Skip to main content

Backtesting & Performance Analysis

Backtesting fundamentals, displaying backtest results on chart, monthly performance tables, calculating drawdown duration, and why you should never blindly trust the Strategy Tester.

From Thrive on YouTube

Watch the matching Thrive video

More on YouTube
On-Chain Analysis Explained: The Complete Guide for Crypto Traders

On-Chain Analysis Explained: The Complete Guide for Crypto Traders

Education only. Not financial advice.

What Makes a Valid Backtest

A valid backtest is not just a profitable equity curve. It is a statistically meaningful sample of trades executed under realistic conditions with proper out-of-sample validation. Most retail traders run a backtest, see green numbers, and start trading with real money. This is a recipe for disaster. You need to understand sample size, market regime, and validation methodology before trusting any backtest result.

Minimum Trade Count

You need at least 30 trades for basic statistical significance. Ideally 100+. A strategy with 10 trades and 80% win rate tells you almost nothing. It could be pure luck.

In-Sample vs Out-of-Sample

Develop your strategy on 70% of your data (in-sample). Test the unchanged strategy on the remaining 30% (out-of-sample). If performance degrades drastically, you have curve-fit.

Walk-Forward Analysis

Divide history into segments. Optimize on segment 1, test on segment 2. Optimize on segments 1+2, test on segment 3. This simulates real-world development.

Realistic Assumptions

Include commissions (0.075–0.1% per trade), slippage (2–5 ticks), and realistic position sizes. A strategy that makes 0.1% per trade is destroyed by 0.15% round-trip costs.

Multiple Market Regimes

Test across trending and ranging markets, bull and bear cycles. A BTC strategy developed during 2020–2021 will likely fail in 2022 bear conditions if not regime-aware.

Sensitivity Analysis

Change key parameters by ±20%. If performance collapses, your strategy is fragile and likely curve-fit. Robust strategies degrade gracefully.

Displaying Backtest Results on Chart

While the Strategy Tester shows the equity curve in its own panel, you can also plot equity, drawdown, and trade markers directly on your price chart for a more integrated view. This is especially useful for understanding how your strategy performs relative to price action. You can see exactly which market conditions produce wins and which produce losses.

pine-Equity curve overlay and trade markers
1//@version=5
2strategy("Equity Overlay", overlay=false,
3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,
4 default_qty_value=95, commission_value=0.075)
5
6// === SIMPLE STRATEGY (for demonstration) ===
7fast = ta.ema(close, 9)
8slow = ta.ema(close, 21)
9if ta.crossover(fast, slow)
10 strategy.entry("L", strategy.long)
11if ta.crossunder(fast, slow)
12 strategy.close("L")
13
14// === EQUITY CURVE ===
15equity = strategy.equity
16equityMA = ta.sma(equity, 20)
17
18plot(equity, "Equity", color.new(color.green, 0), 2)
19plot(equityMA, "Equity MA", color.new(color.yellow, 40), 1)
20plot(strategy.initial_capital, "Starting Capital",
21 color.new(color.gray, 60), 1, plot.style_line)
22
23// === DRAWDOWN ===
24var float peak = strategy.initial_capital
25peak := math.max(peak, equity)
26drawdown = (peak - equity) / peak * 100
27
28plot(-drawdown, "Drawdown %", color.new(color.red, 30), 1,
29 plot.style_area)
30
31// === HIGHLIGHT LOSING PERIODS ===
32bgcolor(equity < equityMA ? color.new(color.red, 95) : na)

Monthly Performance Table

A monthly P&L table gives you a calendar view of performance. You can see which months are consistently profitable and which are not. This reveals seasonality patterns and helps set realistic expectations. Building this in PineScript requires tracking equity at the start and end of each month using arrays and rendering the results in a table.

pine-Monthly performance table
1//@version=5
2strategy("Monthly P&L Table", overlay=true,
3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,
4 default_qty_value=95, commission_value=0.075)
5
6// === STRATEGY (simple for demo) ===
7if ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
8 strategy.entry("L", strategy.long)
9if ta.crossunder(ta.ema(close, 9), ta.ema(close, 21))
10 strategy.close("L")
11
12// === MONTHLY TRACKING ===
13var float[] monthlyReturns = array.new_float(0)
14var int[] monthLabels = array.new_int(0)
15var float monthStart = strategy.initial_capital
16
17newMonth = ta.change(time("M")) != 0
18
19if newMonth and bar_index > 0
20 monthReturn = (strategy.equity - monthStart) / monthStart * 100
21 array.push(monthlyReturns, monthReturn)
22 array.push(monthLabels, month(time[1]))
23 monthStart := strategy.equity
24
25// === TABLE ===
26if barstate.islast
27 rows = math.min(array.size(monthlyReturns), 12)
28 var table perfTable = table.new(position.bottom_right,
29 3, rows + 1, bgcolor=color.new(color.black, 80), border_width=1)
30
31 table.cell(perfTable, 0, 0, "Month", text_color=color.gray, text_size=size.small)
32 table.cell(perfTable, 1, 0, "Return %", text_color=color.gray, text_size=size.small)
33 table.cell(perfTable, 2, 0, "Cum %", text_color=color.gray, text_size=size.small)
34
35 cumReturn = 0.0
36 startIdx = math.max(0, array.size(monthlyReturns) - 12)
37 for i = startIdx to array.size(monthlyReturns) - 1
38 ret = array.get(monthlyReturns, i)
39 cumReturn += ret
40 row = i - startIdx + 1
41 mLabel = array.get(monthLabels, i)
42 clr = ret >= 0 ? color.green : color.red
43
44 table.cell(perfTable, 0, row, str.tostring(mLabel),
45 text_color=color.white, text_size=size.small)
46 table.cell(perfTable, 1, row, str.tostring(ret, "#.##") + "%",
47 text_color=clr, text_size=size.small)
48 table.cell(perfTable, 2, row, str.tostring(cumReturn, "#.##") + "%",
49 text_color=cumReturn >= 0 ? color.green : color.red,
50 text_size=size.small)

Calculating Drawdown Duration

Maximum drawdown depth tells you how much you can lose. Drawdown duration tells you how long you will be underwater. Most traders can stomach a 15% drawdown that recovers in 2 weeks. Few can handle a 15% drawdown that lasts 6 months. Tracking duration is critical for psychological preparedness and realistic expectation-setting.

pine-Drawdown depth and duration tracker
1//@version=5
2strategy("Drawdown Tracker", overlay=false,
3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,
4 default_qty_value=95, commission_value=0.075)
5
6// === STRATEGY ===
7if ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
8 strategy.entry("L", strategy.long)
9if ta.crossunder(ta.ema(close, 9), ta.ema(close, 21))
10 strategy.close("L")
11
12// === DRAWDOWN CALCULATIONS ===
13equity = strategy.equity
14var float peak = strategy.initial_capital
15peak := math.max(peak, equity)
16
17drawdownPct = (peak - equity) / peak * 100
18inDrawdown = equity < peak
19
20// Duration counting
21var int ddBars = 0
22var int maxDdBars = 0
23if inDrawdown
24 ddBars += 1
25 maxDdBars := math.max(maxDdBars, ddBars)
26else
27 ddBars := 0
28
29// Max drawdown tracking
30var float maxDD = 0.0
31maxDD := math.max(maxDD, drawdownPct)
32
33// === PLOTS ===
34plot(-drawdownPct, "Current DD %", color.new(color.red, 30), 2, plot.style_area)
35hline(0, "Zero", color.new(color.gray, 60))
36hline(-5, "-5%", color.new(color.yellow, 60))
37hline(-10, "-10%", color.new(color.orange, 60))
38hline(-20, "-20%", color.new(color.red, 60))
39
40// === DASHBOARD ===
41var table dd = table.new(position.top_right, 2, 4,
42 bgcolor=color.new(color.black, 80), border_width=1)
43if barstate.islast
44 table.cell(dd, 0, 0, "Current DD", text_color=color.gray)
45 table.cell(dd, 1, 0, str.tostring(drawdownPct, "#.##") + "%", text_color=color.red)
46 table.cell(dd, 0, 1, "Max DD", text_color=color.gray)
47 table.cell(dd, 1, 1, str.tostring(maxDD, "#.##") + "%", text_color=color.red)
48 table.cell(dd, 0, 2, "Current Duration", text_color=color.gray)
49 table.cell(dd, 1, 2, str.tostring(ddBars) + " bars", text_color=color.orange)
50 table.cell(dd, 0, 3, "Max Duration", text_color=color.gray)
51 table.cell(dd, 1, 3, str.tostring(maxDdBars) + " bars", text_color=color.orange)

Fading the Breakout: Contrarian Testing

One powerful use of backtesting is testing contrarian ideas. If breakout strategies are popular, what happens if you fade them. Sell when breakout traders buy? In crypto, where fake breakouts are common due to stop hunting and liquidation cascades, fading breakouts can be surprisingly profitable on shorter timeframes. This strategy sells when price breaks above the 20-bar high, betting on a reversal.

pine-Fading breakouts: contrarian backtest
1//@version=5
2strategy("Fade the Breakout", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.percent_of_equity,
5 default_qty_value=90,
6 commission_value=0.075, slippage=3)
7
8lookback = input.int(20, "Breakout Lookback")
9rsiLen = input.int(7, "RSI Length")
10rsiOB = input.int(75, "RSI Overbought")
11atrMult = input.float(1.5, "ATR Stop Mult")
12
13prevHigh = ta.highest(high, lookback)[1]
14prevLow = ta.lowest(low, lookback)[1]
15rsi = ta.rsi(close, rsiLen)
16atr = ta.atr(14)
17
18// Fade the upside breakout: go short when price breaks above previous high
19// but RSI is already overbought (exhaustion signal)
20fadeShort = close > prevHigh and rsi > rsiOB
21if fadeShort
22 strategy.entry("Fade S", strategy.short)
23 strategy.exit("Fade SL", "Fade S",
24 limit = ta.ema(close, 21), // Target: mean
25 stop = close + atr * atrMult) // Stop above
26
27// Fade the downside breakout: go long when price breaks below previous low
28// but RSI is already oversold
29fadeLong = close < prevLow and rsi < (100 - rsiOB)
30if fadeLong
31 strategy.entry("Fade L", strategy.long)
32 strategy.exit("Fade SL L", "Fade L",
33 limit = ta.ema(close, 21),
34 stop = close - atr * atrMult)
35
36// Time exit
37if strategy.position_size != 0
38 if bar_index - strategy.opentrades.entry_bar_index(0) > 10
39 strategy.close_all(comment="Time exit")

Why You Should NEVER Blindly Trust the Strategy Tester

The Strategy Tester is an incredibly useful tool, but it is also the most dangerous tool in a trader's arsenal if misunderstood. A beautiful equity curve with a 90% win rate is more likely a sign of a broken backtest than a profitable strategy. Here are the critical pitfalls:

RepaintingSome indicators change their historical values as new bars come in. If your strategy uses a repainting indicator, it looks perfect in the backtest but produces different signals in real time. Always use confirmed (closed bar) values with [1] offset or barstate.isconfirmed checks.
Lookahead BiasUsing request.security() without lookahead=barmerge.lookahead_off and the [1] offset trick causes your strategy to "see" future data. It will appear to predict the market perfectly, because it literally uses data from the future.
Unrealistic FillsThe backtester assumes your limit orders always fill. In reality, at key support/resistance levels, there may not be enough liquidity. A strategy that relies on precise fills at exact levels will underperform live.
Survivorship BiasYou only backtest on assets that still exist and trade today. You never test on coins that went to zero. This systematically biases your results upward, especially dangerous when testing "buy the dip" strategies on altcoins.
Curve FittingRunning an optimizer to find the "best" RSI length and overbought/oversold levels is guaranteed to find parameters that work on the past. These parameters are unlikely to work in the future. If your strategy requires precise parameters (RSI 13 works but RSI 14 doesn't), it is curve-fit.
Insufficient TradesA strategy with 8 trades and an 87.5% win rate (7 wins, 1 loss) is statistically meaningless. You cannot distinguish this from random chance. Demand 30+ trades minimum, 100+ preferred.

The backtesting reality check

Before going live with any strategy, ask yourself these questions: Does the strategy make logical sense, or is it just data mining? Would it have worked on different assets? What is the maximum drawdown, and can I psychologically handle it? Have I tested it out-of-sample? Have I paper traded it for at least 2 weeks? If you cannot answer yes to all of these, you are not ready to trade it with real money.

Put this lesson to work

Free on Thrive, no account needed.