How to Backtest a Trading Strategy (Step-by-Step Guide)

Welcome to The Long and the Short—a show where you can expect an honest take on trading. Something you won’t hear elsewhere. I’m Sandeep Rao.


Why Learn Backtesting?

Back in episode 6, we covered the what and the why of backtesting, its history, and the core concepts. Now is the time for the how part of it. This has been a highly requested topic, and today I’m covering it.

In this newsletter, I’ll walk you through step by step the precise methods and tools we use to run the backtests you see in many of our episodes. You will learn how to run them exactly like we do. With that, let’s get started.

The Two Tools We Use: TradingView + Claude AI

As always, I want to set the stage by introducing the two essential tools that make our backtesting process possible.

First, you need TradingView. This is an independent third-party platform for charting and, more importantly, for backtesting. I should mention that the TradingView charts you see on Zerodha Kite are just charts.

To run the backtests that I discuss, you need direct access to the TradingView platform itself. You can use the free tier, but at the moment I’m using a paid plan which simply gives me access to more longer history of data for more thorough backtesting.

We’ll use Claude for two key reasons: one, to write the backtesting script, which will be written in the Pine Script language, and two, we would need Claude to analyze the trade logs, which would come after the backtest. Again, you can use the free plan for Claude, but at the moment, I’m using a paid one.

Now here’s a disclaimer: this is not a paid promotion for either TradingView or for Claude. These are simply the tools that I use to run the backtests you see on this show. So with the disclaimers out of the way, now let’s get started with the key steps.

The Five Key Steps of Backtesting



Backtesting involves five key steps:

1. Hypothesis Selection or Creation

This means defining the specific strategy or idea you want to test. For example, you may want to test a trend-following strategy on Nifty. That could be one hypothesis. You can make it more specific by saying “long-only trend-following strategy on Nifty.” That’s also possible, which means you take only long signals and ignore the short signals.

2. Choosing the Method or Indicator

To create a trend-following strategy or to generate trend-following signals, you need a method. Two methods we’ve spoken about in the past are moving averages and using a breakout indicator like SuperTrend.

3. Code the Strategy in Pine Script

This is a step where we will use Claude AI to write the strategy code. You see, this is such a boon, right? I mean, earlier you had to write the code yourself, but now you don’t need to. Claude does an amazing job at it.

4. Run the Strategy in TradingView

Run the strategy across multiple timeframes to observe its initial performance and results. This is a very simple step.

5. Download and Analyze the Trade Logs

The most important step is to download and analyze the trade logs using Claude AI again to perform a deep analysis of the detailed trade history for further refinement.

The focus of this video would be on steps three to five, which includes the end-to-end demonstration of writing the Pine Script code using Claude, running the backtest, and doing the analysis of the trade logs generated by the TradingView platform.

Setting Up and Running the Backtest in TradingView

The process begins with logging into TradingView and opening your chosen symbol. For this demonstration, we’ll work with two instruments: Nifty spot and Gold M futures. Gold M will illustrate some specific points we’ll cover shortly, but let’s start with Nifty.



The Nifty spot chart displays standard timeframes—daily, hourly, and others—with a clean slate. No indicators are applied yet, and the chart remains uncluttered.

The first step in this process involves moving to Claude to write the strategy script. This forms the foundation for everything that follows.

Writing the Strategy Code with Claude

The next step is straightforward: prompt Claude with a simple request—” Write me a strategy indicator in Pine Script using SuperTrend.”

That’s it. Sonnet 4.5 handles the heavy lifting. Within moments, the code is generated on screen.

The output includes several default parameters that Claude has preset, along with additional configurable options. Once the code appears, copy it from the top of the response.

Implementing the Code

Back in TradingView, open the Pine Editor from the toolbar. Within the editor, create a new strategy. The editor displays some default code—delete this entirely and paste the code copied from Claude.

After pasting, click to compile the script. The result: a functioning SuperTrend strategy appears in your editor. Click Save to preserve the work.



Seeing the Strategy in Action

