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
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.
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.
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.
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.
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.
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.
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.
1//@version=52strategy("Equity Overlay", overlay=false,3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,4 default_qty_value=95, commission_value=0.075)56// === 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")1314// === EQUITY CURVE ===15equity = strategy.equity16equityMA = ta.sma(equity, 20)1718plot(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)2223// === DRAWDOWN ===24var float peak = strategy.initial_capital25peak := math.max(peak, equity)26drawdown = (peak - equity) / peak * 1002728plot(-drawdown, "Drawdown %", color.new(color.red, 30), 1,29 plot.style_area)3031// === 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.
1//@version=52strategy("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)56// === 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")1112// === MONTHLY TRACKING ===13var float[] monthlyReturns = array.new_float(0)14var int[] monthLabels = array.new_int(0)15var float monthStart = strategy.initial_capital1617newMonth = ta.change(time("M")) != 01819if newMonth and bar_index > 020 monthReturn = (strategy.equity - monthStart) / monthStart * 10021 array.push(monthlyReturns, monthReturn)22 array.push(monthLabels, month(time[1]))23 monthStart := strategy.equity2425// === TABLE ===26if barstate.islast27 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)3031 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)3435 cumReturn = 0.036 startIdx = math.max(0, array.size(monthlyReturns) - 12)37 for i = startIdx to array.size(monthlyReturns) - 138 ret = array.get(monthlyReturns, i)39 cumReturn += ret40 row = i - startIdx + 141 mLabel = array.get(monthLabels, i)42 clr = ret >= 0 ? color.green : color.red4344 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.
1//@version=52strategy("Drawdown Tracker", overlay=false,3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,4 default_qty_value=95, commission_value=0.075)56// === 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")1112// === DRAWDOWN CALCULATIONS ===13equity = strategy.equity14var float peak = strategy.initial_capital15peak := math.max(peak, equity)1617drawdownPct = (peak - equity) / peak * 10018inDrawdown = equity < peak1920// Duration counting21var int ddBars = 022var int maxDdBars = 023if inDrawdown24 ddBars += 125 maxDdBars := math.max(maxDdBars, ddBars)26else27 ddBars := 02829// Max drawdown tracking30var float maxDD = 0.031maxDD := math.max(maxDD, drawdownPct)3233// === 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))3940// === DASHBOARD ===41var table dd = table.new(position.top_right, 2, 4,42 bgcolor=color.new(color.black, 80), border_width=1)43if barstate.islast44 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.
1//@version=52strategy("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)78lookback = 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")1213prevHigh = ta.highest(high, lookback)[1]14prevLow = ta.lowest(low, lookback)[1]15rsi = ta.rsi(close, rsiLen)16atr = ta.atr(14)1718// Fade the upside breakout: go short when price breaks above previous high19// but RSI is already overbought (exhaustion signal)20fadeShort = close > prevHigh and rsi > rsiOB21if fadeShort22 strategy.entry("Fade S", strategy.short)23 strategy.exit("Fade SL", "Fade S",24 limit = ta.ema(close, 21), // Target: mean25 stop = close + atr * atrMult) // Stop above2627// Fade the downside breakout: go long when price breaks below previous low28// but RSI is already oversold29fadeLong = close < prevLow and rsi < (100 - rsiOB)30if fadeLong31 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)3536// Time exit37if strategy.position_size != 038 if bar_index - strategy.opentrades.entry_bar_index(0) > 1039 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:
| Repainting | Some 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 Bias | Using 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 Fills | The 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 Bias | You 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 Fitting | Running 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 Trades | A 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
Put this lesson to work
Free on Thrive, no account needed.