The short answer
To backtest a gold strategy in Python:
- Get data you are allowed to use: export it from your own MT5 platform, or use MetaQuotes’ official MetaTrader5 Python package. Be careful with unofficial Yahoo Finance libraries: Yahoo’s terms limit use to personal purposes.
- Write rules a computer can follow, with no judgement calls.
- Decide on one candle, act on the next, so the code never “sees the future”.
- Subtract costs from every trade.
- Test on data you did not use to choose the settings.
Below is a complete, 40-line backtest in plain Python. We ran it on daily gold from 2010 to November 2026: it made only 12 trades, with 4 winners, and one long trade decided almost the whole result. That is the kind of honest first answer a short script gives you.
Step 1: Get gold data (and respect the licence)
| Source | What you get | Licence note |
|---|---|---|
| Your MT5 platform | Your broker’s own XAUUSD bars, any timeframe | Your broker’s prices; for your own use |
| MetaTrader5 Python package (official, by MetaQuotes) | Reads bars directly from a running MT5 terminal | Needs MT5 installed and logged in |
| Unofficial Yahoo Finance libraries | COMEX gold futures (GC=F) daily and hourly | Not affiliated with Yahoo; Yahoo’s terms limit use to personal purposes |
| Exchange or paid vendors | Clean futures or spot data | Paid; licence spells out what you may do |
Two important points:
- Futures are not spot. COMEX gold futures (GC=F) trade at a slightly different price from spot XAUUSD and roll between contract months. For daily trend tests the difference is small; for short-term tests it matters.
- Check the licence before you publish or sell. Using data for your own research is usually fine. Sharing the data, or selling a product built on it, often is not.
Our step-by-step lesson backtesting gold with free data covers cleaning the data (gaps, holidays, bad ticks).
Save your data as a CSV file named gold_daily.csv with these columns, oldest row first:
date,open,high,low,close
2010-01-04,1117.7,1122.3,1097.1,1117.7
Step 2: The complete backtest code
This uses only Python’s built-in csv module, so it runs on any Python 3 install with nothing extra to download.
import csv
# 1) Load the data: one row per day, oldest first
rows = []
with open("gold_daily.csv", newline="") as f:
for r in csv.DictReader(f):
rows.append({"date": r["date"], "open": float(r["open"]), "close": float(r["close"])})
rows = [r for r in rows if r["date"] >= "2010-01-01"]
# 2) Simple moving average of the closes
def sma(values, n):
out = [None] * len(values)
total = 0.0
for i, v in enumerate(values):
total += v
if i >= n:
total -= values[i - n]
if i >= n - 1:
out[i] = total / n
return out
closes = [r["close"] for r in rows]
fast = sma(closes, 50)
slow = sma(closes, 200)
# 3) Rules: be long when the 50 SMA is above the 200 SMA, flat otherwise.
# Decide on today's close, act at TOMORROW's open (no peeking).
COST = 0.50 # dollars per ounce per round trip (spread + slippage guess)
trades = []
entry = None
for i in range(200, len(rows) - 1):
signal = fast[i] > slow[i]
next_open = rows[i + 1]["open"]
if signal and entry is None:
entry = (rows[i + 1]["date"], next_open)
elif not signal and entry is not None:
trades.append((entry[0], rows[i + 1]["date"], next_open - entry[1] - COST))
entry = None
if entry is not None: # close any open trade at the last close
trades.append((entry[0], rows[-1]["date"], rows[-1]["close"] - entry[1] - COST))
# 4) Report
wins = [t for t in trades if t[2] > 0]
equity, peak, max_dd = 0.0, 0.0, 0.0
for t in trades:
equity += t[2]
peak = max(peak, equity)
max_dd = min(max_dd, equity - peak)
print(f"trades: {len(trades)} winners: {len(wins)}")
print(f"total: ${sum(t[2] for t in trades):,.1f} per ounce worst run: ${max_dd:,.1f}")
buy_hold = rows[-1]["close"] - rows[200]["open"]
print(f"buy and hold over the same days: ${buy_hold:,.1f} per ounce")
What each part does, in plain words
- Load: reads every row and keeps the date, open and close as numbers.
- SMA: a running total that adds the newest close and drops the oldest, divided by n. This is the simple moving average.
- Rules: the key line is
next_open = rows[i + 1]["open"]. The decision uses today’s close; the trade happens at tomorrow’s open. If you entered at today’s close using today’s close to decide, you would be cheating without noticing. This mistake is called look-ahead bias, and it makes many online backtests look far better than reality. - Report: counts trades and winners, adds up the result, and tracks the worst run (the biggest drop from a peak in the running total).
Step 3: What it printed on real gold data
We ran the exact code above on COMEX gold futures (GC=F) daily data via Yahoo Finance, from 2010 to 12 November 2026 (the first trade decision is possible on 15 December 2010, once 200 days of data exist; the sample row above is the real first row of 2010 in that data):
trades: 12 winners: 4
total: ... worst run: ...
buy and hold over the same days: ...
Run on 17 November 2026. We leave the dollar lines out on purpose: run the code yourself and read your own numbers. Past results do not predict future results.
How to read it
- Only 12 trades in 16 years. That is far too few to trust. One long trade, from 4 December 2023 to 2 July 2026, carried almost the whole result. When one trade decides everything, you have learned about that trade, not about the rule.
- Always print the buy-and-hold line. It tells you whether the rule added anything beyond simply owning gold. A crossover’s main job is usually sitting out some falls, at the cost of missing parts of rallies.
- 4 winners out of 12. Normal for trend-following: many small losses, a few big wins.
- Read the worst run before the total. The worst run is the drop you would have had to sit through. On 0.01 lot (usually 1 ounce), every $1 per ounce is $1 in your account. Size it to your account before you imagine the money.
Step 4: Costs, done properly
The code subtracts $0.50 per ounce per round trip. On gold, think about:
- Spread: often $0.20–$0.40 per ounce at busy hours, more at rollover and news.
- Commission: on raw-spread accounts, convert per-lot commission to per ounce (÷ 100).
- Slippage: the gap between the price you wanted and the one you got.
- Swap: holding a CFD overnight usually costs money. On a trade held for months, swaps can be much larger than the spread. This simple test does not include swaps, so a real CFD result would be lower.
Rule of thumb: run every test at your normal cost and at double it. If the strategy dies at double cost, it is too fragile to trade.
Step 5: Overfitting, shown with real numbers
It is tempting to try many settings and keep the best. Here is what happens when you do.
We tested 26 pairs of moving averages (fast 10–100, slow 50–250) on gold. We chose the “best” using 2010–2017 only (the in-sample period), then checked how that choice did on 2018–2026 (out-of-sample), with the same $0.50 cost.
| Result | |
|---|---|
| Best pair in 2010–2017 | 30/50 |
| How that pair ranked in 2018–2026 | 15th of 26 |
| The classic 50/200 | middle of the pack in both periods |
Our own sweep, run 17 November 2026, COMEX GC=F daily data.
Two lessons:
- The “best” setting was average on new data. Picking the top performer from the past did not pick the top performer for the future.
- The market mattered more than the settings. Nearly every pair looked weak from 2010 to 2017 (when gold went sideways and down) and nearly every pair looked strong from 2018 to 2026 (when gold rose from about $1,300 to above $5,000 at its peak). A strategy that “works” may simply have been in the right market. Results depend on settings, timeframe and costs, so always test on data you did not use to choose the settings.
How to protect yourself:
- Split your data before you start: build on one part, test once on the other.
- Prefer round, common settings over oddly specific ones (50/200, not 47/193).
- Count your attempts. If you tried 100 versions, expect some to look great by luck.
- Look for at least 100 trades before trusting any result.
Our guide is my trading strategy really working? explains how to judge a result fairly.
Next steps
- Add a short side: sell when the fast average is below the slow one. Gold’s long uptrend makes shorts hard; test it and see.
- Try hourly data: more trades, but costs matter much more.
- Use pandas once you understand the loop: it makes the code shorter.
- Move to MT5: if you want to run the rules live, MQL5 Expert Advisors can be tested in the MT5 Strategy Tester with your broker’s real spreads. Read the gold EA and bot checklist first.
You can also compare with the strategies we have already tested, with costs, on our gold trading strategies tested page.
Common mistakes
- Look-ahead bias: using today’s close to decide and also to enter.
- No costs, or no swaps on long holds.
- Too few trades to mean anything.
- Optimising on all the data and calling it proof.
- Using data you are not allowed to share, then publishing it.
This page is education, not financial advice. Code is provided for learning; check it yourself before relying on it. Trading gold with leverage carries a high risk of loss.
Frequently asked questions
Where can I get free gold price data for Python?
The cleanest source is your own trading platform: MT5 can export price bars, and MetaQuotes publishes an official MetaTrader5 Python package that reads bars from a running terminal. Community libraries that read Yahoo Finance data are popular, but they are unofficial and Yahoo’s terms limit use to personal purposes. Always check the licence before sharing or selling anything built on the data.
What is the simplest gold backtest in Python?
A moving-average crossover on daily data: be long when the 50-day average is above the 200-day average, flat otherwise, deciding on today’s close and acting at tomorrow’s open. The full code on this page is about 40 lines and uses only Python’s built-in csv module.
How do I add trading costs to a Python backtest?
Subtract a fixed cost from every round trip, in the same units as your result. For gold in dollars per ounce, a spread of $0.30 plus slippage might be modelled as $0.50 per round trip. Test a higher cost too; if the strategy only works at the lowest cost, it is fragile.
What is overfitting in backtesting?
Overfitting is tuning a strategy so closely to past data that it fits the noise, not a real pattern. In our sweep of 26 moving-average pairs on gold, the best pair from 2010 to 2017 ranked only 15th of 26 from 2018 to 2026. Always test on data you did not use to choose the settings.
Should I use pandas or backtesting libraries?
Libraries such as pandas make the code shorter and faster once you understand the logic. Start with plain Python so you can see every step, especially the ‘decide today, act tomorrow’ rule that prevents look-ahead bias. Then move to a library if you need speed.
Sources and further reading
- CME Group — Gold futures overview — Contract specifications and trading hours for COMEX gold
- CFTC — Commitments of Traders — Weekly futures positioning, including gold
- Investor.gov — Stop order — How stop orders work, and their limits in fast markets
External sites are independent of XAUUSD Global. Check dates and data yourself.
Comments
No comments yet.
More in Strategies & technical analysis
- Williams %R on Gold: Settings, the Overbought Trap and a Simple XAUUSD Rule
- ICT Unicorn Model on Gold: Breaker Block Plus Fair Value Gap, Explained With XAUUSD Rules
- London Opening Range Breakout on Gold: Rules, Timing and Fakeouts on XAUUSD
- London Close Reversal on Gold: Does XAUUSD Really Turn at 4 pm London? We Tested 601 Days
- Williams Alligator and Fractals on Gold: Rules, Settings and a Tested XAUUSD System
Latest on the blog
- The Philly Fed Survey for Gold Traders: Diffusion Index, Prices Paid and the Thursday Reaction
- NR7 Breakout on Gold: How the Narrowest Day of the Last Seven Behaves
- What Is the Fed Beige Book? A Gold Trader's Guide to District Reports, Price Clues and Market Reaction
- Trading Psychology Quotes That Actually Help: 12 Lines From Famous Traders and What They Mean for Gold