Once saved and applied, the chart transforms. Long and short position markers now populate the price chart, indicating where the strategy would have triggered entry and exit signals based on the SuperTrend indicator.

Configuring Strategy Settings

With the strategy now active on the chart, the critical next step involves configuring the settings correctly. Click on the strategy name to access its settings menu.



Reviewing the Inputs

The Inputs tab displays the default parameters—these work fine for now. We’ll revisit and modify these later in the process.

Essential Properties Configuration



The Properties tab requires specific adjustments to ensure accurate calculations:

Currency: Change the setting to INR to match the instrument’s denomination.

Default Order Size: Set this to 75. This quantity serves as the baseline for all strategy calculations. While this number can vary, maintaining 75 ensures consistency across the backtesting process.

Order Execution Timing: Enable the “bar close” option. This setting ensures trades register only upon the completion of each bar, rather than triggering mid-bar. This approach provides more realistic backtesting results that align with actual trading conditions.

After making these adjustments, the strategy is properly configured and ready for testing.

Reviewing Strategy Performance

The strategy report provides a comprehensive view of performance metrics. Switching to percentage terms reveals the comparison between two approaches: the green line represents the equity curve of the strategy, while the blue line shows a simple buy-and-hold approach.

The numbers tell an interesting story. Holding the instrument from inception would have generated returns of 114%. Trading the strategy, however, would have yielded approximately 118%—a modest but meaningful outperformance.

Understanding Drawdowns

The bar chart below the equity curve illustrates drawdown periods—the peak-to-trough declines the strategy experienced. Notable drawdowns of 18% appear at multiple points throughout the backtest period.

Despite these drawdowns, the strategy demonstrates considerable merit when compared to buy-and-hold, particularly in how it manages these declines. The drawdown profile shows less severity than the buy-and-hold alternative, with the equity curve displaying relatively smoother declines during market corrections.

Performance Breakdown

The performance summary separates results by direction. Long positions contributed approximately 111% to overall returns, while short positions added just 7%. This disparity suggests the strategy could potentially function effectively without the short side—an insight worth exploring further.

Open P&L reflects the current running trade, which isn’t relevant for historical analysis.

The interface displays numerous additional parameters for tracking, though these can be reviewed on an as-needed basis. Many traders prefer calculating custom metrics from the raw trade logs—a process we’ll cover shortly. Still, these built-in metrics serve well for quick visual assessments of strategy performance.

Trade Analysis and Key Ratios

The trade analysis section contains essential statistics: total number of trades, open positions, winning and losing trades, and the percentage profitable (win rate). Average P&L per trade appears here as well.

The ratios section follows, displaying Sharpe ratio, Sortino ratio, profit factor, and margin call data—standard metrics for evaluating risk-adjusted returns.

Exporting Trade Data

The most critical component sits at the bottom: the complete list of trades. This granular data forms the foundation for deeper analysis. The next step involves exporting this trade list from TradingView and importing it into Claude for custom calculations and insights.

Using Claude AI to Parse Metrics & Build Reports

Exporting and Validating Trade Data

The download option appears at the top of the trade list. Click this to export the complete trade log from TradingView.

Moving to Claude for Analysis

With the file downloaded, return to Claude and upload the trade log. The first critical step involves verifying data integrity before proceeding with any analysis.

Prompt Claude with: “Can you please parse the data? Show me the five most recent trades from the log.”

Why This Verification Matters

This initial check serves as quality control. The five most recent trades displayed by Claude should match exactly what appears in the TradingView interface. Cross-reference the entry and exit points, timestamps, and P&L figures between Claude’s output and the original TradingView chart.

This verification step is non-negotiable. If discrepancies exist at this stage—if the data hasn’t been captured accurately—every subsequent calculation and insight will be compromised. Garbage in, garbage out.

Only after confirming the data matches perfectly should you proceed to deeper analysis.

Verifying Data Accuracy

Claude displays the most recent trade: a long position initiated on November 17th with an entry at 26,010.5. This trade remains active.

Cross-referencing with the TradingView chart confirms the accuracy. The chart shows the long entry marker at precisely 26,010—matching the close price of that specific candle. The data aligns perfectly.

