The S&P 500 200-day moving average strategy holds the index while its price is above the average of the last 200 daily closes, and moves to cash when the price falls below it. Tested on SPY from November 1993 to November 2026 with EODHD data, it cut the maximum drawdown from 55.19% to 30.24%, but grew $1 to $12.02 instead of $28.44 for buy and hold. It gave up return in exchange for smaller losses.

This guide shows the backtest step by step in Python, then tests the stricter version from the 2023 edition of this article, which combines weekly, daily and hourly 200-period averages. On HSBC’s S&P 500 ETF from November 2020 to November 2026, those rules won 2 of 7 closed trades and returned 16.9%, against a 107.3% price change for holding the ETF.

Register & Get Data

What the S&P 500 200-day moving average shows

A simple moving average (SMA) is the average closing price over a fixed number of periods. The 200-day SMA covers roughly the last ten months of trading, so it changes slowly and shows the long-term trend. When the S&P 500 trades above its 200-day moving average, the trend is usually described as up. When it trades below, the trend is described as down.

The trading rule built on it is simple:

  • Stay invested while the close is above the 200-day SMA.
  • Move to cash when the close falls below it.
  • Buy again when the close rises back above it.

The idea is to stay in during long rises and step aside during long declines. The cost is that every crossing triggers a trade, including the ones that reverse a few days later.

The test setup

Everything below is reproducible with the code in this guide:

  • Data: daily adjusted closes of SPY (SPY.US) from the EODHD end-of-day API, January 29, 1993 to November 6, 2026. The first 200 days are used to build the first average, so the backtest starts on November 11, 1993.
  • Signal: computed on each day’s close and applied to the next day’s return, so no trade uses a price it couldn’t have known.
  • Costs: 0.1% on every switch in or out of the market. Cash earns nothing, which understates the strategy slightly in years with high interest rates.
  • Comparison: buy and hold of the same SPY series, with dividends reinvested through the adjusted close.

How to get your EODHD API key

1. Use the “demo” API key to test our data from a limited set of tickers without registering:
AAPL.US | TSLA.US | VTI.US | AMZN.US | BTC-USD | EUR-USD
Real-Time Data and all of the APIs (except Bulk) are included without API calls limitations with these tickers and the demo key.
2. Register to get your free API key (limited to 20 API calls per day) with access to:
End-Of-Day Historical Data with only the past year for any ticker, and the List of tickers per Exchange.
3. To unlock your API key, we recommend to choose the subscription plan which covers your needs.

Register & Get Data

SPY isn’t one of the demo tickers, and the backtest uses 33 years of history, so it needs the EOD Historical All-World plan or higher. The hourly test later in the guide uses intraday data, which is part of the EOD + Intraday All-World Extended plan and the All-In-One plan.

Backtesting the S&P 500 200-day moving average in Python

The script downloads the adjusted closes, builds the 200-day SMA, and compares the filter with buy and hold over the whole period, during five major sell-offs and during the 2020 rebound:

import os
import sys

import numpy as np
import pandas as pd
import requests

API_KEY = os.environ.get("EODHD_API_KEY", "demo")
FEE = 0.001 # 0.1% per switch, in or out


def get_eod(ticker, start, end):
url = f"https://eodhd.com/api/eod/{ticker}"
params = {"api_token": API_KEY, "fmt": "json", "from": start, "to": end}
data = requests.get(url, params=params, timeout=60).json()
df = pd.DataFrame(data).set_index("date")
df.index = pd.to_datetime(df.index)
return df["adjusted_close"].astype(float)


def stats(daily_ret, years):
equity = (1 + daily_ret).cumprod()
cagr = equity.iloc[-1] ** (1 / years) - 1
drawdown = (equity / equity.cummax() - 1).min()
vol = daily_ret.std() * np.sqrt(252)
return equity.iloc[-1], cagr, drawdown, vol


ticker, start, end = sys.argv[1:4]
close = get_eod(ticker, start, end)
sma = close.rolling(200).mean()

df = pd.DataFrame({"close": close, "sma200": sma}).dropna()
df["ret"] = df["close"].pct_change().fillna(0)
df["in_market"] = (df["close"] > df["sma200"]).astype(int).shift(1).fillna(0)
switches = df["in_market"].diff().abs().fillna(0)
df["strategy"] = df["in_market"] * df["ret"] - switches * FEE

years = (df.index[-1] - df.index[0]).days / 365.25
print(f"{ticker}: {df.index[0].date()} to {df.index[-1].date()}, {len(df)} days, {years:.1f} years")
print(f"Switches in or out: {int(switches.sum())}, time invested: {df['in_market'].mean():.1%}\n")

