OPEN-SOURCE SCRIPT
Aggiornato Analyst Targets Probability

This indicator calculates the probability of the current stock price reaching or exceeding the analyst-provided high, average, and low price targets within a one-year time horizon. It utilizes a geometric Brownian motion (GBM) model, a standard approach in financial modeling that assumes log-normal price distribution with constant volatility.
### Key Features:
- **Analyst Targets**: Automatically pulls the high, average, and low one-year price targets from TradingView's syminfo data.
- **Risk-Free Rate**: Fetched from the 1-year US Treasury yield (symbol: TVC:US01Y). Defaults to 4% if unavailable.
- **Dividend Yield**: Uses trailing twelve-month (TTM) dividends per share (DPS) from financial data, divided by current price. Defaults to 0% if unavailable.
- **Volatility**: Computed as annualized historical volatility based on 252 trading days of daily log returns. Falls back to a 20-day period if insufficient data, or defaults to 30% if still unavailable.
- **Probability Calculation**: Employs the barrier hitting probability formula under GBM:
- Drift (μ) = risk-free rate - dividend yield - (volatility² / 2)
- The formula for probability P of hitting target H from current price S₀ over time T is:
P = Φ(d₊) + (H / S₀)^p ⋅ Φ(d₋) for H > S₀ (or adjusted for H < S₀)
Where l = ln(max(H, S₀)/min(H, S₀)), ν = drift, p = -2ν / σ², d₊ = (-l + νT) / (σ√T), d₋ = (-l - νT) / (σ√T), and Φ is the standard normal CDF (approximated using a polynomial method for accuracy).
- **Output Display**: A table in the top-right corner shows each target type, its value, and the estimated probability (as a percentage). "N/A" appears if data is unavailable or calculations cannot proceed (e.g., zero volatility).
### Assumptions and Limitations:
- Assumes constant volatility and drift, no transaction costs, and continuous trading (real markets may deviate due to jumps, news events, or changing conditions).
- Probabilities are model-based estimates and not guarantees; they represent the likelihood under risk-neutral measure.
- Best suited for stocks with available analyst targets and historical data; may default to assumptions for less-liquid symbols.
- No user inputs required—fully automated using TradingView's data sources.
This script is provided under the Mozilla Public License 2.0. For educational and informational purposes only; not financial advice. Test on your charts and consider backtesting for validation.
### Key Features:
- **Analyst Targets**: Automatically pulls the high, average, and low one-year price targets from TradingView's syminfo data.
- **Risk-Free Rate**: Fetched from the 1-year US Treasury yield (symbol: TVC:US01Y). Defaults to 4% if unavailable.
- **Dividend Yield**: Uses trailing twelve-month (TTM) dividends per share (DPS) from financial data, divided by current price. Defaults to 0% if unavailable.
- **Volatility**: Computed as annualized historical volatility based on 252 trading days of daily log returns. Falls back to a 20-day period if insufficient data, or defaults to 30% if still unavailable.
- **Probability Calculation**: Employs the barrier hitting probability formula under GBM:
- Drift (μ) = risk-free rate - dividend yield - (volatility² / 2)
- The formula for probability P of hitting target H from current price S₀ over time T is:
P = Φ(d₊) + (H / S₀)^p ⋅ Φ(d₋) for H > S₀ (or adjusted for H < S₀)
Where l = ln(max(H, S₀)/min(H, S₀)), ν = drift, p = -2ν / σ², d₊ = (-l + νT) / (σ√T), d₋ = (-l - νT) / (σ√T), and Φ is the standard normal CDF (approximated using a polynomial method for accuracy).
- **Output Display**: A table in the top-right corner shows each target type, its value, and the estimated probability (as a percentage). "N/A" appears if data is unavailable or calculations cannot proceed (e.g., zero volatility).
### Assumptions and Limitations:
- Assumes constant volatility and drift, no transaction costs, and continuous trading (real markets may deviate due to jumps, news events, or changing conditions).
- Probabilities are model-based estimates and not guarantees; they represent the likelihood under risk-neutral measure.
- Best suited for stocks with available analyst targets and historical data; may default to assumptions for less-liquid symbols.
- No user inputs required—fully automated using TradingView's data sources.
This script is provided under the Mozilla Public License 2.0. For educational and informational purposes only; not financial advice. Test on your charts and consider backtesting for validation.
Note di rilascio
### OverviewThis Pine Script v5 indicator, titled **Analyst Targets Probability (ATP)**, overlays on TradingView charts to assess the likelihood of a stock reaching analyst price targets (or fallback historical highs/lows) within a 1-year horizon. It assumes stock prices follow a geometric Brownian motion (GBM) model and incorporates risk-adjusted metrics like alpha, Sharpe ratio, and Sortino ratio. The script dynamically fetches external data (e.g., Treasury yields, dividends) and computes a custom beta relative to SPY. It's designed for stocks but handles non-stocks by defaulting values.
Key updates in this version include:
- **Dynamic market risk premium (MRP)**: Now derived from historical S&P 500 returns minus the risk-free rate, rather than a static 6% assumption.
- **Improved fallbacks**: Enhanced handling of missing data (e.g., volatility defaults to 30%, downside deviation to half of volatility).
- **Historical performance integration**: Adds a "Historical 1Y" row in the table and uses past returns for MRP and alpha calculations.
- **Visual signals**: New conditional labels (green/red arrows) for undervalued/overvalued signals based on stock risk premium vs. MRP, plus a dynamic red target line at 125% of current close.
- **Refined probability model**: Clamps outputs to [0,1] for robustness; uses an approximation for the normal CDF.
- **Table expansion**: Now 35 rows (though only ~8 used), with added rows for MRP, stock risk premium, and drift.
The script runs on the last bar for efficiency and supports dynamic requests for real-time data.
### Key Inputs and Parameters
- **Market Proxy**: SPY (S&P 500 ETF) for beta calculation.
- **Lookback Periods**:
- Beta: 252 days (1 trading year).
- Volatility/Downside Deviation: 252 days (fallback to 20 days).
- **Time Horizon (T)**: Fixed at 1 year.
- **Risk-Free Rate (r)**: 1-year US Treasury yield (TVC:US01Y), default 4%.
- **Dividend Yield (q)**: Trailing twelve months (TTM) dividends per share from financial data, default 0%.
- **Volatility (sig)**: Annualized historical std. dev. of log returns, default 30%.
- **Downside Deviation**: Semi-deviation of negative log returns (annualized), default sig/2.
- **Targets**:
- High/Low/Average: From `syminfo.target_price_*` (analyst consensus); falls back to 252-day highest/lowest and midpoint.
### Core Calculations
1. **Beta (β)**:
- Computed manually via covariance of log returns (stock vs. SPY) divided by market variance over 252 days.
- Defaults to 1.0 if invalid/NA.
- Formula: β = Cov(R_stock, R_market) / Var(R_market).
2. **Historical Returns and MRP**:
- Stock return: (Current price - Price 252 days ago + TTM dividends) / Past price.
- Market return: Similar for SPY, plus average S&P dividend yield (~1.2% default).
- MRP = Historical market return - Average risk-free rate (over 252 days).
- Stock risk premium = β × MRP.
- Required return = r + Stock risk premium.
- Historical alpha = Historical stock return - Required return.
- Historical Sharpe/Sortino: Excess return (historical return - r) divided by sig/downside deviation.
3. **Drift (ν)**:
- ν = r - q - (sig² / 2) (annualized GBM drift).
4. **Probability of Hitting Target (p_hit)**:
- Uses a closed-form GBM barrier hitting probability for a constant barrier.
- For target > S0 (upper barrier): p = N(d+) + (target/S0)^{2ν/σ²} × N(d-), where:
- d+ = [-ln(target/S0) + νT] / (σ√T)
- d- = [-ln(target/S0) - νT] / (σ√T)
- N(·) ≈ Normal CDF via Hart's approximation (polynomial tail expansion).
- Symmetric for lower barrier (target < S0).
- Clamped to [0, 100%]; NA if inputs invalid.
5. **Risk-Adjusted Metrics (for each target)**:
- Expected return = (Target - S0)/S0 + q.
- Alpha = Expected return - (r + β × MRP).
- Sharpe = (Expected return - r) / sig.
- Sortino = (Expected return - r) / Downside deviation.
### Outputs and Display
- **Table (Top-Right Corner)**: A 6-column table updates on the last bar:
| Target Type | Value | Prob. of Hitting (1Y) | Alpha | Sharpe | Sortino |
|-------------------|-----------|-----------------------|-----------|----------|----------|
| **High** | [Price] | [XX.X%] | [XX.X%] | [X.XX] | [X.XX] |
| **Average** | [Price] | [XX.X%] | [XX.X%] | [X.XX] | [X.XX] |
| **Low** | [Price] | [XX.X%] | [XX.X%] | [X.XX] | [X.XX] |
| **Historical 1Y**| [XX.X%] | N/A | [XX.X%] | [X.XX] | [X.XX] |
| **Market Risk Prem/Disc** | [XX.X%] | - | - | - | - |
| **Stock Risk Prem/Disc** | [X.XX%] | - | - | - | - |
| **Drift** | [X.XX%] | - | - | - | - |
- "N/A" for missing data.
- Headers in gray; values in white/black.
- If no analyst data, labels adjust (e.g., "1 Year HL[mid]" header, "Mid Point" row).
- **Visual Signals**:
- **Green Up Arrow**: If stock risk premium > MRP and MRP < 0% (potential undervaluation in bearish market).
- **Red Up Arrow**: If stock risk premium > MRP > 0% (wait, condition seems inverted—likely a bug; flags overvaluation?).
- Arrows placed at current low on the last bar.
- **Red Target Line**: Horizontal line extending right from current close × 1.25 (as a visual upside reference); updates dynamically, deleting prior instance.
### Usage Notes
- **Best For**: Stocks with analyst coverage; works on any timeframe but fetches daily data for consistency.
- **Limitations**: Relies on TradingView's `syminfo` and `request.*` functions—may lag on illiquid symbols. Probability assumes constant volatility/drift (no jumps). Visual labels have conditional logic that might need tweaking for accuracy.
- **Customization Ideas**: Adjust `T` for different horizons; add alerts on prob_high > 70%. Test on symbols like AAPL for analyst targets.
This script provides a comprehensive, probabilistic view of upside/downside potential, blending fundamental targets with quantitative risk metrics.
Note di rilascio
Updated the script to ensure compatibility across multiple timeframes without runtime errors. Key changes include:Refactored beta and downside deviation calculations into dedicated functions (calc_beta() and calc_down_dev()), which are now requested via request.security on the daily ("D") timeframe to handle data consistently regardless of the chart's timeframe.
Adjusted analyst target fallbacks (highest/lowest over 252 bars) to use request.security on "D" for accurate daily-based values.
Updated historical performance metrics (past_price, past_market, mean_sp_div, mean_r) to fetch via request.security on appropriate timeframes ("D" or "1M") for reliability.
Fixed minor issues like undefined variables (e.g., replaced undefined 'time' and 'last_bar_time' with proper bar_index and time references in chart.point.new and line.new calls).
Ensured fallback logic for NA values prevents errors, with defaults like 30% volatility or half volatility for downside deviation.
This update resolves issues where lower timeframes (e.g., hourly) caused NA propagation or insufficient bars in loops, making the indicator robust for any chart setup while preserving the original logic for probability calculations, CAPM metrics (alpha, Sharpe, Sortino), and table display of analyst targets.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.