OPEN-SOURCE SCRIPT
Volatility-Targeted Momentum Portfolio [BackQuant]

Volatility-Targeted Momentum Portfolio [BackQuant]
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
1) What the script does at a glance
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices. Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price[lookback] - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present.
Recommended diagnostic tool. Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check:
It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose. Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Interpretation. You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking. Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Notes.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Practical advice.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.

9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.

10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.

11) Asset allocation pie chart
Builds a wheel of current allocations.

12) Inputs and quick presets
Core
Diagnostics
Presets
13) Suggested workflow
Important implementation details mapped to code
Final notes
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
- What the script does at a glance
- Momentum, what it is, how to know if it is present
- Volatility targeting, why and how it is done here
- Portfolio construction modes: Long Only, Short Only, Delta Neutral
- Regime filter and when the strategy goes to cash
- Transaction cost modelling in this script
- Backtest metrics and definitions
- Performance attribution chart
- Monte Carlo simulation
- Scatter plot analysis modes
- Asset allocation pie chart
- Inputs, presets, and deployment checklist
- Suggested workflow
1) What the script does at a glance
- Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
- Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
- Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
- Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices. Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price[lookback] - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present.
- Leaders and laggards persist across adjacent windows rather than flipping every bar.
- Spread between average momentum of leaders and laggards is materially positive in sample.
- Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
- Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool. Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check:
![Momentum Regression [BackQuant]](https://s3.tradingview.com/k/kRv35WXq_mid.png)
3) Volatility targeting: purpose and implementation here
Purpose. Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
- Return series ret = log(price/price[1]).
- Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
- Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
- Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation. You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking. Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
- Long Only. Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
- Short Only. Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
- Delta Neutral. Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes.
- The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
- If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
- Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
- Short Only active when EMA12 < EMA21. Otherwise cash.
- Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
- Per-bar drag. When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
- Turnover-linked fee. The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice.
- If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
- For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
- If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
- Net Profit percent over the full test.
- Max Drawdown percent, tracked from running peaks.
- Annualized Mean and Stdev using the chosen trading day count.
- Variance is the square of annualized stdev.
- Sharpe uses daily mean adjusted by risk-free rate and annualized.
- Sortino uses downside stdev only.
- Omega ratio of sum of gains to sum of losses.
- Gain-to-Pain total gains divided by total losses absolute.
- CAGR compounded annual growth from start date to now.
- Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
- Skewness of daily returns.
- VaR 95 linear-interpolated 5th percentile of daily returns.
- CVaR average of the worst 5 percent of daily returns.
- Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
- Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
- Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
- Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
- Risk-Return Efficiency. X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
- Momentum vs Volatility. Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
- Beta vs Alpha. X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
- Leverage vs Momentum. X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
- Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
- Short Only, weights show the short book as positive slices that sum to 100 percent.
- Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
- Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
- Portfolio Strategy. Long Only, Short Only, Delta Neutral.
- Initial Capital. For equity scaling in the panel.
- Trading Days/Year. 252 for stocks, 365 for crypto.
- Target Volatility. Annualized, drives volMult.
- Transaction Fees. Per-bar drag and composition change penalty, see the modelling notes above.
- Momentum Lookback. Ranking horizon. Shorter is more reactive, longer is steadier.
- Start Date. Ensure every symbol has data back to this date to avoid bias.
- Benchmark. Used for alpha, beta, and B&H line.
Diagnostics
- Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
- Attribution panel. Toggle winners only to focus on what matters.
- Monte Carlo mode with Normal or Bootstrap and confidence bands.
- Scatter plot type and styling, labels, and portfolio star.
- Pie chart and labels for current allocation.
Presets
- Crypto Daily, Long Only. Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
- Crypto Daily, Delta Neutral. Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
- Equities Daily, Long Only. Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
- Universe sanity check. Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
- Check momentum existence. Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
![Momentum Regression [BackQuant]](https://s3.tradingview.com/k/kRv35WXq_mid.png)
- Set risk budget. Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
- Pick mode. Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
- Tune lookback. If leaders rotate too often, lengthen it. If entries lag, shorten it.
- Validate cost assumptions. Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
- Run attribution. Confirm the strategy’s winners align with intuition and not one unstable outlier.
- Use alerts. Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
- Momentum measure. cr = price / price[lookback] - 1 per symbol for ranking. Simplicity helps avoid overfitting.
- Volatility targeting. vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
- Selection. Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
- Regime filter. EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
- Equity update. Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
- Tables. Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
- Visualization panels. Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
- Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
- Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
- Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
開源腳本
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
免責聲明
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.
開源腳本
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
免責聲明
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.