OPEN-SOURCE SCRIPT
Atualizado 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.
Notas de Lançamento
### 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.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.