OPEN-SOURCE SCRIPT
Updated

Macro Momentum – 4-Theme, Vol Target, Rebalance

136
Macro Momentum — 4-Theme, Vol Target, Rebalance

Purpose. A macro-aware strategy that blends four economic “themes”—Business Cycle, Trade/USD, Monetary Policy, and Risk Sentiment—into a single, smoothed Composite signal. It then:

gates entries/exits with hysteresis bands,

enforces optional regime filters (200-day bias), and

sizes the position via volatility targeting with caps for long/short exposure.

It’s designed to run on any chart (index, ETF, futures, single stocks) while reading external macro proxies on a chosen Signal Timeframe.

How it works (high level)

Build four theme signals from robust macro proxies:

Business Cycle: XLI/XLU and Copper/Gold momentum, confirmed by the chart’s price vs a long SMA (default 200D).

Trade / USD: DXY momentum (sign-flipped so a rising USD is bearish for risk assets).

Monetary Policy: 10Y–2Y curve slope momentum and 10Y yield trend (steepening & falling 10Y = risk-on; rising 10Y = risk-off).

Risk Sentiment: VIX momentum (bearish if higher) and HYG/IEF momentum (bullish if credit outperforms duration).

Normalize & de-noise.

Optional Winsorization (MAD or stdev) clamps outliers over a lookback window.

Optional Z-score → tanh mapping compresses to ~[-1, +1] for stable weighting.

Theme lines are SMA-smoothed; the final Composite is LSMA-smoothed (linreg).

Decide direction with hysteresis.

Enter/hold long when Composite ≥ Entry Band; enter/hold short when Composite ≤ −Entry Band.

Exit bands are tighter than entry bands to avoid whipsaws.

Apply regime & direction constraints.

Optional Long-only above 200MA (chart symbol) and/or Short-only below 200MA.

Global Direction control (Long / Short / Both) and Invert switch.

Size via volatility targeting.

Realized close-to-close vol is annualized (choose 9-5 or 24/7 market profile).

Target exposure = TargetVol / RealizedVol, capped by Max Long/Max Short multipliers.

Quantity is computed from equity; futures are rounded to whole contracts.

Rebalance cadence & execution.

Trades are placed on Weekly / Monthly / Quarterly rebalance bars or when the sign of exposure flips.

Optional ATR stop/TP for single-stock style risk management.

Inputs you’ll actually tweak

General

Signal Timeframe: Where macro is sampled (e.g., D/W).

Rebalance Frequency: Weekly / Monthly / Quarterly.

ROC & SMA lengths: Defaults for theme momentum and the 200D regime filter.

Normalization: Z-score (tanh) on/off.

Winsorization

Toggle, lookback, multiplier, MAD vs Stdev.

Risk / Sizing

Target Annualized Vol & Realized Vol Lookback.

Direction (Long/Short/Both) and Invert.

Max long/short exposure caps.

Advanced Thresholds

Theme/Composite smoothing lengths.

Entry/Exit bands (hysteresis).

Regime / Execution

Long-only above 200MA, Short-only below 200MA.

Stops/TP (optional)

ATR length and SL/TP multiples.

Theme Weights

Per-theme scalars so you can push/pull emphasis (e.g., overweight Policy during rate cycles).

Macro Proxies

Symbols for each theme (XLI, XLU, HG1!, GC1!, DXY, US10Y, US02Y, VIX, HYG, IEF). Swap to alternatives as needed (e.g., UUP for DXY).

Signals & logic (under the hood)

Business Cycle = ½ ROC(XLI/XLU) + ½ ROC(Copper/Gold), then confirmed by (price > 200SMA ? +1 : −1).

Trade / USD = −ROC(DXY).

Monetary Policy = 0.6·ROC(10Y–2Y) − 0.4·ROC(10Y).

Risk Sentiment = −0.6·ROC(VIX) + 0.4·ROC(HYG/IEF).

Each theme → (optional Winsor) → (robust z or scaled ROC) → tanh → SMA smoothing.
Composite = weighted average → LSMA smoothing → compare to bands → dir ∈ {−1,0,+1}.

Rebalance & flips. Orders fire on your chosen cadence or when the sign of exposure changes.
Position size. exposure = clamp(TargetVol / realizedVol, maxLong/Short) × dir.

Note: The script also exposes Gross Exposure (% equity) and Signed Exposure (× equity) as diagnostics. These can help you audit how vol-targeting and caps translate into sizing over time.

Visuals & alerts

Composite line + columns (color/intensity reflect direction & strength).

Entry/Exit bands with green/red fills for quick polarity reads.

Hidden plots for each Theme if you want to show them.

Optional rebalance labels (direction, gross & signed exposure, σ).

Background heatmap keyed to Composite.

Alerts

Enter/Inc LONG when Composite crosses up (and on rebalance bars).

Enter/Inc SHORT when Composite crosses down (and on rebalance bars).

Exit to FLAT when Composite returns toward neutral (and on rebalance bars).

Practical tips

Start higher timeframes. Daily signals with Monthly rebalance are a good baseline; weekly signals with quarterly rebalances are even cleaner.

Tune Entry/Exit bands before anything else. Wider bands = fewer trades and less noise.

Weights reflect regime. If policy dominates markets, raise Monetary Policy weight; if credit stress drives moves, raise Risk Sentiment.

Proxies are swappable. Use UUP for USD, or futures-continuous symbols that match your data plan.

Futures vs ETFs. Quantity auto-rounds for futures; ETFs accept fractional shares. Check contract multipliers when interpreting exposure.

Caveats

Macro proxies can repaint at the selected signal timeframe as higher-TF bars form; that’s intentional for macro sampling, but test live.

Vol targeting assumes reasonably stationary realized vol over the lookback; if markets regime-shift, revisit volLook and targetVol.

If you disable normalization/winsorization, themes can become spikier; expect more hysteresis band crossings.

What to change first (quick start)

Set Signal Timeframe = D, Rebalance = Monthly, Z-score on, Winsor on (MAD).

Entry/Exit bands: 0.25 / 0.12 (defaults), then nudge until trade count and turnover feel right.

TargetVol: try 10% for diversified indices; lower for single stocks, higher for vol-sell strategies.

Leave weights = 1.0 until you’ve inspected the four theme lines; then tilt deliberately.
Release Notes
I added alerts.
Release Notes
...

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.