INVITE-ONLY SCRIPT
已更新

Custom Portfolio [BackQuant]

373
Custom Portfolio {BackQuant]

Overview
This script turns TradingView into a lightweight portfolio optimizer with institutional-grade analytics and real-time position management capabilities.

Rank up to 15 tickers every bar using a pair-wise relative-strength "league table" that compares each asset against all others through your choice of 12 technical indicators.
Auto-allocate 100% of capital to the single strongest asset and optionally apply dynamic leverage when the aggregate market is trending, with full position tracking and rebalancing logic.
Track performance against a custom buy-and-hold benchmark while watching a fully fledged stats dashboard update in real time, including 15 professional risk metrics.

How it works
Relative-strength engine – Each asset is compared against every other asset with a user-selectable indicator (default: 9/21 EMA cross). The system generates a complete comparison matrix where Asset A vs Asset B, Asset A vs Asset C, and so on, creating strength scores. The summed scores crown a weekly/daily/hourly "winner" that receives the full allocation.
Regime filter – A second indicator applied to TOTAL crypto-market cap (or any symbol you choose) classifies the environment as trending or mean-reverting. Leverage activates only in trending regimes, protecting capital during choppy or declining markets. Choose from indicators like Universal Trend Model, Relative Strength Overlay, Momentum Velocity, or Custom RSI for regime detection.
Capital & position logic – Equity grows linearly when flat and multiplicatively while invested. The system tracks entry prices, calculates returns including leverage adjustments, and handles position transitions seamlessly. Optional intra-trade leverage rebalancing keeps exposure in sync with market conditions, recalculating position sizes as regime conditions change.
Risk & performance analytics – Every confirmed bar records return, drawdown, VaR/CVaR, Sharpe, Sortino, alpha/beta vs your benchmark, gain-to-pain, Calmar, win-rate, Omega ratio, portfolio variance, skewness, and annualized statistics. All metrics render in a professional table for instant inspection with proper annualization based on your selected trading days (252 for traditional markets, 365 for crypto).
Key inputs

Backtest window – Hard-code a start date or let the script run from series' inception with full date range validation.
Asset list (15 slots) – Works with spot, futures, indices, even synthetic spreads (e.g., BYBIT:BTCUSDT.P). The script automatically cleans ticker symbols for display.
Indicator universe – Switch the comparative metric to DEMA, BBPCT, LSMAz adaptive scores, Volatility WMA, DEMA ATR, Median Supertrend, and more proprietary indicators.

With more always being added!

Leverage settings – Max leverage from 1x to any multiple, auto-rebalancing toggle, trend/reversion thresholds with precision controls.
Visual toggles – Show/hide equity curve, rolling drawdown heat-map, daily PnL spikes, position label, advanced metrics table, buy-and-hold comparison equity.
Risk-free rate input – Customize the risk-free rate for accurate Sharpe ratio calculations, supporting both percentage and decimal inputs.

On-chart visuals

Color-coded equity curve with "shadow" offset for depth perception that changes from green (profitable) to red (losing) based on recent performance momentum.
Rolling drawdown strip that fades from light to deep red as losses widen, with customizable maximum drawdown scaling for visual clarity.
Optional daily-return histogram line and zero reference for understanding day-to-day volatility patterns.
Bottom-center table prints the current winning ticker in real time with clean formatting.
Top-right metrics grid updates every bar with 15 key performance indicators formatted to three decimal places for precision.
Benchmark overlay showing buy-and-hold performance of your selected index (default: SPX) for relative performance comparison.

Typical workflow
Add the indicator on a blank chart (overlay off).
Populate ticker slots with the assets you actually trade from your broker's symbol list.
Pick your momentum or mean-reversion metric and a regime filter that matches your market hypothesis.
Set max leverage (1 = spot only) and decide if you want dynamic rebalancing.
Press the little "L" on the price axis to view the equity curve in log scale for better long-term visualization.
Enable the metrics table to monitor Sharpe, Sortino, and drawdown in real time.
Iterate through different asset combinations and indicator settings; compare performance vs buy-and-hold; refine until you find robust parameters.
Who is it for?

Systematic crypto traders looking for a one-click, cross-sectional rotation model with professional risk management.
Portfolio quants who need rapid prototyping without leaving TradingView or exporting to Python/R.
Swing traders wanting an at-a-glance health check of their multi-coin basket with instant position signals.
Fund managers requiring detailed performance attribution and risk metrics for client reporting.
Researchers backtesting momentum and mean-reversion strategies across multiple assets simultaneously.

Important notes & tips
Set Trading Days in a Year to 252 for traditional markets; 365 for 24/7 crypto to ensure accurate annualization.
CAGR and Sharpe assume the backtest start date you choose—short windows can inflate stats, so test across multiple market cycles.
Leverage is theoretical; always confirm your broker's margin rules and account for funding costs not modeled here.
The script is computationally heavy at 15 assets due to the N×N comparison matrix—reduce the list or lengthen the timeframe if you hit execution limits.
Best results often come from mixing assets with different volatility profiles rather than highly correlated instruments.
The regime filter symbol can be changed from CRYPTOCAP:TOTAL to any broad market index that represents your asset universe.
發行說明
Chart fix.
發行說明
Chart Fix part 2
發行說明
Added: Ability to choose ticker in which the regime filter is calculated on.

免責聲明

這些資訊和出版物並不意味著也不構成TradingView提供或認可的金融、投資、交易或其他類型的意見或建議。請在使用條款閱讀更多資訊。