Double-Checking with Previous Trades

A second verification adds confidence. The trade before the current one was a short position. Given this is a system that operates continuously, the exit of one trade corresponds to the entry of the next. The short position’s exit should therefore match the current long entry at 26,010—which it does.

Moving backward, that short trade’s entry occurred at 25,780 according to the log. Back on the chart, the short entry marker appears at the close of the candle at 25,780. Again, perfect alignment.

The Sanity Check Complete

These cross-checks—comparing the log data against actual chart markers—constitute the essential sanity test. The data has been captured correctly in the trade log. With this confirmation in place, the analysis can proceed with confidence that the underlying data is reliable.

Generating Performance Metrics

With data validation complete, the analysis moves to visualizing performance. The prompt to Claude: “Can you draw a cumulative P&L in terms of points based on this trade log? Also, draw a drawdown chart along with it.”



Claude processes the request and delivers more than asked. Along with the charts, it provides key performance metrics upfront: 331 trades executed over 5.9 years, accumulated returns of 118%, final equity value, total points gained, and maximum equity peak.

The equity curve appears first—a visual representation of cumulative profit and loss over time. Below it, the drawdown chart illustrates the decline from peak equity at various points throughout the testing period. This drawdown visualization in points wasn’t readily available in TradingView’s interface, making Claude’s automated generation particularly valuable.

Calculating Custom Metrics

Every trader has preferred metrics—specific measurements that reveal whether a strategy meets their risk and return criteria. Rather than manually calculating each one, the process can be streamlined.

The approach: provide Claude with a comprehensive list of desired metrics in a single prompt. “Can you read this list of 19 metrics and calculate it for me?”



Claude parses the request, identifies each metric, and performs the calculations based on the backtest data. Within moments, a complete performance summary appears.

The output includes everything specified: testing period, total P&L, win rate, total number of trades, average winning trade, average losing trade, return to maximum drawdown ratio, and all other requested metrics. This comprehensive view provides the foundation for evaluating whether the strategy meets investment criteria.

Creating Custom Reports

Beyond aggregate metrics, granular time-based analysis reveals patterns. The prompt: “Can you make a year and month-wise table in points with the total column for each year?”

Claude generates a comprehensive matrix showing P&L in points across every month and year of the backtest. The table displays performance for both long and short positions, with annual totals in the rightmost column.

The patterns emerge clearly: 2021 delivered subpar results, 2022 proved exceptional, while 2023, 2024, and 2025 showed relatively consistent performance levels. This temporal view helps identify whether the strategy’s edge remains stable or varies significantly across different market regimes.

The Power of Conversational Analysis

The true advantage of using Claude for trade log analysis lies in its flexibility. Any question about the data can be posed in natural language and answered immediately.

For example: “When was the longest streak of profitable trades and how many trades were those?”

The response arrives instantly: the longest winning streak consisted of seven consecutive profitable trades, running from March 13th through May 28th, 2024.

Unlimited Analytical Depth

This capability extends to virtually any metric or question imaginable. Want to know performance during specific market conditions? Ask. Curious about trade distribution by day of week? Ask. Need to understand drawdown recovery periods? Ask.

The beauty of analyzing trade logs through Claude lies in this conversational interface—no need to write custom scripts or build complex spreadsheets. The data answers whatever questions arise, transforming backtest analysis from a rigid, predefined process into a dynamic exploration.

Continuous Futures & Back-Adjusted Data Explained

The demonstration so far has focused on Nifty spot—a straightforward instrument for backtesting. The methodology, however, applies equally to derivatives. The next example illustrates how to run the same process on Gold M, a futures product.

Before proceeding with the Gold M backtest, an important concept requires explanation: continuous futures contracts.

Gold M represents a continuous futures series. To understand what this means and why it matters for backtesting…

Understanding Continuous Futures

Continuous futures data represents a single, extended price series constructed by stitching together multiple individual futures contracts.

At any moment, three active futures contracts trade simultaneously: the current month, next month, and the month thereafter—each carrying its own distinct price. In November, for instance, November, December, and January contracts all trade in parallel.

