RealTest Ranking, Momentum Rotation, and Monthly Rebalancing (Validated Code Guide)
In RealTest, use SetupScore (never Legacy Mode EntryScore) to prioritize competing entry setups, and use the #Rank breadth tag on its own Data line with NaN for ineligible symbols to rank a filtered universe cleanly. For monthly rotation without lookahead bias, trigger on Month <> Month[1] or EndOfMonth and hold unchanged positions inside DynamicSizing True by returning NaN.
- SetupScore ranks competing setups in RealTest's default top-down engine (highest score enters first), whereas EntryScore is a Legacy Mode relic that introduces lookahead bias on limit and stop entries.
- Cross-sectional #Rank and #PercentRank operate horizontally across all symbols on each date, must occupy their own standalone Data line, and assign rank 1 to the highest value (descending).
- Wrapping your ranking factor in IF(InSPX and liquid, momVal, NaN) excludes non-constituents and illiquid stocks from the #Rank calculation completely rather than letting them pollute top-N ranks.
- RealTest's Top(value, digits) function extracts leading digits from TRBC industry codes (such as Top(TRBC, 2) for economic sector), NOT top-N stock rankings.
- Checking Month <> Month[1] detects the first trading day of every new month strictly backward without negative offsets, avoiding any lookahead peek into future calendar dates.
- To rebalance an equal-weight rotational portfolio monthly without selling and rebuying unchanged winners, use DynamicSizing True with Select(not EndOfMonth, NaN, mustExit, 0, canEnter or Shares, 100 / topN).
Cross-sectional ranking and rotational portfolios are where RealTest leaves single-symbol charting platforms behind. Yet ranking code is also one of the easiest areas to break subtly. Traders routinely confuse SetupScore with EntryScore, try to invent a Top(ROC(C, 126), 10) function that does not exist, or run #Rank across an unfiltered data file so SPY and illiquid tickers steal slots from S&P 500 constituents.
Every rule below follows the official RealTest SetupScore and ranking documentation, and the complete S&P 500 monthly rotation script was parsed and backtested in RealTest 2.0 across 15 years of survivorship-free Norgate data.
SetupScore vs #Rank vs Rank() vs ExitRank in RealTest
RealTest provides four distinct ranking tools that operate at different points in the engine. Mixing them up causes either parse errors or silent ranking distortion.
| RealTest Element | Where It Lives | Direction & Scope | Primary Role in a Rotation Script |
|---|---|---|---|
#Rank / #PercentRank
|
Data (standalone line only) |
Horizontal across all symbols on each date (1 = highest) |
Computes cross-sectional universe rank before the test starts |
SetupScore |
Strategy |
Highest score first among today's qualifying setups | Decides which setups get filled when setups exceed MaxPositions
|
ExitScore & ExitRank
|
Strategy |
Horizontal across currently open positions each bar | Ranks held positions to drop the weakest holdings first |
Rank(expr, count) |
Any formula | Vertical over one symbol's own past count bars |
Time-series rank within one stock (NOT cross-sectional) |
Two common traps deserve special attention. First, omit EntryScore in modern RealTest scripts because EntryScore applies only in Legacy Mode and creates lookahead bias on limit or stop strategies. Second, do not confuse RealTest's Top(value, digits) function with stock ranking. In RealTest, Top(TRBC, 2) slices the leading digits of a TRBC sector code; top-N stock selection always uses #Rank in Data or SetupScore plus MaxPositions in Strategy.
Why NaN Filtering Inside #Rank Prevents Universe Contamination
When RealTest runs momRank: #Rank ROC(C, 126), it ranks every symbol stored in the .rtd file on that date, including benchmark ETFs like SPY, stocks below your liquidity floor, and stocks that were not members of the S&P 500 on that date. Per the RealTest User Guide, any symbol whose input formula returns NaN is excluded from the #Rank array completely and receives NaN as its rank.
Data:
momVal: ROC(C, 126)
ma200: Avg(C, 200)
liquid: C > 5 and Avg(C * V, 20) > 20000000
// NaN excludes non-SPX, illiquid, and downtrend stocks before #Rank runs
eligMom: IF(InSPX and liquid and C > ma200, momVal, NaN)
// #Rank MUST start its own standalone Data line
momRank: #Rank eligMom
Keep #Rank at the very start of its own Data line. Placing a breadth operator inside parentheses or arithmetic (such as momVal - (#Avg momVal)) fails to parse with expected an operator here. Also remember that RealTest's #Rank is descending (rank 1 = highest value), so buying the strongest 10 stocks uses momRank <= 10.
Monthly Rebalancing Without Lookahead Bias (Standard vs DynamicSizing)
There are two clean ways to rotate a portfolio monthly in RealTest depending on whether you want simple rank-buffer holding (standard strategy mode) or exact monthly equal-weight resizing of existing winners (DynamicSizing: True).
To trigger on the first trading day of every new month using strictly backward data (zero negative-offset lookahead like EndOfMonth[-1]), define newMonth: Month <> Month[1]. At the month turn, exiting only when a stock falls outside a rank buffer (for example buying top 10 and holding until rank drops past 20) cuts unnecessary turnover dramatically compared to rotating every single slot each month.
If instead you want true monthly weight rebalancing (trimming winners that grew to 14 percent back down to 10 percent and topping up laggards without closing and reopening the entire position), RealTest's DynamicSizing: True mode handles it natively by returning NaN on non-rebalance days.
// True monthly equal-weight rebalance in DynamicSizing mode
Strategy: spx_monthly_rebalance_dynamic
DynamicSizing: True
QtyType: Percent
SetupScore: momVal
// Return NaN on non-rebalance days so open holdings stay untouched
Quantity: Select(
not newMonth, NaN,
not spyUp or IsNaN(momRank) or momRank > bufferRank, 0,
momRank <= topN or Shares > 0, 100 / topN)
MaxExposure: 100
Reduce: 0.01 * S.Alloc
Commission: Max(1, Shares * 0.005)
Slippage: 0.02
Notice the subtle power of Select here. Between month turns, Quantity returns NaN, which tells RealTest to place zero orders. On a month turn, stocks dropping out of the buffer receive 0 (full exit), while top-ranked entries and retained holdings receive 100 / topN, automatically generating only the net share difference required to restore equal weights. For full details on DynamicSizing, MaxExposure, and Reduce, see our RealTest position sizing and volatility guide.
Complete Validated RealTest Script (S&P 500 Monthly Momentum Rotation)
Below is a complete, runnable S&P 500 monthly momentum rotation script built on Norgate Data historical constituents (InSPX). It buys the top 10 liquid S&P 500 momentum leaders above their 200-day moving average when SPY is in an uptrend, holds them until their rank drops past 20 or the regime filter turns off, and labels each exit clearly with Select (rank_drop vs regime_off). If you need guidance on Norgate historical constituency tiers, read our Norgate Data and RealTest plan guide.
Notes:
Validated RealTest monthly momentum rotation demonstrating #Rank with NaN
universe filtering, backward-only month-turn rebalancing (zero lookahead),
and rank-buffer exits with custom Select exit reasons.
Import:
DataSource: Norgate
IncludeList: .S&P 500 Current & Past
IncludeList: SPY
StartDate: 2005-01-01
EndDate: Latest
SaveAs: spx_rotation.rtd
Settings:
DataFile: spx_rotation.rtd
StartDate: 2010-01-01
EndDate: 2024-12-31
AccountSize: 100000
BarSize: Daily
Parameters:
topN: 10
bufferRank: 20
momLen: 126
Data:
momVal: ROC(C, momLen)
vol20: Avg(C * V, 20)
ma200: Avg(C, 200)
spyUp: Extern($SPY, C > Avg(C, 200))
liquid: C > 5 and vol20 > 20000000
eligMom: IF(InSPX and liquid and C > ma200, momVal, NaN)
momRank: #Rank eligMom
newMonth: Month <> Month[1]
Strategy: spx_monthly_rotation_buffer
Side: Long
EntrySetup: newMonth and spyUp and momRank <= topN
SetupScore: momVal
Quantity: 100 / topN
QtyType: Percent
MaxPositions: topN
MinFreeCash: 0.02 * S.Equity
Commission: Max(1, Shares * 0.005)
Slippage: 0.02
ExitRule: Select(
newMonth and not spyUp, "regime_off",
newMonth and (IsNaN(momRank) or momRank > bufferRank), "rank_drop")
ExitTime: NextOpen
Charts:
MA200: ma200
Validated in RealTest 2.0 from 2010 through 2024 across historical S&P 500 constituents (including delisted names such as BDK-201003, PXD-202405, and MEE-201106), this syntax template completed 520 trades across 15 years with 368 rank_drop exits, 133 regime_off exits, 10 end-of-data exits, and 9 end-of-test closures.