rows = []
for name, col in [("Buy and hold", "ret"), ("SMA200 filter", "strategy")]:
final, cagr, dd, vol = stats(df[col], years)
rows.append({"Strategy": name, "Growth of $1": round(final, 2), "CAGR": f"{cagr:.2%}",
"Max drawdown": f"{dd:.2%}", "Volatility": f"{vol:.2%}"})
print(pd.DataFrame(rows).to_string(index=False), "\n")

# The same comparison inside each major sell-off and recovery
periods = {
"2000-2002 dot-com bust": ("2000-03-24", "2002-10-09"),
"2007-2009 financial crisis": ("2007-10-09", "2009-03-09"),
"2020 Covid crash": ("2020-02-19", "2020-03-23"),
"2020 Covid rebound": ("2020-03-23", "2020-08-31"),
"2022 bear market": ("2022-01-03", "2022-10-12"),
"2025 tariff sell-off": ("2025-02-19", "2025-04-08"),
}
rows = []
for name, (a, b) in periods.items():
p = df.loc[a:b]
rows.append({"Period": name,
"Buy and hold": f"{(1 + p['ret'].iloc[1:]).prod() - 1:.1%}",
"SMA200 filter": f"{(1 + p['strategy'].iloc[1:]).prod() - 1:.1%}"})
print(pd.DataFrame(rows).to_string(index=False))

Run with python sma200_filter.py SPY.US 1993-01-29 2026-11-06:

SPY.US: 1993-11-11 to 2026-11-06, 8303 days, 33.0 years
Switches in or out: 213, time invested: 77.4%

Strategy Growth of $1 CAGR Max drawdown Volatility
Buy and hold 28.44 10.68% -55.19% 18.69%
SMA200 filter 12.02 7.83% -30.24% 12.15%

Period Buy and hold SMA200 filter
2000-2002 dot-com bust -47.5% -24.3%
2007-2009 financial crisis -55.2% -15.1%
2020 Covid crash -33.7% -17.8%
2020 Covid rebound 57.4% 17.2%
2022 bear market -24.5% -14.1%
2025 tariff sell-off -18.8% -9.7%

S&P 500 200-day moving average results

Buy and hold200-day SMA filter
Growth of $1, Nov 1993 to Nov 2026$28.44$12.02
Annual return (CAGR)10.68%7.83%
Maximum drawdown-55.19%-30.24%
Annual volatility18.69%12.15%
Time invested100%77.4%
SPY growth of $1 and drawdowns for the S&P 500 200-day moving average filter and buy and hold

The filter did what it was designed to do in long declines. In the 2007-2009 financial crisis it lost 15.1% while the S&P 500 lost 55.2%, and in the 2000-2002 bust it lost 24.3% against 47.5%. Its volatility was about a third lower over the whole period.

It also missed a large part of the rebounds. After the Covid low on March 23, 2020, SPY rose 57.4% by the end of August, while the filter gained 17.2%, because the price had to climb back above its 200-day average before the strategy bought again. Over 33 years, the filter ended with less than half of the buy and hold result. Late re-entries like this one, the switching fees and cash that earned nothing all contributed to the gap.

The 213 switches also matter. Of the 107 periods in the market, 77 lasted 20 trading days or less, and so did 89 of the 106 periods in cash. Those short spells came from the price crossing the average back and forth, and each crossing paid the 0.1% fee.

The weekly, daily and hourly SMA200 rules

The 2023 edition of this article described a stricter set of rules on HSPX.LSE, HSBC’s S&P 500 ETF listed in London:

  • Trade only while the daily SMA200 is above the weekly SMA200.
  • Buy when the hourly SMA200 crosses above the daily SMA200.
  • Sell when the hourly SMA200 crosses below the daily SMA200.

Hourly data from EODHD APIs for HSPX.LSE starts in late 2020, which gives six years to test the rules. The script below uses the last completed daily and weekly averages for each hourly bar, so no hour uses data from later in the same day. All three averages use raw closes, because the hourly data has no adjusted close. The results are therefore price returns, without dividends.

import os
import sys
from datetime import datetime, timezone

import pandas as pd
import requests

API_KEY = os.environ.get("EODHD_API_KEY", "demo")
BASE = "https://eodhd.com/api"


def get(path, **params):
resp = requests.get(f"{BASE}/{path}", params={"api_token": API_KEY, "fmt": "json", **params}, timeout=60)
resp.raise_for_status()
return resp.json()


def eod(ticker, period, start, end):
df = pd.DataFrame(get(f"eod/{ticker}", period=period, **{"from": start, "to": end}))
return df.set_index(pd.to_datetime(df["date"]))["close"].astype(float)