For charting and backtesting purposes, however, a single smooth and uninterrupted price series is essential. When analyzing historical data, the series should reflect what was then the current month contract at each point in time.

The Rollover Problem

A complication arises at contract expiration. When one monthly contract ends and the next begins, a price difference—called the spread—exists between the two series. This spread creates a gap in the data that doesn’t represent actual market movement.

Platforms address this through a process called back-adjustment.

How Back-Adjustment Works

Consider a practical example. On rollover day, suppose Nifty November futures trades at 25,800 while Nifty December futures trades at 25,950.



Simply switching from November to December would create a 150-point jump on the chart. This jump isn’t a real market move—it’s merely an artifact of changing contracts.



TradingView solves this through proportional back-adjustment. The platform divides the next month’s futures price by the current month’s price, then multiplies all previous historical prices by this factor.



Using the example: 25,950 divided by 25,800 equals 1.005814. Every historical price point before the rollover gets multiplied by this factor, effectively eliminating the artificial gap while preserving the relative price relationships throughout the series.



Applying Back-Adjustment in TradingView

With the concept of back-adjustment explained, the practical application in TradingView becomes straightforward. Before running any strategy on continuous futures, locate the adjustment button in the chart toolbar and activate it. This step is non-negotiable—the data must be back-adjusted before strategy testing begins.

Once clicked and highlighted, the historical price series has been properly adjusted to eliminate rollover gaps.

Optimizing Strategy Parameters

Navigate to the Strategy Tester and access the overall portfolio settings. Here, parameter optimization can begin.

In this example, the ATR period started at seven. Testing with a value of ten shows improved performance compared to two. This iterative process—adjusting parameters and observing results—helps identify optimal settings for the instrument.

Long, Short, or Both?

The position direction setting offers three options. The current selection shows long-only trades. Switching to short-only reveals poor performance for this particular strategy on gold. Enabling both long and short naturally produces better returns than long-only, though the improvement depends on the short side’s contribution.

Experimentation with these settings reveals which configuration delivers superior risk-adjusted returns.

Configuration Settings

In the Properties tab, futures contracts require specific settings: set both default order size and quantity to one, and ensure execution occurs on bar close. These settings differ from the spot instrument configuration used earlier for Nifty.

Completing the Analysis

The remaining process mirrors the Nifty workflow exactly. Download the trade logs from the strategy tester, upload them to Claude, and proceed with comprehensive analysis using the same questioning approach demonstrated earlier.

Why Gold Matters

This gold futures example serves a specific purpose: demonstrating the back-adjustment feature available in TradingView for certain futures contracts. For traders working with Indian gold futures, this functionality ensures accurate backtesting that accounts for contract rollovers properly.

Limitations of TradingView Backtests (India Context)



While I have shared how to use TradingView for backtesting, it’s also important to know its limitations:

  • First , in an Indian context, we don’t have historical options data. So that’s out.
  • Second , you cannot do portfolio-level testing at one point. You can test a strategy only on one symbol. Therefore, you cannot run a strategy in parallel on multiple symbols or employ any strategy that requires switching symbols.
  • Third , statistics-wise, if we look at it, there are no features for segregating the data as in-sample and out-of-sample, or even stuff like walk-forward analysis, etc. Though this can be taken care of by selecting different time periods while backtesting and downloading the data separately as two different datasets, and letting Claude do the job.

That said, it’s still a good starting point to do basic backtests and use tools like Claude to do further analysis.

Closing Thoughts: The “Blind Monkey vs. Backtesting Monkey” Analogy

Our base reference here is being a blind monkey throwing darts versus being a monkey that does a backtest and then throws darts. The idea is to be more like the second monkey. But remember, just backtesting by itself does not guarantee success. For all you know, the blind monkey may still win.


I hope this provides a clear understanding of how we conduct backtests for episodes. And I also hope it encourages you to try different backtests.

Do share your questions, thoughts, and feedback in the comments. I’ll do my best to respond. Thank you for watching, and see you in the next one.

3 Likes