Chapter 9
Introduction to Backtesting

"No amount of experimentation can ever prove me right; a single experiment can prove me wrong."
— Albert Einstein

Imagine standing at the edge of a vast forest, deciding which path to take. Some trails look well-trodden; others are faint and overgrown. Without a map, every choice feels like a gamble. Now imagine having a detailed guide — one that shows where each path led past travelers: which trails ended at a cliff, and which ones opened into wide fields of gold. Wouldn’t you want that knowledge before taking your first step?

That’s what backtesting offers traders: a map of history.

In financial markets, intuition is not enough. Many strategies sound convincing when explained — buy low, sell high — but few survive the harsh realities of real data. Backtesting forces ideas to confront history. It separates what merely sounds good from what actually works.

In the following sections, we’ll see how backtesting can transform trading from an emotional guessing game into a disciplined, evidence-based craft. Before we design new strategies, we must first learn how to properly test them — and why the process matters so much.

9.1 What is Backtesting?

At its core, backtesting is simple: it means testing a trading strategy against historical market data to see how it would have performed.

Think of it like this: If you had followed a particular set of trading rules over the past 10, 20, or even 30 years — what would have happened? Would you have grown your wealth steadily? Or would you have faced devastating losses? Backtesting lets you find out before you risk real money.

Importantly, backtesting is not about guessing the future. It’s about measuring how specific actions would have played out in the real world, based on real past events. Instead of relying on opinions or hunches, you let history itself answer your questions.

In practice, backtesting follows a simple process:

  • Define your trading rules clearly — for example, "Buy when the price moves above the 50-day moving average. Sell when it moves below."
  • Gather historical data — daily prices, volumes, dividends, and so on.
  • Apply your trading rules to this historical data, step by step, as if you were trading in real time.
  • Record each trade — when you would have bought, when you would have sold, and what your gains or losses would have been.

The result is a realistic simulation of how your strategy would have behaved under real market conditions. It shows not just total profit or loss, but also how volatile the journey would have been — including the inevitable periods of drawdowns, stagnation, and risk.

In short: Backtesting is your first real test of any trading idea. Without it, you are not investing — you are guessing.

9.2 A First Example: Testing a SMA Strategy

Before diving deeper into backtesting techniques, let’s start with a concrete, intuitive example.

Suppose someone suggests a simple trading idea: "Buy SPY when the price crosses above its 200-day simple moving average (SMA), and sell when it crosses below."

At first glance, this sounds reasonable. The 200-day moving average is widely followed by traders and institutions. It’s often seen as a rough dividing line between bullish and bearish trends. If the price is above the 200-day line, the market is likely strong. If the price is below, weakness could persist. By trading based on this signal, you hope to stay in the market during major uptrends and sidestep serious downtrends — avoiding the worst bear markets.

It makes sense — at least in theory.

Step-by-Step: How We Would Test It

To see whether this idea actually works, we can set up a backtest. Here’s the process we would follow:

  1. Gather Historical Data: Obtain daily SPY data: dates, closing prices, and any necessary adjustments for dividends and splits.
  2. Calculate the 200-Day SMA: For each day, compute the average closing price of the past 200 trading days.
  3. Define Trading Rules:

    • Buy Signal: If today’s closing price crosses above the 200-day SMA, buy SPY.
    • Sell Signal: If today’s closing price crosses below the 200-day SMA, sell SPY (and move to cash).
  4. Simulate Trades: Go through the historical data day by day. Apply the buy and sell rules exactly as written, as if you were trading in real time.
  5. Track Performance: Record each trade: entry date, exit date, profit or loss, and other key metrics like maximum drawdown and total return.

Notice that at every step, we act as if we are living in the past, with no knowledge of future events. We only use information that would have been available at the time — ensuring realism and avoiding hindsight bias.

Why This Strategy Seems Sensible (Before Testing)

