β ≈ GLD / SLV
Blog / Math 2026.02.20 ← All entries
MATH

Gold, Silver & a Kalman Filter

How a pairs-trading experiment turned into a gold–silver rotation strategy, and what a 20-year backtest really says about it.

Feb 20, 2026 · 15 min read

GLD (gold) and SLV (silver) since April 2006, both rebased to 1 on a log scale
TABLE OF CONTENTS

    Info. The code for this article is on GitHub. Every chart below re-runs the backtest live in your browser on 20 years of daily GLD and SLV prices, so you can change the settings and watch the results move.

    A Little Bit of Context

    Put ₹10,000 into this strategy on 28 April 2006, leave it alone, and by 12 February 2026 it had grown to ₹111,594. That's a 1015.94% return in just under 20 years, against 593.49% for simply holding gold and 390.44% for holding silver.

    Period
    19.8 yrs
    28 Apr 2006 – 12 Feb 2026
    Our strategy
    +1015.94%
    ₹10,000 → ₹111,594
    Hold gold
    +593.49%
    Buy & hold GLD
    Hold silver
    +390.44%
    Buy & hold SLV

    So how does one rule beat both of the metals it chooses between? It started as a pairs trade. Gold and silver are two metals that usually move together, and the classic idea is to bet on the gap between two such assets snapping back when it stretches too far[3]. To do that you need a hedge ratio, the number \(\beta\) that says how many units of silver behave like one unit of gold. That ratio isn't constant, so I estimated it with a Kalman filter, which updates its guess for \(\beta\) every day as new prices arrive.

    While plotting that daily \(\beta\), I noticed something more useful than the spread. The direction of \(\beta\) told me which metal was leading. So I stopped hedging and started rotating: hold gold when \(\beta\) trends up, hold silver when it trends down. Over the backtest this beat buying and holding either metal, and that's the strategy this post is about.

    I'll walk through the whole thing: the data, the filter, the signal and the backtest. Then I'll stress-test my own results, because the most useful part of this project turned out to be finding out where the impressive number comes from and how fragile it is.

    Not financial advice. This is a research write-up of a historical backtest. Past performance doesn't predict future returns, and the costs of real trading are discussed in §7.

    Gold, Silver and Their Ratio

    The two assets are exchange-traded funds that hold physical metal. GLD holds gold, and one share is backed by roughly a tenth of an ounce. SLV holds silver, roughly one ounce per share. SLV only started trading in April 2006, so although my code asks for data from 2005, the backtest effectively begins on 28 April 2006.

    Silver behaves like gold with the volume turned up. It is a precious metal but also an industrial one (solar panels, electronics), so it reacts more violently in both directions. Over these 20 years silver's worst peak-to-trough fall was −76%, against −46% for gold. The relationship between them is usually summarised by the gold/silver ratio: how many ounces of silver buy one ounce of gold. For the ETFs it is simply \(\text{GLD}/\text{SLV}\), which is about a tenth of the metal ratio because of the share sizes.

    Figure 1 The GLD/SLV price ratio. When it rises, gold is outperforming silver, and when it falls, silver is winning. The dashed line is the 20-year median.

    The ratio wanders a long way. Silver's boom pushed it to its low of 3.2 in April 2011, and the COVID crash pushed it to its high of 12.6 in March 2020, a fourfold range. A fixed hedge ratio would be badly wrong most of the time, which is why I reached for a filter that tracks it.

    The Original Plan: Pairs Trading

    A pairs trade models one price as a multiple of the other:

    $$y_t = \beta_t\, x_t + \varepsilon_t, \qquad y = \text{GLD},\ x = \text{SLV}.$$

    If you are long one share of gold and short \(\beta\) shares of silver, your position is worth the spread \(s_t = y_t - \beta_t x_t\). When the spread is unusually wide you bet on it narrowing, and vice versa. The whole strategy rests on two things, a good estimate of \(\beta_t\) and a spread that actually mean-reverts.

    The simplest way to estimate \(\beta\) is an ordinary least-squares regression over a rolling window, say the last 60 days. That works, but it forces a trade-off. A long window is stable but slow to notice change, and a short window reacts quickly but is noisy. The Kalman filter makes that trade-off explicit, with one knob for how fast \(\beta\) is allowed to drift and another for how noisy each observation is.

    The Kalman Filter

    The State-Space Model

    The filter treats \(\beta\) as a hidden state that changes slowly and that we only see through noisy prices[1]:

    $$\underbrace{\beta_t = \beta_{t-1} + w_t}_{\text{state: a random walk}}, \quad w_t \sim \mathcal{N}(0, \delta) \qquad\qquad \underbrace{y_t = \beta_t x_t + v_t}_{\text{observation}}, \quad v_t \sim \mathcal{N}(0, R).$$

    Here \(\delta\) is the process noise, how much \(\beta\) can wander from one day to the next, and \(R\) is the measurement noise, how much a single day's prices can be off the true relationship. Each day the filter runs two steps. It predicts, growing its uncertainty \(P\) because \(\beta\) may have drifted. Then it updates, nudging \(\beta\) towards today's evidence by an amount set by the Kalman gain \(K\):

    $$P \leftarrow P + \delta, \qquad K = \frac{P\,x_t}{x_t^2 P + R}, \qquad \hat\beta \leftarrow \hat\beta + K\,(y_t - \hat\beta x_t), \qquad P \leftarrow (1 - K x_t)\,P.$$

    The term \(y_t - \hat\beta x_t\) is the forecast error. If the filter is very unsure (large \(P\)) or the data is very clean (small \(R\)), \(K\) is large and \(\beta\) jumps towards the new evidence. If the filter is confident or the data is noisy, it barely moves. This is my implementation, a direct transcription of those four lines:

    class KalmanHedge:
        def __init__(self, delta=1e-4, R=1e-3):
            self.delta = delta  # process noise: how fast beta may drift
            self.R = R          # measurement noise: how noisy each day is
    
        def update(self, y, x):
            n_obs = len(y)
            betas = np.zeros(n_obs)
            P = 1.0             # initial uncertainty
            beta_hat = 0.0      # initial guess
            for t in range(n_obs):
                P = P + self.delta                      # predict
                y_pred = beta_hat * x[t]
                error = y[t] - y_pred                   # forecast error
                K = P * x[t] / (x[t]**2 * P + self.R)   # Kalman gain
                beta_hat = beta_hat + K * error         # update
                P = (1 - K * x[t]) * P
                betas[t] = beta_hat
            return betas

    What β Actually Tracks

    When I came back to this project to write it up, I found something I hadn't noticed at the time. With my settings, \(\delta = 10^{-4}\) and \(R = 10^{-3}\), the filtered \(\beta\) is almost exactly the price ratio \(y_t / x_t\). Across 5,139 trading days the two differ by 0.025% on average.

    The update equation explains why. The fraction of today's error that the filter accepts is

    $$K x_t = \frac{x_t^2 P}{x_t^2 P + R} = \frac{1}{1 + R / (x_t^2 P)}.$$

    SLV has traded between about $9 and $106, so \(x_t^2\) ranges from about 80 to over 10,000. Even a tiny \(P\) makes \(x_t^2 P\) much bigger than \(R = 0.001\), so \(K x_t \approx 1\). Then the update becomes \(\hat\beta \leftarrow \hat\beta + (y_t - \hat\beta x_t)/x_t = y_t/x_t\). The filter throws away almost all of its memory and resets \(\beta\) to today's ratio every day. My Kalman filter had quietly rediscovered the gold/silver ratio.

    That isn't a bug, but it reframes the project. The real engine of the strategy is a moving-average signal on the gold/silver ratio, and the filter is a very elaborate way of computing a division. Try making \(R\) larger below. The filter starts to smooth, \(\beta\) lags behind the ratio, and the strategy's results change.

    Figure 2 The Kalman filter's β (red) against the plain GLD/SLV ratio (black). At my original settings (δ = 10⁻⁴, R = 10⁻³) the red line hides the black one completely. The readout re-runs the full strategy with these filter settings.

    From Hedge to Rotation

    The Signal

    The rotation rule compares a fast and a slow moving average of \(\beta\), a crossover like the ones trend followers have used for decades[5]:

    $$\bar\beta^{\,\text{fast}}_t = \text{SMA}_6(\beta)_t, \qquad \bar\beta^{\,\text{slow}}_t = \text{SMA}_{21}\!\big(\bar\beta^{\,\text{fast}}\big)_t,$$ $$\text{hold} = \begin{cases} \text{GLD} & \text{if } \bar\beta^{\,\text{fast}}_t > \bar\beta^{\,\text{slow}}_t \quad (\text{ratio rising: gold leading}), \\ \text{SLV} & \text{if } \bar\beta^{\,\text{fast}}_t < \bar\beta^{\,\text{slow}}_t \quad (\text{ratio falling: silver leading}). \end{cases}$$

    Six trading days is about a week and a bit, and 21 is about a month. Because the slow average is taken of the fast one, the trend line is smoothed twice. A rising ratio means gold is beating silver, so the rule holds gold. In plain words, it holds whichever metal has been winning lately.

    strat['beta_smooth'] = strat['beta'].rolling(window=6).mean()          # fast
    strat['beta_trend']  = strat['beta_smooth'].rolling(window=21).mean()  # slow
    
    strat['signal'] = 0
    strat.loc[strat['beta_smooth'] > strat['beta_trend'], 'signal'] = 1   # GLD
    strat.loc[strat['beta_smooth'] < strat['beta_trend'], 'signal'] = 2   # SLV
    
    # trade tomorrow on today's signal: no look-ahead
    strat['position'] = strat['signal'].shift(1).fillna(0)
    ■ holding GLD   ■ holding SLV
    Figure 3 Fast average of β (black) against the slow trend (red, dashed). The background shows which metal the strategy holds on each day, one day after the crossing that triggered it.

    Avoiding Look-Ahead Bias

    The line that matters most in the code is shift(1). The signal for day \(t\) uses the closing prices of day \(t\), so you can only act on it from the next day. Without the shift, the backtest would trade today using today's close, which is information it couldn't have had, and the results would look far better than anything achievable. With the shift, the return on day \(t+1\) always comes from a decision made at the close of day \(t\).

    The Backtest

    The backtest starts with ₹10,000, puts all of it in whichever ETF the signal picks, and compounds daily returns. For the first 25 days, before the moving averages exist, it sits in cash. In the baseline there are no trading costs.

    Figure 4 Growth of ₹10,000 in the switcher strategy (green) against buying and holding GLD (gold, dashed) and SLV (silver, dotted). Drag the sliders to change the moving averages or add a trading cost per switch. 1 bps = 0.01%.

    Results

    My original run ended on 12 February 2026, which produced the chart in the project's README. Re-running the same code on a second data source gives nearly identical numbers. The small differences come from the two providers' closing prices.

    Total returnMy run (Stooq)Replication (Yahoo)To 1 Oct 2026
    Switcher strategy1015.9%1008.1%693.9%
    Buy & hold GLD593.5%593.5%488.1%
    Buy & hold SLV390.4%390.4%298.0%

    Over 20.4 years the strategy compounds at about 10.7% a year, against 9.1% for gold and 7.0% for silver. It switches 275 times, so it holds each position for roughly 19 trading days. It spends a little more time in gold (54%) than in silver (46%).

    The two end dates differ so much because of one day. On 30 January 2026 silver fell 28.5% in a single session, and the strategy was holding silver. The tall spike at the end of my original chart is silver's run-up into that day, and the cliff is the crash. A strategy that holds one asset at a time takes its full hit.

    Stress-Testing the Stress Test

    A backtest is only a first draft. Before believing "1016%", it's worth asking what has to go right for that number to hold up. I ran three checks: costs, risk, and sensitivity to the settings.

    Trading Costs

    Every switch means selling one ETF and buying the other, which costs brokerage, the bid-ask spread and slippage. With 275 switches, small costs compound into big ones. Set the cost slider in Figure 4 and watch:

    Cost per switchStrategy total returnvs GLD (488%)
    0 bps (baseline)693.9%ahead
    5 bps (0.05%)591.8%ahead
    10 bps (0.10%)502.9%roughly level
    20 bps (0.20%)357.8%behind

    The whole edge over gold disappears at about 10 basis points per switch. For a large investor trading these very liquid ETFs in the US, that's achievable. For a retail investor in India buying them through an overseas account, with currency conversion and higher brokerage, it probably isn't.

    Risk-Adjusted Returns

    Higher returns don't mean much if they came from taking more risk. The Sharpe ratio measures return per unit of volatility, annualised from daily returns. Higher is better. The stats table under Figure 4 shows it live:

    • Switcher: Sharpe 0.52, worst drawdown −51.5%.
    • Buy & hold GLD: Sharpe 0.56, worst drawdown −45.6%.
    • Buy & hold SLV: Sharpe 0.37, worst drawdown −76.3%.

    The strategy earned more than gold by spending almost half its time in silver, which is more volatile, so per unit of risk it did slightly worse than simply holding gold. That doesn't make the strategy useless. Higher absolute growth is a valid goal. But it means the headline number is partly a reward for risk rather than a free lunch.

    Is 6 / 21 Special?

    I picked 6 and 21 days by looking at results, and choosing settings by looking at results is how backtests get overfitted[6]. A real effect shouldn't depend on a lucky combination, so the grid below re-runs the full 20-year backtest for 160 different pairs of windows:

    cost / switch
    ■ beats GLD   ■ trails GLD
    Figure 5 Total return (%) to 1 Oct 2026 for each combination of fast window (rows) and slow window (columns). The boxed cell is my 6 / 21. Hover over a cell, or tap it, to see its exact numbers.

    This is the result that humbled me most. Without costs, 62 of the 160 combinations beat buy-and-hold gold, which means most of them don't. The winners form two clusters. One is the top-left corner, where both windows are short and the strategy reacts within days to the ratio turning. The other is the bottom-right, where both are long and it follows slower trends. In between, most settings trail gold, and across the grid the results swing between 240% and 970%. My 6 / 21 (694%) sits on a good patch, but its neighbour 6 / 30 earns only 435%.

    Switch the grid to 10 bps and only 15 of 160 still beat gold. Taken together, the honest summary is that the gold/silver ratio has shown some momentum, but the size of the edge depends heavily on the settings, and most of it lies within a trading cost or two of zero.

    Extra Notes

    • The currency label. GLD and SLV trade in US dollars, so the backtest's numbers are in dollars. My code prints "$10,000" at the start but labels the chart "₹". The percentage returns are the same either way, but an Indian investor's rupee returns would also include the dollar's rise against the rupee over the period.
    • The model has no intercept. \(y = \beta x\) forces the fitted line through zero, which is a big part of why \(\beta\) collapses to the ratio. Adding an intercept, \(y = \alpha + \beta x\), makes the filter track a genuine regression and would be the natural next experiment.
    • Tuning δ and R. If the goal is a smoother β, the clean way is to estimate \(\delta\) and \(R\) from the data by maximum likelihood, rather than choosing them by hand. Figure 2 shows how much they matter.
    • Out-of-sample testing. A stronger test would pick the windows using only, say, 2006–2015, then run them untouched on 2016–2026 (a walk-forward test).
    • Data source. The original code reads from Stooq through pandas-datareader. The figures on this page use a snapshot of Yahoo Finance closing prices taken on 2 October 2026. As shown in §6, the two give almost identical results.
    • Further reading: Ernie Chan's Algorithmic Trading[2] has a chapter on exactly this use of the Kalman filter for pairs, and Welch & Bishop's tutorial[4] is the friendliest introduction to the filter itself.

    References

    1. R. E. Kalman, "A New Approach to Linear Filtering and Prediction Problems", J. Basic Engineering 82(1) (1960) 35–45.
    2. E. P. Chan, Algorithmic Trading: Winning Strategies and Their Rationale, Wiley, 2013.
    3. E. Gatev, W. N. Goetzmann & K. G. Rouwenhorst, "Pairs Trading: Performance of a Relative-Value Arbitrage Rule", Review of Financial Studies 19(3) (2006) 797–827.
    4. G. Welch & G. Bishop, "An Introduction to the Kalman Filter", Technical Report TR 95-041, University of North Carolina at Chapel Hill.
    5. T. J. Moskowitz, Y. H. Ooi & L. H. Pedersen, "Time Series Momentum", Journal of Financial Economics 104(2) (2012) 228–250.
    6. D. H. Bailey & M. López de Prado, "The Deflated Sharpe Ratio", Journal of Portfolio Management 40(5) (2014) 94–107.
    TAGS: #MATH#KALMAN FILTER#BACKTESTING#GOLD#SILVER