本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("[DAOL] P/E Band V2 - Valuation Context", shorttitle="DAOL PE V2", overlay=false, precision=2, max_bars_back=1200)
// Baseline concept: user-supplied [DAOL] P/E Band V1 by DAOL.
// V2 implementation written for this task; no Community script code copied.
// Standard P/E: price / trailing EPS. Historical quantiles are descriptive.
// Financial IDs/timing: https://www.tradingview.com/pine-script-docs/concepts/other-timeframes-and-data/
// https://www.tradingview.com/support/solutions/43000564727-what-financial-data-is-available-in-pine/
// log(PE1/PE0) = log(P1/P0) - log(EPS1/EPS0), for positive inputs.
// Financial series are NOT guaranteed point-in-time earnings-announcement data.
// This is not a backtest or a fair-value/expected-return model.
int sampleLength = input.int(36, "Completed monthly P/E samples", minval=12, maxval=120, group="Historical reference")
float innerPct = input.float(25.0, "Inner lower percentile", minval=15.0, maxval=45.0, step=5.0, group="Historical reference")
float outerPct = input.float(10.0, "Outer lower percentile", minval=1.0, maxval=20.0, step=1.0, group="Historical reference")
string epsType = input.string("Basic", "TTM EPS type", options=["Basic", "Diluted"], group="Fundamentals")
int driverLength = input.int(21, "P/E driver comparison (trading bars)", minval=5, maxval=252, group="P/E drivers")
float epsDecline = input.float(5.0, "EPS weakening threshold (%)", minval=0.0, maxval=50.0, step=1.0, group="P/E drivers")
int confirmation = input.int(2, "Consecutive closed bars for state", minval=1, maxval=10, group="Alerts")
bool showFixedEPS = input.bool(false, "Show P/E with comparison-date EPS held fixed", group="Display")
bool showDashboard = input.bool(true, "Show dashboard", group="Display")
if not timeframe.isdaily or timeframe.multiplier != 1
runtime.error("Use a standard 1-day chart. Monthly samples and driver periods in this version are defined on daily bars.")
if outerPct >= innerPct
runtime.error("Outer lower percentile must be smaller than inner lower percentile.")
string financialID = epsType == "Basic" ? "EARNINGS_PER_SHARE" : "EARNINGS_PER_SHARE_DILUTED"
float eps = request.financial(syminfo.tickerid, financialID, "TTM", gaps=barmerge.gaps_off, ignore_invalid_symbol=true, currency=syminfo.currency)
bool validPE = not na(eps) and eps > 0.0 and close > 0.0
float pe = validPE ? close / eps : na
// One observation at each preceding month's final chart close. The previous
// bar is sampled when the new month begins, and committed only at bar close.
// Reset at invalid month-end rather than silently selecting only profitable months.
bool newMonth = timeframe.change("1M")
var array<float> samples = array.new_float(0)
var float medianPE = na
var float lowerInner = na
var float upperInner = na
var float lowerOuter = na
var float upperOuter = na
var int sampleTime = na
var float rankPct = na
f_quantile(array<float> sorted, float percentile) =>
float index = (array.size(sorted) - 1) * percentile / 100.0
int lo = int(math.floor(index))
int hi = int(math.ceil(index))
float fraction = index - lo
array.get(sorted, lo) * (1.0 - fraction) + array.get(sorted, hi) * fraction
if barstate.isconfirmed and newMonth and bar_index > 0
if not na(pe[1]) and pe[1] > 0.0
array.push(samples, pe[1])
if array.size(samples) > sampleLength
array.shift(samples)
sampleTime := time[1]
else
array.clear(samples)
sampleTime := na
if array.size(samples) == sampleLength
array<float> ordered = array.copy(samples)
array.sort(ordered, order.ascending)
medianPE := f_quantile(ordered, 50.0)
lowerInner := f_quantile(ordered, innerPct)
upperInner := f_quantile(ordered, 100.0 - innerPct)
lowerOuter := f_quantile(ordered, outerPct)
upperOuter := f_quantile(ordered, 100.0 - outerPct)
else
medianPE := na
lowerInner := na
upperInner := na
lowerOuter := na
upperOuter := na
bool driverValid = validPE and not na(eps[driverLength]) and eps[driverLength] > 0.0 and close[driverLength] > 0.0
float epsChangePct = driverValid ? 100.0 * (eps / eps[driverLength] - 1.0) : na
float priceDriver = driverValid ? 100.0 * math.log(close / close[driverLength]) : na
float earningsDriver = driverValid ? -100.0 * math.log(eps / eps[driverLength]) : na
float totalDriver = driverValid ? priceDriver + earningsDriver : na
float fixedEPSPE = driverValid ? close / eps[driverLength] : na
bool weakEPS = driverValid and epsChangePct < -epsDecline
// State: -3 low historical PE / drivers unavailable, -2 low / EPS weaker,
// -1 low / no EPS decline beyond threshold, 0 middle, 1 high historical PE.
// 'No weakening' is NOT earnings-quality verification.
bool bandReady = validPE and not na(medianPE)
int rawState = 0
if bandReady
if pe < lowerOuter
rawState := not driverValid ? -3 : weakEPS ? -2 : -1
else if pe > upperOuter
rawState := 1
f_name(int s) =>
s == -3 ? "Low PE / EPS context unavailable" : s == -2 ? "Low PE / EPS weaker" : s == -1 ? "Low PE / EPS not weakening" : s == 1 ? "High historical PE" : "Within outer band"
f_color(int s) =>
s == -3 ? color.gray : s == -2 ? color.orange : s == -1 ? color.aqua : s == 1 ? color.red : color.silver
var float closedPE = na
var float closedFixed = na
var float closedPriceDriver = na
var float closedEarningsDriver = na
var float closedTotalDriver = na
var float closedEPSChange = na
var float closedEPS = na
var bool closedBandReady = false
var int closedRaw = 0
var int candidate = 0
var int streak = 0
var int confirmedState = 0
var bool initialized = false
bool changed = false
if barstate.isconfirmed
closedPE := pe
closedFixed := fixedEPSPE
closedPriceDriver := priceDriver
closedEarningsDriver := earningsDriver
closedTotalDriver := totalDriver
closedEPSChange := epsChangePct
closedEPS := eps
closedBandReady := bandReady
closedRaw := rawState
rankPct := na
if bandReady
float rank = 0.0
for i = 0 to array.size(samples) - 1
float observation = array.get(samples, i)
rank += observation < pe ? 1.0 : observation == pe ? 0.5 : 0.0
rankPct := 100.0 * rank / array.size(samples)
// Reference changes reset confirmation; no synthetic transition alert
// caused solely by replacing the monthly baseline.
if newMonth
streak := 0
initialized := false
if streak == 0 or rawState != candidate
candidate := rawState
streak := 1
else
streak := math.min(streak + 1, confirmation)
if streak >= confirmation
changed := initialized and candidate != confirmedState
confirmedState := candidate
initialized := true
else
streak := 0
initialized := false
pPE = plot(closedPE, "P/E (positive TTM EPS only)", color=closedBandReady ? f_color(closedRaw) : color.gray, linewidth=2)
plot(medianPE, "Monthly sample median", color=color.white, linewidth=2, style=plot.style_stepline)
pLI = plot(lowerInner, "Inner lower percentile", color=color.new(color.teal, 35), style=plot.style_stepline)
pUI = plot(upperInner, "Inner upper percentile", color=color.new(color.orange, 35), style=plot.style_stepline)
pLO = plot(lowerOuter, "Outer lower percentile", color=color.teal, style=plot.style_stepline)
pUO = plot(upperOuter, "Outer upper percentile", color=color.red, style=plot.style_stepline)
fill(pLI, pUI, color=color.new(color.gray, 93), title="Inner historical band")
fill(pLO, pLI, color=color.new(color.teal, 90), title="Lower historical zone")
fill(pUI, pUO, color=color.new(color.orange, 90), title="Upper historical zone")
plot(showFixedEPS ? closedFixed : na, "Counterfactual P/E: old EPS held fixed", color=color.purple, linewidth=1)
plot(rankPct, "Historical rank (%)", display=display.data_window)
plot(closedPriceDriver, "Price contribution (100 x log ratio)", display=display.data_window)
plot(closedEarningsDriver, "EPS contribution (negative 100 x log ratio)", display=display.data_window)
plot(closedTotalDriver, "Total P/E change (100 x log ratio)", display=display.data_window)
plot(closedEPS, "TTM EPS in price currency", display=display.data_window)
var table dashboard = table.new(position.top_right, 2, 8, border_width=1)
if barstate.islast and showDashboard
color panel = color.rgb(35, 35, 35)
string dataStatus = na(closedEPS) ? "No TTM EPS" : closedEPS <= 0.0 ? "EPS <= 0: PE not meaningful" : not closedBandReady ? "Building monthly reference" : "Historical valuation context"
table.cell(dashboard, 0, 0, "DAOL P/E Band V2", text_color=color.white, bgcolor=color.rgb(35, 45, 65))
table.cell(dashboard, 1, 0, "1D / financial series", text_color=color.white, bgcolor=color.rgb(35, 45, 65))
table.cell(dashboard, 0, 1, "Data", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 1, dataStatus, text_color=color.white, bgcolor=panel)
table.cell(dashboard, 0, 2, "PE / TTM EPS", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 2, na(closedPE) ? "N/A" : str.tostring(closedPE, "#.00") + " / " + str.tostring(closedEPS, "#.000") + " " + syminfo.currency, text_color=color.white, bgcolor=panel)
table.cell(dashboard, 0, 3, "Monthly samples / rank", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 3, str.tostring(array.size(samples)) + "/" + str.tostring(sampleLength) + " / " + (na(rankPct) ? "N/A" : str.tostring(rankPct, "#.0") + "%"), text_color=color.white, bgcolor=panel)
table.cell(dashboard, 0, 4, "EPS change (" + str.tostring(driverLength) + " bars)", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 4, na(closedEPSChange) ? "N/A" : str.tostring(closedEPSChange, "#.1") + "%", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 0, 5, "Log drivers: price / EPS", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 5, na(closedTotalDriver) ? "N/A" : str.tostring(closedPriceDriver, "#.2") + " / " + str.tostring(closedEarningsDriver, "#.2"), text_color=color.white, bgcolor=panel)
table.cell(dashboard, 0, 6, "Latest / confirmed", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 6, closedBandReady ? f_name(closedRaw) + " / " + (initialized ? f_name(confirmedState) : "Waiting") : "N/A", text_color=f_color(closedRaw), bgcolor=panel)
table.cell(dashboard, 0, 7, "Last monthly sample", text_color=color.white, bgcolor=panel)
table.cell(dashboard, 1, 7, na(sampleTime) ? "N/A" : str.format_time(sampleTime, "yyyy-MM-dd", syminfo.timezone), text_color=color.white, bgcolor=panel)
alertcondition(changed and confirmedState == -1, "DAOL: Low PE without EPS weakening", "DAOL PE V2: below outer historical band; EPS decline does not exceed selected threshold. Not a buy signal. {{ticker}}")
alertcondition(changed and confirmedState == -2, "DAOL: Low PE with EPS weakening", "DAOL PE V2: below outer historical band with weaker TTM EPS. Review earnings context. {{ticker}}")
alertcondition(changed and confirmedState == 1, "DAOL: High historical PE", "DAOL PE V2: above outer historical band. Not a sell signal. {{ticker}}")
alertcondition(changed and confirmedState == 0, "DAOL: Back within outer band", "DAOL PE V2: confirmed return within outer historical band. {{ticker}}")
alertcondition(changed, "DAOL: Any confirmed valuation-state change", "DAOL PE V2: historical valuation state changed. {{ticker}}")
// Historical rank uses a mid-rank tie convention; not probability of success.
// Log drivers are additive contributions, not ordinary percentage returns.
// Monthly band replacement initializes silently after confirmation.
// Nonpositive EPS suppresses P/E; invalid month-end resets sample history.
// Positive but near-zero EPS can still yield enormous PE and rank distortion.
// Financial data can be revised and aligned to fiscal periods rather than
// publication dates. No guarantee of point-in-time or non-repainting history.
// Splits, special items, security currency/share basis need user verification.
// External numerical tests only; TradingView compilation pending.