Dual Momentum ETF Rotation in RealTest (Validated Monthly Rebalance Code)
To build a Dual Momentum ETF rotation in RealTest without lookahead bias or unnecessary turnover, isolate your risk ETFs with IF(isRisk, momBlend, NaN) before #Rank, compare each ETF's return against Extern($SHY, momBlend) for absolute momentum, count qualifying slots with #Sum, and use DynamicSizing True returning NaN between month turns so existing holdings stay untouched until Month <> Month[1].
- Dual Momentum combines relative momentum (#Rank across risk ETFs) with an absolute momentum hurdle (beating Extern($SHY, momBlend)) so capital shifts automatically into short-term Treasuries during broad equity and bond drawdowns.
- Wrapping the ranking formula in IF(isRisk, momBlend, NaN) prevents SHY and any unrelated ETFs inside the .rtd data file from occupying top-N relative momentum ranks.
- Using #Sum qualRisk counts how many risk ETFs pass both relative and absolute hurdles on each month turn, letting DynamicSizing route the exact leftover allocation ((topN - qualCount) * 50 percent) into SHY automatically.
- Returning NaN inside DynamicSizing True on non-rebalance days eliminates daily resize churn, keeping average exposure near 99.85 percent while trimming appreciated winners like GLD back to target weight once per month.
- Adding a Benchmark section for SPY compares strategy equity and drawdown side by side in RealTest's Daily Stats Graph without polluting Combined portfolio statistics.
- Validated in RealTest 2.0 from 2010 through 2024 on multi-asset ETFs, this unoptimized Dual Momentum template completed 349 trades (67.62 percent win rate, 2.28 profit factor, 7.34 percent annualized return) and cut max drawdown to -23.03 percent versus -30.25 percent for buy-and-hold SPY.
Monthly ETF rotation is one of the highest-demand strategies traders try to code in RealTest. The concept looks simple on paper. Rank a basket of diversified asset-class ETFs once a month, hold the top two leaders with positive absolute momentum, and park unused slots in short-term Treasury bills (SHY) whenever risk assets turn negative.
In practice, first drafts in RealTest break in three specific ways. Putting #Rank directly on momBlend lets SHY compete inside the risk rankings. Using a standard strategy with ExitRule: newMonth sells and rebuys unchanged winners every single month, burning unnecessary slippage and triggering avoidable short-term capital gains. Writing DynamicSizing: True without a NaN hold rule resizes positions every single trading day. Every directive below follows the official RealTest Benchmark and DynamicSizing documentation and was parsed and executed in RealTest 2.0 across 15 years of multi-asset ETF data.
Relative Momentum vs Absolute Momentum Architecture in RealTest
Classic Dual Momentum requires two separate gates evaluated cleanly at the turn of each month without peeking into future calendar dates.
| Dual Momentum Component | RealTest Implementation | Why This Exact Pattern Matters |
|---|---|---|
| Relative Momentum |
eligMom: IF(isRisk, momBlend, NaN) followed by momRank: #Rank eligMom
|
NaN excludes SHY and unused tickers from the #Rank pool completely |
| Absolute Momentum Gate |
shyMom: Extern($SHY, momBlend) then momBlend > shyMom
|
Requires each top-ranked risk ETF to outperform T-bills over the same lookback |
| Dynamic Safe-Haven Fallback |
qualCount: #Sum qualRisk then (topN - qualCount) * (100 / topN) for SHY
|
Routes 0%, 50%, or 100% into SHY automatically depending on how many risk ETFs qualify |
| Zero-Lookahead Monthly Clock | newMonth: Month <> Month[1] |
Triggers strictly backward on the first trading day of each new month (never use EndOfMonth[-1]) |
| Zero-Churn Rebalancing |
DynamicSizing: True returning NaN when not newMonth
|
Holds unchanged ETFs continuously and trades only the net share difference at month-end |
| Clean Benchmark Overlay | Benchmark: spy_buy_and_hold |
Plots SPY equity and drawdown on the same graph without contaminating Combined stats |
Notice why we keep global BarSize: Daily rather than switching the whole script to monthly bars. Running on daily bars with newMonth: Month <> Month[1] preserves full daily mark-to-market drawdown accuracy (capturing true intra-month shocks like March 2020 that monthly bars hide) while still executing entries and rebalances strictly once a month. For more details on cross-sectional #Rank and DynamicSizing, pair this template with our RealTest SetupScore and #Rank guide and our RealTest position sizing reference.
Complete Validated RealTest Script (Dual Momentum ETF Rotation vs SPY)
Below is a complete, runnable textbook Dual Momentum script covering six global asset-class ETFs (SPY US stocks, VEU international stocks, TLT long-term Treasuries, GLD gold, VNQ real estate, and DBC commodities) plus SHY (1 to 3 year Treasury bills) as the defensive fallback, built on total-return adjusted Norgate Data ETF series so dividends are reinvested properly.
Notes:
Dual Momentum ETF rotation combining relative momentum ranking (#Rank)
with absolute momentum trend filtering against SHY Treasury bills
and monthly DynamicSizing rebalancing without daily churn.
Import:
DataSource: Norgate
IncludeList: SPY, VEU, TLT, GLD, VNQ, DBC, SHY
StartDate: 2007-01-01
EndDate: Latest
SaveAs: etf_dual_mom.rtd
Settings:
DataFile: etf_dual_mom.rtd
StartDate: 2010-01-01
EndDate: 2024-12-31
AccountSize: 100000
BarSize: Daily
Parameters:
topN: 2
Data:
// Diversified global risk ETFs plus SHY cash-equivalent fallback
isRisk: Symbol = $SPY or Symbol = $VEU or Symbol = $TLT or Symbol = $GLD or Symbol = $VNQ or Symbol = $DBC
isSafe: Symbol = $SHY
// Equal blend of 3-month, 6-month, and 12-month total return momentum
momBlend: (ROC(C, 63) + ROC(C, 126) + ROC(C, 252)) / 3
shyMom: Extern($SHY, momBlend)
// Rank strictly among the 6 risk ETFs using NaN for all other symbols
eligMom: IF(isRisk, momBlend, NaN)
momRank: #Rank eligMom
qualRisk: isRisk and momRank <= topN and momBlend > shyMom
qualCount: #Sum qualRisk
// Backward-only first trading day of each month (zero lookahead)
newMonth: Month <> Month[1]
Strategy: etf_dual_momentum
DynamicSizing: True
QtyType: Percent
// Return NaN between month turns to hold unchanged; shift unused slots to SHY
Quantity: Select(
not newMonth, NaN,
qualRisk, 100 / topN,
isSafe and qualCount < topN, (topN - qualCount) * (100 / topN),
1, 0)
MaxExposure: 100
Reduce: 1000
Commission: Max(1, Shares * 0.005)
OpenSlip: 0.0003 * FillPrice
Benchmark: spy_buy_and_hold
Side: Long
EntrySetup: Symbol = $SPY
Quantity: 100
QtyType: Percent
MaxPositions: 1
Charts:
MA200: Avg(C, 200)
Notice how Select() handles every case cleanly in four lines. Between month turns, every symbol returns NaN so zero orders trigger. On the first trading day of a new month, qualifying risk leaders receive 50 percent each, SHY receives 50 percent when one risk ETF fails absolute momentum or 100 percent when both fail, and dropped ETFs receive 0 to close at the next open. Remember that DynamicSizing: True forbids Side, EntrySetup, ExitRule, and ExitStop (as documented in our RealTest parser error reference).
Validated 2010 to 2024 Backtest Results (And Textbook Limitations)
Executed in RealTest 2.0 from January 2010 through December 2024 with IBKR commissions and 3 bps OpenSlip, this textbook 6-ETF Dual Momentum script completed 349 total transactions across all seven ETFs (87 in SPY, 68 in GLD, 64 in VNQ, 46 in DBC, 38 in VEU, 35 in TLT, and 11 defensive cash rotations into SHY).
| Metric (2010 to 2024) | etf_dual_momentum (Textbook 6-ETF) | spy_buy_and_hold (Benchmark) |
|---|---|---|
| Ending Equity ($100k start) | $288,747 | $588,449 |
| Annualized Return (ROR) | 7.34% | 12.55% |
| Maximum Daily Drawdown | -23.03% | -30.25% |
| Win Rate / Profit Factor | 67.62% / 2.28 | Single buy-and-hold |
| Average Exposure | 99.85% (includes SHY defensive holds) | 100.00% |

Look honestly at the equity comparison above. During sharp crashes like March 2020 and the 2022 stock-and-bond selloff, the absolute momentum SHY switch protected capital dramatically, holding 2020 and 2022 drawdowns far shallower than SPY. Yet across a 15-year US mega-cap bull market, an unrefined equal-weight 6-ETF textbook rotation still lagged raw US equities during choppy sideways years (2015 to 2016 and 2018 to 2019) because monthly rebalancing reacts slowly to rapid volatility regimes and treats choppy commodity or bond ETFs identically to persistent equity leaders.
Upgrading From Textbook ETF Rotation to Production Systems
Improving raw Dual Momentum without curve-fitting typically comes down to cleaner volatility scaling, smarter universe selection, and pairing monthly rotation with an uncorrelated short-term sleeve inside one portfolio (see our RealTest multi-strategy combining guide and our RealTest OrderSettings and Rebalance order guide). To test more free templates locally right away, start with our free RealTest strategy and code library or grab the Free Mean-Reversion Strategy for RealTest and Python.
If you want complete, out-of-sample validated rotation systems engineered specifically to address those textbook ETF whipsaws with full editable RealTest source code, examine our RealTest ETF Rotate Monthly Rebalance Investing Strategy and RealTest NASDAQ Momentum Rotation. To combine monthly rotation with mean reversion under one equity curve, explore the RealTest Portfolios collection or test combinations in our RealTest Strategy Combiner & Portfolio Builder.
To extend monthly ETF rotation into Wouter Keller canary allocation (DAA/VAA) and cross-sectional inverse-volatility risk parity via #Sum, read our RealTest risk parity and Keller DAA/VAA guide.
Key terms
- Dual Momentum
- A systematic rotation framework combining relative momentum (ranking risk assets against each other) with absolute momentum (requiring leaders to outperform a T-bill benchmark like SHY before investing).
- Benchmark Section
- A special RealTest script section modeling a reference asset like buy-and-hold SPY for side-by-side equity and drawdown graphing without including it in Combined portfolio stats.
- DynamicSizing NaN Hold
- Returning NaN from Quantity inside DynamicSizing True on non-rebalance bars so RealTest places zero trades and avoids daily weight-drift churn.
- Reduce Position Trade
- A partial trim generated automatically by RealTest's DynamicSizing engine when an existing winning ETF's market value grows above its target rebalance percentage.
- Total-Return Adjusted ETF Data
- Price series (such as Norgate Total Return adjustment) that reinvests ETF dividends and distributions into historical prices so momentum rankings accurately include yield.
Frequently asked questions
How do you code Dual Momentum ETF rotation in RealTest?
Precompute a blended return such as (ROC(C, 63) + ROC(C, 126) + ROC(C, 252)) / 3 in Data, isolate risk ETFs with IF(isRisk, momBlend, NaN), rank them with standalone #Rank, check absolute momentum against Extern($SHY, momBlend), count qualifying risk ETFs via #Sum, and assign target weights inside DynamicSizing True on Month <> Month[1].
How do you move unused ETF rotation slots into SHY or cash in RealTest?
Compute qualCount as #Sum qualRisk on its own Data line. Inside DynamicSizing True, assign 100 / topN to qualifying risk ETFs and assign (topN - qualCount) * (100 / topN) to SHY whenever qualCount is below topN, routing 50 percent or 100 percent smoothly into Treasury bills during bear markets.
Why does my RealTest DynamicSizing rotation trade every single day?
When DynamicSizing is True, returning a target percentage on every bar forces RealTest to buy or sell small share differences every session as prices drift. Return NaN whenever not newMonth so RealTest holds open positions untouched between scheduled rebalance dates.
Should a monthly ETF rotation script in RealTest use BarSize Monthly or Daily?
Using BarSize Daily with Month <> Month[1] is generally superior for research because it executes trades on the exact same monthly schedule while keeping full daily mark-to-market drawdown visibility during rapid intra-month crashes like March 2020.
How do you compare a RealTest ETF rotation against SPY buy and hold on one chart?
Add a Benchmark section named spy_buy_and_hold with Side Long, EntrySetup set to Symbol = $SPY, Quantity 100, QtyType Percent, and MaxPositions 1. RealTest plots the benchmark curve alongside your strategy in the Stats Graph without mixing benchmark equity into Combined portfolio totals.
Why must SHY be excluded with NaN before calling #Rank?
#Rank operates across every non-NaN symbol in the .rtd file on each date. If SHY is not masked to NaN inside eligMom before #Rank runs, SHY can occupy a top-N relative momentum slot and distort both qualCount and risk ETF weighting.