Why Your SetupScore Might Appear to Do Nothing
A frequent RealTest forum question is why changing SetupScore produces the exact same equity curve. SetupScore only acts as a tie-breaker when more symbols pass EntrySetup than your capacity constraints (MaxPositions, MaxExposure, or MaxInvested) can accept. If you already restricted EntrySetup to momRank <= 10 with MaxPositions: 10 and zero existing holdings, all 10 setups fit regardless of SetupScore. Once you introduce a rank buffer (such as holding 7 winners and filling 3 open slots from 10 candidates), SetupScore immediately governs which 3 stocks take the open slots. You can also inspect rejected candidates using KeepTrades: All from our RealTest debugging guide.
From Ranking Template to Production Rotation Systems
Monthly rotation systems shine when paired with low-correlation mean-reversion or breakout sleeves inside a single RealTest portfolio. To start testing clean scripts immediately, download templates from our free RealTest strategy and code library or explore the Free Mean-Reversion Strategy for RealTest and Python.
If you want complete, out-of-sample validated momentum rotation systems ready to import straight into RealTest, examine our RealTest ETF Rotate Monthly Rebalance Strategy and the RealTest NASDAQ Momentum Rotation Strategy. When you are ready to run monthly rotations live through Interactive Brokers, review our Dual Momentum ETF rotation RealTest blueprint, our RealTest OrdersMode and IBKR order generation syntax guide, and our RealTest trailing stop guide.
To build custom ranking formulas like Clenow exponential regression R-squared, SuperTrend, and VCP contraction scores, read our RealTest SuperTrend, MACD, VCP, and Clenow R-Squared guide, our RealTest TRBC sector caps and #ByEcon ranking guide, and our RealTest weekly Clenow momentum blueprint.
Key terms
- SetupScore
- A RealTest Strategy formula that sorts competing qualifying setups from highest to lowest before capacity constraints (MaxPositions, MaxExposure) select which orders are placed.
- #Rank
- A RealTest cross-sectional breadth operator placed at the start of a Data item that ranks all non-NaN symbols horizontally on each date with 1 assigned to the highest value.
- #PercentRank
- A RealTest cross-sectional breadth operator that assigns each non-NaN symbol a percentile rank from 0 to 100 across the universe on each date.
- ExitScore
- A RealTest Strategy formula evaluated across currently open positions each bar to compute ExitRank so weak holdings can be rotated out ahead of stronger holdings.
- Rank Buffer
- A rotation design where a strategy enters only top-N ranked stocks (such as rank 1 to 10) but holds existing positions until their rank falls past a wider threshold (such as rank 20) to cut turnover.
- EndOfMonth
- A RealTest bar date flag returning 1 on the final trading session of each calendar month across the unified data file calendar (or CalendarSym).
Frequently asked questions
What is the difference between SetupScore and #Rank in RealTest?
#Rank is a Data-section cross-sectional breadth operator that ranks every eligible symbol on each date before the backtest starts (1 = highest) so you can filter entries or exits by rank number. SetupScore is a Strategy-section tie-breaker formula that prioritizes today's qualifying setups (highest first) whenever setups exceed MaxPositions or MaxExposure.
How do you rank only S&P 500 or liquid stocks with #Rank in RealTest?
Assign NaN to ineligible symbols in a separate Data item before calling #Rank, such as eligMom as IF(InSPX and liquid, ROC(C, 126), NaN) followed by momRank as #Rank eligMom. RealTest excludes NaN values from the ranking pool so non-constituents never occupy top-N slots.
Should I use SetupScore or EntryScore in RealTest?
Always use SetupScore. EntryScore is a Legacy Mode directive that has no use case in RealTest's default top-down engine and causes lookahead bias when combined with EntryLimit or EntryStop orders.
How do you code a monthly rebalance in RealTest without lookahead bias?
Define newMonth as Month <> Month[1] (which fires strictly on the first trading day of each new month without peeking forward) or use EndOfMonth with a HolidayList. In standard mode, gate EntrySetup and ExitRule with newMonth; for true weight rebalancing of unchanged holdings, use DynamicSizing True and return NaN on non-rebalance bars.
Why does #Rank inside an arithmetic formula give a syntax error in RealTest?
RealTest requires every breadth operator (#Rank, #PercentRank, #Avg, #Sum) to sit at the very start of its own Data item. Split the breadth calculation onto one line, then combine or filter that Data item on the next line.
Does RealTest have a Top() function for selecting the top 10 stocks?
No. RealTest's Top(value, digits) function extracts leading digits from numeric codes like TRBC sector identifiers (for example Top(TRBC, 2) for economic sector). To select the top 10 ranked stocks, use #Rank with momRank <= 10 or set SetupScore with MaxPositions 10.