OPEN-SOURCE SCRIPT
Relative Momentum Rotation [CHE]

Relative Momentum Rotation [CHE] — Ranks assets by multi-horizon momentum for guided rotational selection with regime overlay
Summary
This indicator evaluates a universe of assets using a blended momentum measure across three time horizons, then ranks them to highlight top performers for potential portfolio rotation. It incorporates a regime filter to contextualize signals, tinting the background to indicate favorable or unfavorable market conditions and labeling transitions for awareness. By focusing on relative strength within a selectable universe, it helps identify leaders without relying on absolute thresholds, reducing noise from isolated trends and promoting disciplined asset switching.
Motivation: Why this design?
Traders often struggle with momentum signals that perform unevenly across market phases, such as overreacting in volatile periods or lagging in steady uptrends, leading to suboptimal rotations in multi-asset portfolios. The core idea of relative momentum rotation addresses this by comparing assets head-to-head within a defined group, blending short- and long-term changes to capture sustained strength while a regime overlay adds a macro layer to avoid fighting broader trends. This setup prioritizes peer-relative outperformance over standalone measures, aiding consistent selection in rotational strategies.
What’s different vs. standard approaches?
- Reference baseline: Traditional rate-of-change indicators track absolute price shifts over a single window, which can generate whipsaws in sideways markets or miss cross-asset opportunities.
- Architecture differences:
- Blends three distinct horizons into one composite score for a fuller momentum picture, rather than isolating one period.
- Applies ranking across a customizable universe (e.g., crypto or tech stocks) to emphasize relatives, not absolutes.
- Integrates a simple regime check via moving average crossover on a reference symbol, gating selections without overcomplicating the core logic.
- Outputs a dynamic table for visual ranking, plus subtle visual cues like background tints, instead of cluttered plots.
- Practical effect: Charts show clearer hierarchy among assets, with regime tints providing at-a-glance context—top ranks stand out more reliably in bull regimes, helping traders focus rotations without constant recalibration.
How it works (technical)
The indicator starts by assembling a list of symbols from the selected universe, including only those marked as active to keep the group focused. For each symbol, it gathers change rates over three specified horizons on a higher timeframe, blends them using user-defined weights (automatically normalized if they do not sum to one), and computes a single composite score. Scores are then ranked to select the top performers up to a set number, forming a rotation candidate list.
To add context, a regime state is determined by comparing the reference symbol's price to its moving average on daily bars—above signals a positive environment, below a negative one, with an option to invert this logic. The current chart's symbol is checked against the top list for inclusion status. All higher-timeframe data pulls are set to avoid lookahead bias, though updates may shift slightly until bars close. Persistent variables track the table state and prior regime to handle redraws efficiently, ensuring the display rebuilds only when the selection count changes.
Parameter Guide
Universe — Switches between predefined crypto or US-tech symbol sets for ranking peers. Default: Crypto. Trade-offs/Tips: Crypto for volatile assets; US-Tech for equities—match to your portfolio to avoid mismatched volatility.
Include Symbol 1–12 — Toggles individual symbols in the universe on or off. Default: Varies (true for top 10, false for extras). Trade-offs/Tips: Start with defaults for a balanced group; disable laggards to sharpen focus, but keep at least 5–8 for robust ranking.
Scoring Timeframe — Sets the aggregation period for momentum changes (e.g., monthly bars). Default: Monthly. Trade-offs/Tips: Monthly for long-term rotation; weekly for faster signals—increases noise if too short.
Weight 12m / 6m / 3m — Adjusts emphasis on long/medium/short horizons in the blend. Default: 0.50 / 0.30 / 0.20. Trade-offs/Tips: Heavier long-term for stability in trends; balance to fit asset class—test sums near 1.0 to avoid auto-normalization surprises.
ROC over MA instead of Close — Uses smoothed averages for change rates to reduce chop. Default: False. Trade-offs/Tips: Enable in noisy markets for fewer false tops; adds slight lag, so monitor for delayed rotations.
Top N to hold — Limits selections to this many highest-ranked assets. Default: 10. Trade-offs/Tips: Lower for concentrated bets (higher risk/reward); higher for diversification—align with your position sizing.
Mark current symbol if in Top N — Highlights if the chart's asset ranks in the selection. Default: True. Trade-offs/Tips: Useful for self-scanning; disable in multi-chart setups to declutter.
Enable Regime Filter — Activates macro overlay using reference symbol. Default: True. Trade-offs/Tips: Core for trend-aware trading; disable for pure momentum plays, but risks counter-trend entries.
Regime Symbol — Chooses the benchmark for regime (e.g., broad index). Default: QQQ. Trade-offs/Tips: Broad market proxy like SPY for equities; swap for BTC in crypto to match universe.
SMA Length (D) — Sets the averaging window for regime comparison. Default: 100. Trade-offs/Tips: Longer for fewer flips (smoother regimes); shorter for quicker detection—default suits daily checks.
Invert (rare) — Flips the regime logic (price above average becomes negative). Default: False. Trade-offs/Tips: Only if your view inverts the benchmark; test thoroughly as it reverses all tints/labels.
Show Ranking Table — Displays the ranked list with scores and regime status. Default: True. Trade-offs/Tips: Essential for selection; position tweaks help on crowded charts.
Table X / Y — Places the table on the chart (e.g., top-right). Default: Right / Top. Trade-offs/Tips: Corner placement avoids price overlap; middle for central focus in reviews.
Dark Theme — Applies inverted colors for visibility. Default: True. Trade-offs/Tips: Matches most TradingView themes; toggle for light backgrounds without losing contrast.
Text Size — Scales table font for readability. Default: Normal. Trade-offs/Tips: Smaller for dense data; larger on big screens—impacts only last-bar render.
Background Tint by Regime — Colors the chart faintly green/red based on state. Default: True. Trade-offs/Tips: Subtle cue for immersion; disable if it distracts from price action.
Label on Regime Flip — Adds text markers at state changes. Default: True. Trade-offs/Tips: Aids journaling flips; space them by disabling in low-vol periods to cut clutter.
Reading & Interpretation
The ranking table lists top assets by position, symbol, percentage score (higher indicates stronger blended momentum), and regime status—green "ON" for favorable, red "OFF" for cautionary. Background shifts to a light teal in positive regimes (suggesting alignment for longs) or pale red in negative ones (hinting at reduced exposure). Flip labels appear as green "Regime ON" above bars or red "Regime OFF" below, marking transitions without ongoing noise. If the current symbol appears in the top rows with a solid score, it signals potential hold or entry priority within rotations.
Practical Workflows & Combinations
- Trend following: Scan the table weekly on monthly charts for top entrants; confirm with higher highs/lows in price structure before rotating in. Use regime tint as a veto—skip buys in red phases.
- Exits/Stops: Rotate out of bottom-half ranks monthly; tighten stops below recent lows during regime flips to protect against reversals. Pair with volatility filters like average true range for dynamic sizing.
- Multi-asset/Multi-TF: Defaults work across crypto/equities on daily+ timeframes; for intraday, shorten scoring to weekly but expect more interim noise. Scale universe size with portfolio count—e.g., top 5 for aggressive crypto rotations.
Behavior, Constraints & Performance
Signals update on bar close to confirm higher-timeframe data, but live bars may preview shifts from security calls, introducing minor repaint until finalized—mitigated by non-lookahead settings, though daily regime checks can lag by one session. Arrays handle up to 12 symbols efficiently, with loops capped at selection size; max bars back at 5000 supports historical depth without overload. Resource use stays low, but dense universes on very long charts may slow initial loads.
Known limits include sensitivity to universe composition (skewed groups amplify biases) and regime lag at sharp market turns, potentially delaying rotations by a period.
Sensible Defaults & Quick Tuning
Defaults assume a 10-asset crypto rotation on monthly scoring with balanced weights and QQQ regime—ideal for intermediate-term equity-like plays. For too-frequent table reshuffles, extend scoring timeframe or weight longer horizons more. If selections feel sluggish, shorten the 3-month weight or enable MA smoothing off. In high-vol environments, raise top N and SMA length for stability; for crypto bursts, drop to weekly scoring and invert regime if using a volatile proxy.
What this indicator is—and isn’t
This is a selection and visualization tool for momentum-based rotations, layering relative ranks and regime context onto charts to inform asset picks. It is not a standalone system—pair it with entry/exit rules, position sizing, and risk limits. Nor is it predictive; it reacts to past changes and may underperform in prolonged ranges or during universe gaps.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Where does it come from, specifically?
The principle of “composite momentum across multiple horizons” is common in TAA/rotation strategies. As a documented example: Keller/Butler use a composite 1/3/6/12-month momentum (“13612W”)—same idea, different windows/weights.
Robot Wealth
A practical vendor example: EPS Momentum calculates an RMR composite as a weighted mix of 12/6/3/1-month ranks (very close to “12/6/3”).
EPS Momentum
Related but not identical: StockCharts’ RRG measures the momentum rotation of relative strength—often mentioned in the same context, but it doesn’t have a fixed “12/6/3” composite.
chartschool.stockcharts.com
How is it typically computed?
ROC_12 + ROC_6 + ROC_3 (often scaled/weighted), then ranked vs. peers; the rotation periodically holds the top ranks in the portfolio. (Variants use different weights or additionally include 1-month—see the sources above.)
robotwealth.com/wp-content/uploads/2017/07/Momentum-and-Markowtiz-A-Golden-Combination.pdf
epsmomentum.com/tutorials
Summary
This indicator evaluates a universe of assets using a blended momentum measure across three time horizons, then ranks them to highlight top performers for potential portfolio rotation. It incorporates a regime filter to contextualize signals, tinting the background to indicate favorable or unfavorable market conditions and labeling transitions for awareness. By focusing on relative strength within a selectable universe, it helps identify leaders without relying on absolute thresholds, reducing noise from isolated trends and promoting disciplined asset switching.
Motivation: Why this design?
Traders often struggle with momentum signals that perform unevenly across market phases, such as overreacting in volatile periods or lagging in steady uptrends, leading to suboptimal rotations in multi-asset portfolios. The core idea of relative momentum rotation addresses this by comparing assets head-to-head within a defined group, blending short- and long-term changes to capture sustained strength while a regime overlay adds a macro layer to avoid fighting broader trends. This setup prioritizes peer-relative outperformance over standalone measures, aiding consistent selection in rotational strategies.
What’s different vs. standard approaches?
- Reference baseline: Traditional rate-of-change indicators track absolute price shifts over a single window, which can generate whipsaws in sideways markets or miss cross-asset opportunities.
- Architecture differences:
- Blends three distinct horizons into one composite score for a fuller momentum picture, rather than isolating one period.
- Applies ranking across a customizable universe (e.g., crypto or tech stocks) to emphasize relatives, not absolutes.
- Integrates a simple regime check via moving average crossover on a reference symbol, gating selections without overcomplicating the core logic.
- Outputs a dynamic table for visual ranking, plus subtle visual cues like background tints, instead of cluttered plots.
- Practical effect: Charts show clearer hierarchy among assets, with regime tints providing at-a-glance context—top ranks stand out more reliably in bull regimes, helping traders focus rotations without constant recalibration.
How it works (technical)
The indicator starts by assembling a list of symbols from the selected universe, including only those marked as active to keep the group focused. For each symbol, it gathers change rates over three specified horizons on a higher timeframe, blends them using user-defined weights (automatically normalized if they do not sum to one), and computes a single composite score. Scores are then ranked to select the top performers up to a set number, forming a rotation candidate list.
To add context, a regime state is determined by comparing the reference symbol's price to its moving average on daily bars—above signals a positive environment, below a negative one, with an option to invert this logic. The current chart's symbol is checked against the top list for inclusion status. All higher-timeframe data pulls are set to avoid lookahead bias, though updates may shift slightly until bars close. Persistent variables track the table state and prior regime to handle redraws efficiently, ensuring the display rebuilds only when the selection count changes.
Parameter Guide
Universe — Switches between predefined crypto or US-tech symbol sets for ranking peers. Default: Crypto. Trade-offs/Tips: Crypto for volatile assets; US-Tech for equities—match to your portfolio to avoid mismatched volatility.
Include Symbol 1–12 — Toggles individual symbols in the universe on or off. Default: Varies (true for top 10, false for extras). Trade-offs/Tips: Start with defaults for a balanced group; disable laggards to sharpen focus, but keep at least 5–8 for robust ranking.
Scoring Timeframe — Sets the aggregation period for momentum changes (e.g., monthly bars). Default: Monthly. Trade-offs/Tips: Monthly for long-term rotation; weekly for faster signals—increases noise if too short.
Weight 12m / 6m / 3m — Adjusts emphasis on long/medium/short horizons in the blend. Default: 0.50 / 0.30 / 0.20. Trade-offs/Tips: Heavier long-term for stability in trends; balance to fit asset class—test sums near 1.0 to avoid auto-normalization surprises.
ROC over MA instead of Close — Uses smoothed averages for change rates to reduce chop. Default: False. Trade-offs/Tips: Enable in noisy markets for fewer false tops; adds slight lag, so monitor for delayed rotations.
Top N to hold — Limits selections to this many highest-ranked assets. Default: 10. Trade-offs/Tips: Lower for concentrated bets (higher risk/reward); higher for diversification—align with your position sizing.
Mark current symbol if in Top N — Highlights if the chart's asset ranks in the selection. Default: True. Trade-offs/Tips: Useful for self-scanning; disable in multi-chart setups to declutter.
Enable Regime Filter — Activates macro overlay using reference symbol. Default: True. Trade-offs/Tips: Core for trend-aware trading; disable for pure momentum plays, but risks counter-trend entries.
Regime Symbol — Chooses the benchmark for regime (e.g., broad index). Default: QQQ. Trade-offs/Tips: Broad market proxy like SPY for equities; swap for BTC in crypto to match universe.
SMA Length (D) — Sets the averaging window for regime comparison. Default: 100. Trade-offs/Tips: Longer for fewer flips (smoother regimes); shorter for quicker detection—default suits daily checks.
Invert (rare) — Flips the regime logic (price above average becomes negative). Default: False. Trade-offs/Tips: Only if your view inverts the benchmark; test thoroughly as it reverses all tints/labels.
Show Ranking Table — Displays the ranked list with scores and regime status. Default: True. Trade-offs/Tips: Essential for selection; position tweaks help on crowded charts.
Table X / Y — Places the table on the chart (e.g., top-right). Default: Right / Top. Trade-offs/Tips: Corner placement avoids price overlap; middle for central focus in reviews.
Dark Theme — Applies inverted colors for visibility. Default: True. Trade-offs/Tips: Matches most TradingView themes; toggle for light backgrounds without losing contrast.
Text Size — Scales table font for readability. Default: Normal. Trade-offs/Tips: Smaller for dense data; larger on big screens—impacts only last-bar render.
Background Tint by Regime — Colors the chart faintly green/red based on state. Default: True. Trade-offs/Tips: Subtle cue for immersion; disable if it distracts from price action.
Label on Regime Flip — Adds text markers at state changes. Default: True. Trade-offs/Tips: Aids journaling flips; space them by disabling in low-vol periods to cut clutter.
Reading & Interpretation
The ranking table lists top assets by position, symbol, percentage score (higher indicates stronger blended momentum), and regime status—green "ON" for favorable, red "OFF" for cautionary. Background shifts to a light teal in positive regimes (suggesting alignment for longs) or pale red in negative ones (hinting at reduced exposure). Flip labels appear as green "Regime ON" above bars or red "Regime OFF" below, marking transitions without ongoing noise. If the current symbol appears in the top rows with a solid score, it signals potential hold or entry priority within rotations.
Practical Workflows & Combinations
- Trend following: Scan the table weekly on monthly charts for top entrants; confirm with higher highs/lows in price structure before rotating in. Use regime tint as a veto—skip buys in red phases.
- Exits/Stops: Rotate out of bottom-half ranks monthly; tighten stops below recent lows during regime flips to protect against reversals. Pair with volatility filters like average true range for dynamic sizing.
- Multi-asset/Multi-TF: Defaults work across crypto/equities on daily+ timeframes; for intraday, shorten scoring to weekly but expect more interim noise. Scale universe size with portfolio count—e.g., top 5 for aggressive crypto rotations.
Behavior, Constraints & Performance
Signals update on bar close to confirm higher-timeframe data, but live bars may preview shifts from security calls, introducing minor repaint until finalized—mitigated by non-lookahead settings, though daily regime checks can lag by one session. Arrays handle up to 12 symbols efficiently, with loops capped at selection size; max bars back at 5000 supports historical depth without overload. Resource use stays low, but dense universes on very long charts may slow initial loads.
Known limits include sensitivity to universe composition (skewed groups amplify biases) and regime lag at sharp market turns, potentially delaying rotations by a period.
Sensible Defaults & Quick Tuning
Defaults assume a 10-asset crypto rotation on monthly scoring with balanced weights and QQQ regime—ideal for intermediate-term equity-like plays. For too-frequent table reshuffles, extend scoring timeframe or weight longer horizons more. If selections feel sluggish, shorten the 3-month weight or enable MA smoothing off. In high-vol environments, raise top N and SMA length for stability; for crypto bursts, drop to weekly scoring and invert regime if using a volatile proxy.
What this indicator is—and isn’t
This is a selection and visualization tool for momentum-based rotations, layering relative ranks and regime context onto charts to inform asset picks. It is not a standalone system—pair it with entry/exit rules, position sizing, and risk limits. Nor is it predictive; it reacts to past changes and may underperform in prolonged ranges or during universe gaps.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Where does it come from, specifically?
The principle of “composite momentum across multiple horizons” is common in TAA/rotation strategies. As a documented example: Keller/Butler use a composite 1/3/6/12-month momentum (“13612W”)—same idea, different windows/weights.
Robot Wealth
A practical vendor example: EPS Momentum calculates an RMR composite as a weighted mix of 12/6/3/1-month ranks (very close to “12/6/3”).
EPS Momentum
Related but not identical: StockCharts’ RRG measures the momentum rotation of relative strength—often mentioned in the same context, but it doesn’t have a fixed “12/6/3” composite.
chartschool.stockcharts.com
How is it typically computed?
ROC_12 + ROC_6 + ROC_3 (often scaled/weighted), then ranked vs. peers; the rotation periodically holds the top ranks in the portfolio. (Variants use different weights or additionally include 1-month—see the sources above.)
robotwealth.com/wp-content/uploads/2017/07/Momentum-and-Markowtiz-A-Golden-Combination.pdf
epsmomentum.com/tutorials
Script de código abierto
Siguiendo fielmente el espíritu de TradingView, el creador de este script lo ha publicado en código abierto, permitiendo que otros traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la publicación de este código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.
Script de código abierto
Siguiendo fielmente el espíritu de TradingView, el creador de este script lo ha publicado en código abierto, permitiendo que otros traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la publicación de este código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.