def hourly(ticker, start, end):
# Intraday timestamps are in UTC
ts = lambda d: int(datetime.fromisoformat(d).replace(tzinfo=timezone.utc).timestamp())
df = pd.DataFrame(get(f"intraday/{ticker}", interval="1h", **{"from": ts(start), "to": ts(end)}))
df = df[df["close"] > 0]
return df.set_index(pd.to_datetime(df["datetime"]))["close"].astype(float)


ticker, start, end = sys.argv[1:4]
weekly_sma = eod(ticker, "w", "2010-01-01", end).rolling(200).mean()
daily_sma = eod(ticker, "d", "2019-01-01", end).rolling(200).mean()
h = hourly(ticker, start, end)

df = pd.DataFrame({"close": h, "hourly_sma": h.rolling(200).mean()})
day = df.index.normalize()
# Last completed day and week before each hourly bar
df["daily_sma"] = daily_sma.shift(1).reindex(day, method="ffill").values
df["weekly_sma"] = weekly_sma.shift(1).reindex(day, method="ffill").values
df = df.dropna()

regime = df["daily_sma"] > df["weekly_sma"]
above = df["hourly_sma"] > df["daily_sma"]
cross_up = above & ~above.shift(1, fill_value=True)
cross_down = ~above & above.shift(1, fill_value=False)

trades, entry = [], None
for t, row in df.iterrows():
if entry is None and cross_up[t] and regime[t]:
entry = (t, row["close"])
elif entry is not None and cross_down[t]:
trades.append({"entry": entry[0], "exit": t, "entry_price": entry[1], "exit_price": row["close"]})
entry = None
if entry is not None:
last = df.index[-1]
trades.append({"entry": entry[0], "exit": last, "entry_price": entry[1],
"exit_price": df["close"].iloc[-1], "open": True})

tr = pd.DataFrame(trades)
tr["return"] = tr["exit_price"] / tr["entry_price"] - 1
tr["days"] = (tr["exit"] - tr["entry"]).dt.days
closed = tr[tr.get("open", pd.Series(False, index=tr.index)).fillna(False) == False]

print(f"{ticker} hourly bars: {df.index[0]} to {df.index[-1]}, {len(df)} bars")
print(f"Hours with daily SMA200 above weekly SMA200: {regime.mean():.1%}")
print(f"Trades: {len(tr)} ({len(closed)} closed)")
print(f"Winning closed trades: {(closed['return'] > 0).sum()} of {len(closed)} ({(closed['return'] > 0).mean():.0%})")
print(f"Average closed trade: {closed['return'].mean():.2%}, median holding: {closed['days'].median():.0f} days")
print(f"Strategy, compounded: {(1 + tr['return']).prod() - 1:.1%}")
print(f"Buy and hold, same hours: {df['close'].iloc[-1] / df['close'].iloc[0] - 1:.1%}\n")
print(tr[["entry", "exit", "entry_price", "exit_price", "return", "days"]].to_string(index=False,
formatters={"return": "{:.2%}".format, "entry_price": "{:.2f}".format, "exit_price": "{:.2f}".format}))

Run with python three_timeframe.py HSPX.LSE 2020-06-01 2026-11-07:

HSPX.LSE hourly bars: 2020-11-11 08:00:00 to 2026-11-06 16:30:00, 13887 bars
Hours with daily SMA200 above weekly SMA200: 100.0%
Trades: 8 (7 closed)
Winning closed trades: 2 of 7 (29%)
Average closed trade: 1.91%, median holding: 49 days
Strategy, compounded: 16.9%
Buy and hold, same hours: 107.3%

entry exit entry_price exit_price return days
2022-03-01 14:00:00 2022-03-02 08:00:00 3279.13 3257.50 -0.66% 0
2022-03-29 10:00:00 2022-05-18 07:00:00 3533.80 3309.93 -6.34% 49
2022-08-15 11:00:00 2022-10-18 12:00:00 3544.20 3346.20 -5.59% 64
2022-11-14 14:00:00 2022-12-13 16:00:00 3421.40 3299.80 -3.55% 29
2023-02-13 11:00:00 2023-03-21 08:00:00 3418.60 3259.62 -4.65% 35
2023-05-30 15:00:00 2025-03-21 14:00:00 3429.00 4388.83 27.99% 660
2025-07-15 13:00:00 2026-04-07 09:00:00 4746.20 5038.21 6.15% 265
2026-04-17 11:00:00 2026-11-06 16:30:00 5274.40 5619.20 6.54% 203
HSPX.LSE hourly close with the hourly, daily and weekly SMA200 and the periods in a trade

