OPEN-SOURCE SCRIPT
Telah dikemas kini

Strategy Stats [presentTrading]

1 525
Hello! it's another weekend. This tool is a strategy performance analysis tool. Looking at the TradingView community, it seems few creators focus on this aspect. I've intentionally created a shared version. Welcome to share your idea or question on this.

█ Introduction and How it is Different
Strategy Stats is a comprehensive performance analytics framework designed specifically for trading strategies. Unlike standard strategy backtesting tools that simply show cumulative profits, this analytics suite provides real-time, multi-timeframe statistical analysis of your trading performance.

  • Multi-timeframe analysis: Automatically tracks performance metrics across the most recent time periods (last 7 days, 30 days, 90 days, 1 year, and 4 years)
  • Advanced statistical measures: Goes beyond basic metrics to include Information Coefficient (IC) and Sortino Ratio
  • Real-time feedback: Updates performance statistics with each new trade
  • Visual analytics: Color-coded performance table provides instant visual feedback on strategy health
  • Integrated risk management: Implements sophisticated take profit mechanisms with 3-step ATR and percentage-based exits


BTCUSD Performance
syot kilat

The table in the upper right corner is a comprehensive performance dashboard showing trading strategy statistics.

Note: While this presentation uses Vegas SuperTrend as the underlying strategy, this is merely an example. The Stats framework can be applied to any trading strategy. The Vegas SuperTrend implementation is included solely to demonstrate how the analytics module integrates with a trading strategy.

⚠️ Timeframe Limitations
Important: TradingView's backtesting engine has a maximum storage limit of 10,000 bars. When using this strategy stats framework on smaller timeframes such as 1-hour or 2-hour charts, you may encounter errors if your backtesting period is too long.

Recommended Timeframe Usage:
  • Ideal for: 4H, 6H, 8H, Daily charts and above
  • May cause errors on: 1H, 2H charts spanning multiple years
  • Not recommended for: Timeframes below 1H with long history


█ Strategy, How it Works: Detailed Explanation
The Strategy Stats framework consists of three primary components: statistical data collection, performance analysis, and visualization.

🔶 Statistical Data Collection
The system maintains several critical data arrays:
  • equityHistory: Tracks equity curve over time
  • tradeHistory: Records profit/loss of each trade
  • predictionSignals: Stores trade direction signals (1 for long, -1 for short)
  • actualReturns: Records corresponding actual returns from each trade

For each closed trade, the system captures:

float tradePnL = strategy.closedtrades.profit(tradeIndex)
float tradeReturn = strategy.closedtrades.profit_percent(tradeIndex)
int tradeType = entryPrice < exitPrice ? 1 : -1 // Direction

🔶 Performance Metrics Calculation
The framework calculates several key performance metrics:

Information Coefficient (IC):
The correlation between prediction signals and actual returns, measuring forecast skill.
IC = Correlation(predictionSignals, actualReturns)
Where Correlation is the Pearson correlation coefficient:
Correlation(X,Y) = (nΣXY - ΣXY) / √[(nΣX² - (ΣX)²)(nΣY² - (ΣY)²)]

Sortino Ratio:
Measures risk-adjusted return focusing only on downside risk:
Sortino = (Avg_Return - Risk_Free_Rate) / Downside_Deviation
Where Downside Deviation is:
Downside_Deviation = √[Σ(min(0, R_i - T)²) / n]
R_i represents individual returns, T is the target return (typically the risk-free rate), and n is the number of observations.

Maximum Drawdown:
Tracks the largest percentage drop from peak to trough:
DD = (Peak_Equity - Trough_Equity) / Peak_Equity * 100


🔶 Time Period Calculation
The system automatically determines the appropriate number of bars to analyze for each timeframe based on the current chart timeframe:
  • bars_7d = math.max(1, math.round(7 * barsPerDay))
  • bars_30d = math.max(1, math.round(30 * barsPerDay))
  • bars_90d = math.max(1, math.round(90 * barsPerDay))
  • bars_365d = math.max(1, math.round(365 * barsPerDay))
  • bars_4y = math.max(1, math.round(365 * 4 * barsPerDay))

Where barsPerDay is calculated based on the chart timeframe:
barsPerDay = timeframe.isintraday ?
24 * 60 / math.max(1, (timeframe.in_seconds() / 60)) :
timeframe.isdaily ? 1 :
timeframe.isweekly ? 1/7 :
timeframe.ismonthly ? 1/30 : 0.01

syot kilat

🔶 Visual Representation
The system presents performance data in a color-coded table with intuitive visual indicators:
  • Green: Excellent performance
  • Lime: Good performance
  • Gray: Neutral performance
  • Orange: Mediocre performance
  • Red: Poor performance


█ Trade Direction
The Strategy Stats framework supports three trading directions:
  • Long Only: Only takes long positions when entry conditions are met
  • Short Only: Only takes short positions when entry conditions are met
  • Both: Takes both long and short positions depending on market conditions



█ Usage
To effectively use the Strategy Stats framework:
  1. Apply to existing strategies: Add the performance tracking code to any strategy to gain advanced analytics
  2. Monitor multiple timeframes: Use the multi-timeframe analysis to identify performance trends
  3. Evaluate strategy health: Review IC and Sortino ratios to assess predictive power and risk-adjusted returns
  4. Optimize parameters: Use performance data to refine strategy parameters
  5. Compare strategies: Apply the framework to multiple strategies to identify the most effective approach

For best results, allow the strategy to generate sufficient trade history for meaningful statistical analysis (at least 20-30 trades).


█ Default Settings
The default settings have been carefully calibrated for cryptocurrency markets:
Performance Tracking:
  • Time periods: 7D, 30D, 90D, 1Y, 4Y
  • Statistical measures: Return, Win%, MaxDD, IC, Sortino Ratio
  • IC color thresholds: >0.3 (green), >0.1 (lime), <-0.1 (orange), <-0.3 (red)
  • Sortino color thresholds: >1.0 (green), >0.5 (lime), <0 (red)


Multi-Step Take Profit:
  • ATR multipliers: 2.618, 5.0, 10.0
  • Percentage levels: 3%, 8%, 17%
  • Short multiplier: 1.5x (makes short take profits more aggressive)
  • Stop loss: 20%





Nota Keluaran

  • Period Adjustment: Replaced previous periods with 30D, 90D, 180D, and 360D to mitigate TradingView's backtesting engine storage limitations..
  • Pair-Specific Metrics Added: Now tracks underlying asset performance, including pair returns and max drawdown, for direct benchmarking against strategy returns.
  • Improved Sortino Calculation: Adjusted Sortino ratio to exclusively measure downside volatility based on negative returns, providing clearer risk-adjusted insights.
  • Refined IC Calculation: Explicitly adjusted returns based on trade direction for more accurate Information Coefficient (IC) assessment.
  • Total Return Metrics: Added comprehensive metrics from backtest inception, enhancing long-term strategy evaluation.

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.