There are a few reasons why this strategy might intuitively appeal to traders:

  • Trend Following: Instead of trying to predict tops and bottoms, you ride major trends while avoiding prolonged downturns.
  • Simple, Visible Signal: The 200-day SMA is a widely recognized technical indicator. Many large funds and institutions watch it, so it can influence real market behavior.
  • Emotion Control: Having a clear rule to follow removes guesswork and panic decisions during market turbulence.
  • Avoiding the Big Crashes: Historically, major bear markets like 2000-2002 and 2008-2009 have seen prices fall below the 200-day SMA early in the downturn, potentially giving an early exit signal.

In theory, this strategy seems like it could work — at least better than simply holding blindly through every market environment.

What Comes Next: The Real Test

Of course, a strategy sounding good is very different from a strategy actually working.

In the next section, we will use real SPY historical data to backtest this idea step-by-step. We’ll see:

  • How many trades it would have generated
  • What the total return and annual return would have been
  • How deep the worst drawdowns were
  • Whether it truly outperformed simply buying and holding SPY

Only after seeing the data will we know whether this idea holds up — or whether it’s just another nice-sounding story.

Previewing the Results — Without Going Too Deep (Yet)

When we run this simple 200-day SMA strategy on real SPY data going back to 1993, the results are mixed but insightful.

The annualized return comes out to around 8.7% — noticeably lower than a pure buy-and-hold approach. However, the strategy shines in one critical area: risk control. Its maximum drawdown was just 23.54%, far smaller than the major crashes experienced by passive investors during bear markets.

In other words, the strategy offers a smoother ride — giving up some return in exchange for better downside protection. This tradeoff is something we’ll explore in much more detail later. And it naturally raises a question:

If the strategy is safer, could we apply some leverage to boost returns — without taking on excessive risk?

That’s exactly the kind of idea we’ll investigate in future chapters.

But before we get there, we’ll lay the groundwork. The next chapters will guide you through working with SPY market data, building a realistic backtesting framework, and writing the basic code needed to simulate strategies. From there, we’ll explore a range of approaches — including buy and hold, dollar cost averaging, and various crossover strategies — all leading toward more advanced topics like using leverage with call options.

9.3 A Philosophy of Realism
and Conservative Assumptions

Throughout this part of the book, we will embrace a philosophy of realism. We want to simulate not just what could have happened, but what a trader could have realistically done. We will include slippage, transaction costs, dividend yields, and cash interest. For example:

  • Cash earns 4% annual interest (as offered by platforms like Robinhood).
  • SPY pays quarterly dividends if we hold stocks — we’ll include that in our returns.
  • Options do not earn dividends, and they decay over time — we’ll simulate that too.
  • When estimating costs like slippage, we will be pessimistic. If we think slippage could range from 0.1% to 0.5%, we’ll assume 0.5%.

These conservative assumptions may reduce our paper profits, but they increase our confidence that the results are real.

9.4 Roadmap for This Part

In the chapters ahead, we’ll take a hands-on approach to building and testing trading strategies using historical SPY data. We’ll begin by acquiring and preparing real-world market data — understand the difference between close and adjusted close prices, and ensure the dataset is clean and properly aligned for analysis.

Next, we’ll construct a realistic backtesting framework. This includes programming the essential components: tracking positions, simulating trades, and calculating performance metrics like returns and drawdowns. Every tool we build will be grounded in practical use, forming a foundation you can extend later.

With the framework in place, we’ll start testing strategies — beginning with Buy and Hold as a baseline, followed by Dollar Cost Averaging. From there, we’ll explore a range of crossover-based strategies, including price crossing above or below a moving average, the classic golden cross and death cross, and how parameter tuning can significantly impact results.

Finally, we’ll introduce leverage through long-dated call options. You’ll learn how adding leverage changes the return profile — amplifying gains, but also potentially increasing drawdowns — and how to apply it thoughtfully within a data-driven framework.

This part of the book isn’t just about discovering which strategies perform well. It’s about building the skills to test ideas rigorously, avoid common pitfalls, and approach the market with clarity and confidence.

Let’s dive in.