The results show three things:

  • The weekly filter never applied. The daily SMA200 stayed above the weekly SMA200 in every hour of the test, so the first rule didn’t change a single trade.
  • The rules missed the 2021 rise. The hourly average was already above the daily average when the test started, and the strategy waits for a crossing before buying, so the first trade came in March 2022.
  • 2022 and early 2023 produced five losing trades in a row, as the hourly average crossed the daily average back and forth. One long trade from May 2023 to March 2025, with a 27.99% gain, made up for them.

The 2023 article described these rules as tested over many years, with a 99% success rate in one trader’s last 100 trades. Over this six-year window, with EODHD data and the rules as written, 2 of 7 closed trades were profitable, and the ETF’s price change over the same hours was more than six times as large.

Getting the data with the eodhd Python library

The scripts above call the API with requests. The official eodhd library (version 1.0.32 at the time of writing) also returns daily, weekly and hourly bars, through the interval argument:

import os

from eodhd import APIClient

api = APIClient(os.environ["EODHD_API_KEY"])
df_daily = api.get_historical_data(symbol="HSPX.LSE", interval="d",
iso8601_start="2019-01-01", iso8601_end="2026-11-06")
df_weekly = api.get_historical_data(symbol="HSPX.LSE", interval="w",
iso8601_start="2010-01-01", iso8601_end="2026-11-06")
df_hourly = api.get_historical_data(symbol="HSPX.LSE", interval="1h",
iso8601_start="2021-01-01", iso8601_end="2026-11-06")

The price columns come back with the object data type, so convert them with astype(float) before calculating averages.

Where the S&P 500 200-day moving average strategy breaks

The results above depend on several choices. Check each one before using any version of the strategy:

  • Rebounds after crashes. The filter re-enters only after the price is back above a slow average, so it buys late after V-shaped recoveries. From March to August 2020, SPY rose 57.4% and the filter 17.2%.
  • Sideways markets. When the price stays close to the average, every small move triggers a trade. That happened in 2022 and early 2023 for the hourly rules, and 77 of the daily filter’s 107 periods in the market lasted 20 trading days or less.
  • Cash return. This test assumes cash earns nothing. A money market fund or Treasury bills would have added return during the 22.6% of the time the filter was out of the market.
  • Costs and taxes. The test charges 0.1% per switch. In a taxable account, selling 100 times or more in 33 years also realizes gains that buy and hold would have deferred.
  • One market and one period. The S&P 500 rose strongly over most of this sample. A market or period with longer, deeper declines could give a different result, so test the filter on the indices you actually hold.

Conclusion

The S&P 500 200-day moving average works as a risk filter, not as a way to beat the index. Over 33 years of SPY data, it reduced the maximum drawdown from 55.19% to 30.24% and the volatility by about a third, at the cost of roughly three percentage points of annual return. The stricter weekly, daily and hourly rules from the 2023 edition returned 16.9% over six years against a 107.3% price change for holding the ETF.

Whether the trade-off is worth it depends on how much a deep drawdown matters to you. The scripts in this guide let you test it on any ticker, period and fee level with EODHD data.

For the endpoints used here, see the End-of-Day Historical Data API documentation and the Intraday Historical Data API documentation.

This article is for educational purposes and is not financial advice.

Register & Get Data

FAQs

Q: What is the 200-day moving average of the S&P 500?

It is the average of the S&P 500’s last 200 daily closing prices, about ten months of trading. Investors use it as a long-term trend line: the trend is usually described as up while the index trades above it and down while it trades below.

Q: Does the 200-day moving average strategy beat buy and hold?

Not in this test. From November 1993 to November 2026, the filter on SPY returned 7.83% a year against 10.68% for buy and hold. It did reduce the maximum drawdown from 55.19% to 30.24%.

Q: What happens when the S&P 500 crosses below its 200-day moving average?

The filter sells and moves to cash. In this test, that protected the strategy during long declines such as 2008, but many crossings reversed within weeks: 77 of the 107 periods in the market lasted 20 trading days or less, and each switch paid the 0.1% fee.

Q: How many trades does a 200-day moving average strategy make?

On SPY from 1993 to 2026, the filter switched in or out of the market 213 times, and was invested 77.4% of the time.

Q: Can I use the 200-day moving average on hourly data?

Yes, the average can be calculated on any interval. The hourly version from the 2023 edition of this article, tested from November 2020 to November 2026, won 2 of 7 closed trades and returned 16.9%, against a 107.3% price change for holding the ETF.

Do you enjoy our articles?

We can send new ones right to your email box