CT - Maybe the Price Is Wrong

ComplexityTrading · study · 1989 行 · 点赞 11 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® is open-source and subject to the terms of the Mozilla Public License 2.0.
 
// You may use, copy, modify, and distribute this script in accordance with the license.
 
// Attribution required. ⚠️ Any derivative works must also remain open-source.
 
// © 2026 ComplexityTrading
 
//@version=6
 
indicator("CT — Maybe the Price Is Wrong™",
     shorttitle="CT Maybe Price Is Wrong",
     overlay=false,
     precision=2,
     dynamic_requests=true,
     max_bars_back=1200)
 
// =====================================================
// CT — MAYBE THE PRICE IS WRONG™ v6
//
// UNIVERSAL TARGET vs BENCHMARK
//
// MODE 1: Direct ETF / Index comparison
// MODE 2: Editable weighted constituent basket
//
// Exclusions apply only to constituent basket mode.
//
// No BUY / SELL signals.
// Large diamonds = new statistical extreme episodes.
//
// Forward outcomes use completed historical bars.
// Statistical discount != intrinsic undervaluation.
//
// IMPORTANT:
// Default constituent weights are illustrative,
// frozen reference weights from the earlier
// GOOGL / XLK proxy experiment.
// They are not historical point-in-time holdings.
// =====================================================
 // ============================================================
// ============================================================
// PUBLIC RELEASE NOTICE - OPEN-SOURCE RESEARCH, NOT VALIDATED ALPHA
// PUBLIC RELEASE / VALIDATION STATUS (2026-11-05):
// This is a transparent exploratory research implementation.
// Source-code inspection does NOT constitute independent replication.
// Historical EVENT / BASE / EDGE estimates have not been verified
// against independently sourced point-in-time constituent data.
// No statistical significance, predictive accuracy or executable
// trading advantage is claimed. Publication is for scrutiny and
// hypothesis generation, not certification of empirical results.
//
// BENCHMARK LIMIT: The default 10-stock selected tech proxy is NOT
// actual XLK minus its semiconductor holdings. A synthetic basket
// uses frozen user-selected symbols and weights across history.
// Its displayed coverage is only share of configured input weights.
// Compare Direct ETF and synthetic modes as distinct benchmarks.
//
// ============================================================
// This measures unusual RELATIVE PRICE performance, NOT
// intrinsic undervaluation, a fair-value discount, or a BUY.
// Historical EVENT / BASE / EDGE results are IN-SAMPLE,
// descriptive associations; they have NOT been independently
// replicated or validated as a predictive trading advantage.
// Event cooldown reduces clustering but does NOT establish
// statistical independence. BASE includes all eligible dates,
// including event dates, and forward windows can overlap.
// Synthetic baskets use CURRENT USER-ENTERED membership and
// fixed weights across history, NOT point-in-time ETF holdings.
// Look-ahead/survivorship bias and benchmark tracking error may
// therefore materially alter historical extremes and results.
// Configuration coverage is NOT actual fund coverage.
// Distribution warnings are heuristics, not stationarity tests.
// Read the complete methodology, limitations and disclaimer.
// ============================================================
 // CT — MAYBE THE PRICE IS WRONG™
 // THEORY, METHODOLOGY & USER GUIDE
 // ============================================================
 //
 // PURPOSE
// PUBLICATION STATUS: Open-source experimental research release.
// This measures relative-price extremity, not fair value.
// Synthetic results are not point-in-time ETF reconstructions.
// Forward EDGE is in-sample and not independently validated.
 //
 // CT — Maybe the Price Is Wrong™ is a configurable statistical
 // instrument designed to identify when an individual security
 // has experienced unusually large relative underperformance
 // against a selected benchmark.
 //
 // The benchmark may be an ETF, an index, or a custom basket
 // of stocks with selected constituents excluded.
 //
 // The underlying question is:
 //
 // "Has this security become unusually depressed relative to
 //  the market segment against which we wish to measure it?"
 //
 // This is a relative-dislocation instrument, not a conventional
 // trading signal generator or fundamental valuation model.
 //
 // Its purpose is to identify statistical extremes, measure
 // their historical frequency, and examine what subsequently
 // happened to relative performance.
 //
 //
 // ============================================================
 // 1. THE UNDERLYING THEORY
 // ============================================================
 //
 // Securities do not exist in isolation.
 //
 // Their prices reflect company-specific developments alongside
 // sector conditions, market-wide liquidity, economic expectations,
 // capital allocation, institutional positioning, and changes
 // in investors' willingness to bear risk.
 //
 // Consequently, a stock falling 20% does not automatically
 // constitute an unusual or attractive discount.
 //
 // If its relevant sector has fallen 30%, that stock has
 // actually outperformed its comparison group.
 //
 // Conversely, a stock that has remained unchanged while its
 // peers have appreciated 25% has experienced substantial
 // relative underperformance despite having suffered no
 // absolute price decline.
 //
 // Relative performance therefore provides a different
 // perspective from observing the stock price alone.
 //
 // However, relative underperformance is not synonymous with
 // intrinsic undervaluation.
 //
 // A sustained discount may represent:
 //
 // A. Temporary company-specific selling pressure.
 //
 // B. Sector rotation or changes in capital allocation.
 //
 // C. A difference in business fundamentals or expectations.
 //
 // D. A permanent repricing of the security's prospects.
 //
 // E. An unusually large but potentially reversible
 //    statistical dislocation.
 //
 // The indicator cannot determine which explanation is correct.
 //
 // Instead, it quantifies the extremity of the observed
 // relative movement and reports historical outcomes.
 //
 //
 // ============================================================
 // 2. SELECTING THE STOCK TO ASSESS
 // ============================================================
 //
 // In "Stock to assess", select the target security.
 //
 // Examples:
 //
 // GOOGL  - Alphabet
 // AAPL   - Apple
 // MSFT   - Microsoft
 // AMZN   - Amazon
 // NVDA   - NVIDIA
 // JPM    - JPMorgan Chase
 //
 // Any TradingView-supported symbol with sufficient valid
 // historical data may be used.
 //
 // The target is independent of the chart symbol.
 //
 // For clarity, displaying the target's price on the main
 // chart is recommended, although it is not required.
 //
 //
 // ============================================================
 // 3. SELECTING THE BENCHMARK
 // ============================================================
 //
 // Two benchmark modes are available.
 //
 // MODE A: DIRECT ETF
 //
 // The target is compared with the selected benchmark's
 // actual reported price series.
 //
 // Examples:
 //
 // XLK - Technology sector
 // QQQ - Nasdaq-100 exposure
 // SPY - S&P 500 exposure
 // XLC - Communication Services
 // XLF - Financial sector
 // XLE - Energy sector
 //
 // In this mode, no constituents are removed.
 //
 // The comparison measures relative performance against
 // the selected benchmark as it exists.
 //
 // This is the simplest and most direct configuration.
 //
 //
 // MODE B: CONSTITUENT BASKET
 //
 // The benchmark is constructed from individual stocks.
 //
 // Each constituent has:
 //
 // - A selectable TradingView symbol.
 // - An assigned numerical weight.
 // - An exclusion checkbox.
 //
 // The script calculates a composite daily return from
 // the included securities.
 //
 // This permits comparisons against modified baskets,
 // including sector benchmarks with selected constituents
 // removed.
 //
 // IMPORTANT:
 //
 // Selecting XLK, QQQ, SPY, or another ETF in the direct
 // benchmark field does not automatically import its holdings
 // into the constituent basket.
 //
 // Custom basket symbols and weights must be configured
 // separately.
 //
 // The script supports 12 editable constituent slots.
 //
 //
 // ============================================================
 // 4. EXCLUDING STOCKS FROM THE BENCHMARK
 // ============================================================
 //
 // Why exclude constituents?
 //
 // A stock may be compared against a sector dominated by
 // several unusually large or volatile companies.
 //
 // Those companies can disproportionately influence
 // benchmark performance and obscure the relationship
 // being investigated.
 //
 // Excluding selected constituents allows the researcher
 // to examine a more specific comparison universe.
 //
 // EXAMPLE:
 //
 // Assess GOOGL against non-semiconductor technology.
 //
 // A suitable comparison basket would contain selected
 // technology stocks but exclude semiconductor companies.
 //
 // This removes direct semiconductor constituent returns
 // from the constructed benchmark.
 //
 // It does not remove indirect AI, semiconductor, or
 // technology-cycle exposure from the remaining companies.
 //
 // To exclude a stock:
 //
 // 1. Open the constituent settings.
 //
 // 2. Locate the stock you wish to remove.
 //
 // 3. Enable its "Exclude" checkbox.
 //
 // 4. The stock is removed from the basket calculation.
 //
 // 5. The remaining constituents are automatically
 //    renormalized.
 //
 // The "Automatically exclude target" option prevents
 // the target security from contributing to its own
 // constituent benchmark, provided the symbol matches.
 //
 // Without this exclusion, part of the target's return
 // may also appear in the comparison basket.
 //
 //
 // ============================================================
 // 5. CONSTRUCTING THE SYNTHETIC BENCHMARK
 // ============================================================
 //
 // Two weighting methods are available.
 //
 // PROPORTIONAL WEIGHTING
 //
 // Each included constituent contributes according to its
 // assigned weight.
 //
 // The basket return is calculated as:
 //
 // BasketReturn =
 //     SUM(Weight_i \\\\* Return_i) / SUM(Weight_i)
 //
 // Only included constituents contribute to these sums.
 //
 // EXAMPLE:
 //
 // Stock A: 50% reference weight
 // Stock B: 30% reference weight
 // Stock C: 20% reference weight
 //
 // If Stock A is excluded, the remaining weights become:
 //
 // Stock B: 60%
 // Stock C: 40%
 //
 // The original weights do not need to total 100.
 //
 // They are normalized automatically.
 //
 //
 // EQUAL WEIGHTING
 //
 // Every included constituent receives the same weight,
 // irrespective of the numerical reference weights.
 //
 // Equal-weight baskets answer a different question
 // from capitalization-weighted sector benchmarks.
 //
 // Neither weighting method is universally superior.
 //
 // Proportional weighting better approximates a reference
 // portfolio when its supplied weights are accurate.
 //
 // Equal weighting reduces concentration in the largest
 // constituents but changes the economic exposure.
 //
 // Both methods construct a daily-rebalanced basket.
 //
 // They do not account for transaction costs, turnover,
 // financing costs, or implementation constraints.
 //
 //
 // ============================================================
 // 6. MEASURING RELATIVE PERFORMANCE
 // ============================================================
 //
 // The model compares the target's daily total price factor
 // with the benchmark's daily total price factor.
 //
 // A daily price factor equals:
 //
 // 1 + daily return
 //
 // The relative logarithmic return is:
 //
 // RelativeLogReturn =
 //     ln(1 + TargetReturn)
 //     - ln(1 + BenchmarkReturn)
 //
 // These differences are accumulated across time.
 //
 // Over a selected horizon, the model measures the
 // cumulative relative logarithmic return.
 //
 // The default horizon is 63 trading days,
 // approximately one trading quarter.
 //
 // The corresponding compounded relative return is:
 //
 // RelativeReturn =
 //     EXP(RelativeLogReturn) - 1
 //
 // EXAMPLE:
 //
 // Target cumulative factor:     0.85
 // Benchmark cumulative factor:  1.10
 //
 // Relative performance:
 //
 // 0.85 / 1.10 - 1 = -22.73%
 //
 // This means the target's cumulative price factor is
 // 22.73% below the benchmark's factor over the period.
 //
 // It does not mean the stock is intrinsically
 // undervalued by 22.73%.
 //
 // The calculation uses price returns, not necessarily
 // dividend-reinvested total returns.
 //
 //
 // ============================================================
 // 7. THE STATISTICAL Z-SCORE
 // ============================================================
 //
 // The indicator compares the latest relative return
 // against its own rolling historical distribution.
 //
 // Default statistical reference: 252 trading days.
 //
 // The Z-score is:
 //
 // Z = (CurrentRelativeReturn - HistoricalMean)
 //     / HistoricalStandardDeviation
 //
 // The modeled variable is the rolling relative log return.
 //
 // INTERPRETATION:
 //
 // Z =  0.0
 // Current relative performance is at its rolling mean.
 //
 // Z = -1.0
 // Current relative performance is one historical standard
 // deviation below its rolling mean.
 //
 // Z = -2.0
 // Current relative performance is two historical standard
 // deviations below its rolling mean.
 //
 // Z = +1.0
 // Current relative performance is one historical standard
 // deviation above its rolling mean.
 //
 // Lower Z-scores indicate increasingly unusual relative
 // weakness against the selected benchmark.
 //
 // Importantly, the Z-score is not a valuation percentage.
 //
 // It measures statistical distance from a historical mean,
 // not distance from fundamental fair value.
 //
 // The model does not assume that market returns are
 // independent or normally distributed.
 //
 // Overlapping rolling return observations are strongly
 // dependent, and the historical distribution can change
 // across economic and market regimes.
 //
 // Therefore, a Z-score of -2 should not automatically
 // be interpreted as a precise Gaussian tail probability.
 //
 //
 // ============================================================
 // 8. HISTORICAL PERCENTILE
 // ============================================================
 //
 // The percentile measures where the current relative
 // return ranks within the rolling reference sample.
 //
 // EXAMPLE:
 //
 // Percentile = 5%
 //
 // The current relative return is near the bottom of
 // the historical observations in the reference window.
 //
 // Percentile = 50%
 //
 // The current relative return is near the middle of
 // the reference distribution.
 //
 // Percentile = 95%
 //
 // The current relative return is unusually strong.
 //
 // Percentiles complement Z-scores because they measure
 // empirical rank rather than standardized distance.
 //
 // A very low percentile combined with a strongly
 // negative Z-score reinforces the conclusion that
 // relative performance is historically unusual.
 //
 // Neither observation proves mispricing.
 //
 //
 // ============================================================
 // 9. DISCOUNT CLASSIFICATIONS
 // ============================================================
 //
 // NORMAL RANGE
 //
 // Relative performance is not sufficiently depressed
 // to meet the configured discount threshold.
 //
 // DISCOUNT
 //
 // Z-score <= -1.0 by default.
 //
 // The target has experienced statistically unusual
 // relative underperformance.
 //
 // EXTREME DISCOUNT
 //
 // Z-score <= -2.0 by default.
 //
 // The target's relative underperformance has reached
 // the configured extreme threshold.
 //
 // RELATIVE PREMIUM
 //
 // Z-score >= +1.0 by default.
 //
 // The target has experienced unusually strong relative
 // performance against the selected benchmark.
 //
 // These classifications are statistical descriptions.
 //
 // They are not BUY, SELL, LONG, or SHORT instructions.
 //
 // Thresholds are configurable and should be evaluated
 // against historical observations.
 //
 //
 // ============================================================
 // 10. UNDERSTANDING THE CHART
 // ============================================================
 //
 // The main plotted line is the Relative Discount Z-score.
 //
 // WHITE LINE
 //
 // Relative performance is within the normal range.
 //
 // ORANGE LINE
 //
 // Relative performance is in discount territory.
 //
 // RED LINE
 //
 // Relative performance is in extreme-discount territory.
 //
 // CYAN LINE
 //
 // Relative performance is unusually strong.
 //
 // HORIZONTAL GREY LINE AT ZERO
 //
 // The rolling statistical center.
 //
 // HORIZONTAL ORANGE LINE AT -1
 //
 // The default discount threshold.
 //
 // HORIZONTAL RED LINE AT -2
 //
 // The default extreme-discount threshold.
 //
 //
 // ============================================================
 // 11. LARGE RED DIAMONDS
 // ============================================================
 //
 // Large red diamonds identify the first confirmed daily
 // observation of a new extreme-discount episode.
 //
 // The event occurs when:
 //
 // 1. The Z-score enters extreme-discount territory.
 //
 // 2. The preceding observation was not in that territory.
 //
 // 3. The current daily bar has closed.
 //
 // EXAMPLE:
 //
 // Yesterday: Z = -1.85
 // Today:     Z = -2.07
 //
 // A new extreme-discount diamond appears.
 //
 // If the Z-score remains below -2 for ten days,
 // the indicator does not place ten diamonds.
 //
 // The continuous interval represents one episode.
 //
 // If the Z-score rises above -2 and later falls below
 // it again, a new diamond may appear.
 //
 // This rule can generate multiple nearby episodes.
 //
 // Diamonds are observational event markers.
 //
 // They do not indicate that the price has bottomed,
 // that a rebound is imminent, or that the stock
 // should immediately be purchased.
 //
 //
 //
 // V6: RAW EPISODES VERSUS SEPARATED RESEARCH EVENTS
 //
 // The large red diamonds mark ALL newly-entered extreme
 // episodes on confirmed daily closes. They are not filtered
 // by the research cooldown. A separate study-event series
 // accepts a raw event only when the configured minimum
 // number of chart bars has elapsed since the last accepted
 // event. Default cooldown: 60 daily bars.
 //
 // Consequently, the number of diamonds (RAW) can exceed the
 // number of accepted research events (SEPARATED). This is
 // intentional, not missing data. The study uses only the
 // accepted events, while diamonds preserve the complete
 // observation history of threshold crossings.
 //
 // A cooldown reduces obvious clusters. It cannot make
 // observations independent: persistent market regimes,
 // common shocks, and overlapping subsequent return windows
 // can continue to link the results. Accepted-event spacing
 // is measured from the last ACCEPTED event, not necessarily
 // from the most recent raw diamond.
 // ============================================================
 // 12. RELATIVE TRAJECTORY
 // ============================================================
 //
 // The dashboard also describes the direction of
 // the relative-performance measure.
 //
 // IMPROVING
 //
 // Relative performance has improved over the
 // selected trajectory interval.
 //
 // DETERIORATING
 //
 // Relative performance has weakened over the
 // selected trajectory interval.
 //
 // FLAT
 //
 // There is no measured change over that interval.
 //
 // Trajectory provides context around the extreme.
 //
 // An extreme discount with deteriorating trajectory
 // indicates that relative weakness continues.
 //
 // An extreme discount with improving trajectory
 // indicates that relative weakness is moderating
 // or reversing over the selected interval.
 //
 // Improvement does not establish a durable reversal.
 //
 // The indicator deliberately does not convert
 // trajectory into an automatic entry signal.
 //
 //
 // ============================================================
 // 13. HISTORICAL FORWARD OUTCOMES
 // ============================================================
 //
 // This is the empirical research component.
 //
 // Whenever a new extreme-discount episode begins,
 // the indicator records an event.
 //
 // It subsequently evaluates relative performance over:
 //
 // 5 trading days
 // 10 trading days
 // 20 trading days
 // 60 trading days
 //
 // Outcomes are included only after their respective
 // observation windows have elapsed.
 //
 // An event occurring yesterday cannot contribute
 // to a completed 20-day forward observation.
 //
 // The dashboard reports:
 //
 // AVG %
 //
 // Mean realized forward relative return following
 // the recorded extreme-discount events.
 //
 // WIN %
 //
 // Percentage of completed observations for which
 // subsequent relative performance was positive.
 //
 // N
 //
 // Number of completed observations available for
 // the specified horizon.
 //
 // EXAMPLE:
 //
 // 20 DAYS
 // AVG: +3.4%
 // WIN: 65%
 // N:   20
 //
 // This means that the sample of 20 completed
 // historical extreme-discount observations had:
 //
 // - An average 20-day relative return of +3.4%.
 // - Positive relative returns in 65% of observations.
 //
 // This example is illustrative, not an actual
 // calculated result.
 //
 // A positive forward relative return does not
 // necessarily mean the stock's price increased.
 //
 // The stock may simply have fallen less than
 // the comparison benchmark.
 //
 //
 //
 // V6: CONDITIONAL FORWARD OUTCOME STUDY
 //
 // The study starts at the CLOSE of an accepted separated
 // extreme event. Its forward observation is the compounded
 // target-versus-benchmark return over 5, 10, 20 or 60
 // subsequent daily bars. It is added only once all bars of
 // that horizon have elapsed AND valid prices are present.
 // No future bars are used when the event diamond is formed.
 //
 // EACH HORIZON REPORTS:
 //
 // EVENT = mean realized forward RELATIVE return after
 //         accepted extreme research events with complete
 //         observations for that horizon.
 //
 // BASE  = mean realized forward RELATIVE return from all
 //         eligible historical starting dates for the same
 //         horizon. The BASE sample INCLUDES event dates.
 //         It is an unconditional reference, not a separately
 //         matched or disjoint control group.
 //
 // EDGE  = EVENT - BASE in PERCENTAGE POINTS.
 //         Positive EDGE means conditional average exceeded
 //         the unconditional average in this sample.
 //
 // W     = fraction of mature event observations with a
 //         positive forward relative return, expressed in %.
 //
 // N     = number of MATURE accepted event observations for
 //         that horizon; it is NOT raw episode count.
 //
 // EXAMPLE (illustrative figures, not empirical findings):
 // EVENT = +2.6%; BASE = +1.0%; EDGE = +1.6 pp.
 // There is historical conditional outperformance of 1.6
 // percentage points in this sample. This alone proves no
 // positive expected return, causal effect or trading edge.
 //
 // Sample N may differ across horizons: recent episodes can
 // have mature 5-day outcomes but not yet mature 60-day ones.
 // The research caution highlights N below the user-selected
 // minimum sample count. Minimum N is a warning threshold,
 // NOT an empirical statistical-significance criterion.
 //
 // Underlying EVENT and BASE forward intervals overlap and
 // are dependent. The displayed EDGE is not a confidence
 // interval, p-value, t-statistic or forecast probability.
 // A positive W compares relative returns, NOT necessarily
 // profits or positive absolute stock price returns.
 // ============================================================
 // 14. WHAT THE FORWARD STUDY CAN TELL US
 // ============================================================
 //
 // The forward study investigates whether unusual relative
 // underperformance has historically been followed by:
 //
 // A. Further relative deterioration.
 //
 // B. Relative stabilization.
 //
 // C. Partial relative recovery.
 //
 // D. Strong subsequent relative outperformance.
 //
 // Consider two possible historical patterns.
 //
 // PATTERN A:
 //
 // Average forward relative returns remain negative
 // after extreme-discount episodes.
 //
 // This suggests that the measured extremes have
 // historically been followed by continued weakness.
 //
 // PATTERN B:
 //
 // Average forward relative returns become positive
 // after extreme-discount episodes.
 //
 // This is consistent with historical relative recovery.
 //
 // Neither pattern automatically establishes a tradeable
 // edge without further controls and testing.
 //
 // A useful assessment should also examine:
 //
 // - The unconditional forward-return benchmark.
 // - Event sample size.
 // - Dispersion of outcomes.
 // - Maximum adverse movement.
 // - Overlapping observation windows.
 // - Changes in market regime.
 // - Out-of-sample stability.
 //
 // Closely spaced events can share much of the same
 // forward observation period and should not be treated
 // as independent experiments.
 //
 //
 //
 // V6: INTERPRETING EDGE WITH SCIENTIFIC DISCIPLINE
 //
 // An EDGE > 0 is an observed difference of sample averages,
 // not a validated discovery of a repeatable anomaly. Before
 // drawing any predictive conclusion, test an independently
 // specified universe of benchmark constructions, untouched
 // time periods, transaction-cost assumptions, and an
 // explicit comparator matched for regime and volatility.
 //
 // The unconditional BASE uses EVERY eligible historical
 // starting date, including accepted extreme-event dates.
 // It is therefore a useful descriptive reference, but not
 // an independent control sample. BASE intervals overlap
 // extensively (for example 20-day returns started one day
 // apart share 19 daily bars). EDGE uncertainty requires
 // separate treatment of autocorrelation and clustering.
 //
 // One must also ask whether differences are explained by
 // sector concentration, changing correlation, single-stock
 // news or market-wide liquidity changes rather than by a
 // stable relative-discount phenomenon.
 // ============================================================
 // 15. LIMITATIONS & SCIENTIFIC CAUTIONS
 // ============================================================
 //
 // FIRST: RELATIVE DISCOUNT IS NOT INTRINSIC VALUE.
 //
 // The model does not estimate discounted cash flow,
 // earnings power, asset value, or fundamental fair value.
 //
 // It identifies statistically unusual relative movement.
 //
 //
 // SECOND: BENCHMARK SELECTION MATTERS.
 //
 // The same stock may appear unusually weak relative
 // to one sector and entirely normal relative to another.
 //
 // Benchmark choice is part of the research hypothesis.
 //
 //
 // THIRD: CONSTITUENT WEIGHTS MATTER.
 //
 // Frozen contemporary portfolio weights applied to
 // historical observations introduce look-ahead bias.
 //
 // A custom basket is not a faithful historical index
 // unless constituent membership, weights, and
 // rebalancing are reconstructed point in time.
 //
 //
 // FOURTH: STATISTICAL RELATIONSHIPS CAN CHANGE.
 //
 // Business models, market structure, liquidity,
 // industry composition, and capital allocation
 // can evolve.
 //
 // A historically unusual relative decline may
 // represent a permanent change rather than
 // a temporary dislocation.
 //
 //
 // FIFTH: EXTREME DOES NOT MEAN REVERSAL.
 //
 // A security may remain statistically depressed
 // for an extended period.
 //
 // Extreme observations may precede further losses.
 //
 //
 // SIXTH: FORWARD RETURNS ARE DESCRIPTIVE.
 //
 // Historical mean outcomes and win rates are not
 // independently validated predictive probabilities.
 //
 // Small or overlapping samples can produce unstable
 // estimates.
 //
 //
 // SEVENTH: DATA QUALITY MATTERS.
 //
 // Corporate actions, symbol history, missing returns,
 // dividend treatment, and benchmark construction
 // can influence the results.
 //
 // The current instrument uses TradingView's available
 // price series and must be evaluated accordingly.
 //
 //
 //
 // EIGHTH: EVENT DEPENDENCE AND SAMPLE SELECTION.
 //
 // Event cooldowns reduce repeated nearby signals but do not
 // guarantee independent observations. Forward-study EVENT
 // and BASE outcomes can overlap across time. Baseline dates
 // include event dates, so EDGE is a descriptive contrast.
 // No standard errors or confidence intervals are claimed.
 //
 // NINTH: DISTRIBUTION INSTABILITY DIAGNOSTICS.
 //
 // The configured statistical reference is split into recent and
 // older halves. RECENT VOLATILITY RATIO divides the recent
 // half-window standard deviation of rolling relative returns
 // by the full-window standard deviation. The default
 // threshold flags ratios above 1.75 or below 1/1.75.
 //
 // MEAN SHIFT compares the recent and older half-window
 // means, divided by the full-window standard deviation.
 // Default caution threshold: absolute shift above 1.0 SD.
 //
 // SHIFT / CAUTION means one or both heuristic thresholds
 // is breached. NO LARGE SHIFT merely means that neither
 // configured test breached its threshold. It does NOT mean
 // stationarity was proven, nor that a discount will reverse.
 // Both tests use overlapping relative-return observations.
 //
 // TENTH: FROZEN-WEIGHT BASKET INTEGRITY.
 //
 // In DIRECT mode the benchmark is the selected symbol's
 // reported PRICE series with NO constituent exclusions.
 // In SYNTHETIC mode the script uses at most 12 user-entered
 // symbols and their fixed weights across all chart history.
 // Historical weights, membership and changing sector
 // definitions are not reconstructed. Historical basket
 // observations may therefore suffer look-ahead and survivor
 // bias and may depart substantially from the named ETF.
 //
 // CONFIGURATION coverage is the percentage of the SUM OF
 // USER-ENTERED REFERENCE WEIGHTS that remains in the basket
 // after exclusions. It is never the percentage of the
 // actual ETF replicated, nor a test of tracking error.
 // Basket weighting assumes daily rebalancing; fees,
 // reconstitution costs and dividend reinvestment are absent.
 //
 // ELEVENTH: VALIDATION STATUS.
 //
 // The calculation code is available for external scrutiny.
 // Source visibility does not constitute independent
 // replication, predictive validation or data certification.
 // Users should compare outputs with external historical
 // price series and separately check point-in-time holdings.
 // ============================================================
 // 16. HOW TO CONFIGURE IT
 // ============================================================
 //
 // 1. SELECT THE TARGET
 //
 // In "Stock to assess", choose GOOGL, AAPL, MSFT,
 // AMZN, or any other supported symbol.
 //
 //
 // 2. CHOOSE A BENCHMARK MODE
 //
 // Select "Direct ETF" for a comparison against
 // XLK, QQQ, SPY, XLC, or another benchmark.
 //
 // Select "Constituent Basket" to control the
 // individual stocks included in the comparison.
 //
 //
 // 3. CONFIGURE CONSTITUENTS & EXCLUSIONS
 //
 // Change any of the 12 constituent symbols and weights.
 //
 // Tick "Exclude" beside any stock you wish to remove.
 //
 // The script renormalizes the remaining basket.
 //
 // Select "Proportional" to use the supplied weights
 // or "Equal" to give active constituents equal weight.
 //
 //
 // 4. SELECT THE STATISTICAL WINDOWS
 //
 // Relative performance horizon: 63 days by default.
 //
 // Statistical reference window: 252 days by default.
 //
 // Longer reference windows provide more historical
 // observations but may mix different market regimes.
 //
 // Shorter reference windows adapt faster but may
 // produce more unstable classifications.
 //
 //
 // 5. EXAMINE THE DISCOUNT
 //
 // The Z-score line identifies unusual relative
 // underperformance.
 //
 // Large red diamonds mark new extreme episodes.
 //
 // The dashboard displays:
 //
 // - Discount classification.
 // - Statistical Z-score.
 // - Historical percentile.
 // - Relative return.
 // - Relative trajectory.
 // - Benchmark configuration.
 // - Historical forward outcomes.
 //
 //
 // 6. INTERPRET THE OUTCOMES
 //
 // Examine what historically followed similar extremes.
 //
 // Look beyond the average return.
 //
 // Sample size, event dependence, benchmark choice,
 // and stability across different periods matter.
 //
 // Do not confuse a statistically unusual observation
 // with proof of economic mispricing.
 //
 //
 //
 // 7. CONFIGURE RESEARCH CONTROLS (V6)
 //
 // Separated-event cooldown: minimum trading-bar spacing
 // between accepted research events; defaults to 60 bars.
 // It does not suppress raw diamonds or force independent
 // observations. The dashboard shows RAW / SEPARATED counts.
 //
 // Volatility drift ratio limit: flags a recent half-window
 // dispersion more than 1.75 times the full-window estimate,
 // or less than its reciprocal. User configurable.
 //
 // Mean-shift threshold: flags recent-versus-older mean
 // separation exceeding 1.0 full-window standard deviation.
 //
 // Minimum event samples: marks a small sample when completed
 // accepted EVENT observations fall below this number.
 // Changing any of these inputs changes the study definition.
 //
 // 8. VERIFY BENCHMARK MODE AND DATA COVERAGE
 //
 // DIRECT ETF = unmodified selected symbol price history.
 // CONSTITUENT BASKET = frozen-weight synthetic portfolio.
 // The 12 slots do NOT automatically import an ETF's holdings.
 // Slots with weight ZERO are disabled. Exclusions remove
 // active stocks and renormalize the remaining constituents.
 // Equal mode allocates the same daily weight to active names.
 // The dashboard's coverage refers ONLY to input weights.
 // Check for missing historical data and short histories.
 // ============================================================
 // 17. RECOMMENDED RESEARCH WORKFLOW
 // ============================================================
 //
 // STEP 1:
 // Identify the stock to investigate.
 //
 // STEP 2:
 // Choose an economically defensible benchmark.
 //
 // STEP 3:
 // Exclude constituents if their presence would
 // distort the specific comparison being studied.
 //
 // STEP 4:
 // Examine the current Z-score and percentile.
 //
 // STEP 5:
 // Identify prior extreme-discount episodes.
 //
 // STEP 6:
 // Review completed forward relative outcomes.
 //
 // STEP 7:
 // Compare those outcomes with ordinary periods
 // and alternative benchmark constructions.
 //
 // STEP 8:
 // Determine whether the observed relationship
 // survives changes in period, sector, and regime.
 //
 // The goal is not to locate the lowest possible
 // price retrospectively.
 //
 // The goal is to determine whether relative extremes
 // contain reproducible information about subsequent
 // market behaviour.
 //
 //
 //
 // STEP 9:
 // Compare each forward horizon's EVENT mean against BASE and
 // report EDGE, W and mature N without calling it alpha.
 //
 // STEP 10:
 // Inspect RAW / SEPARATED episode counts, event-cooldown
 // sensitivity and small-sample warnings. Consider whether
 // event windows remain economically dependent.
 //
 // STEP 11:
 // Examine SHIFT / CAUTION, recent volatility ratio and mean
 // shift. Test stability across rolling reference lengths.
 //
 // STEP 12:
 // For synthetic baskets, check point-in-time composition
 // and weights against actual holdings where available.
 // Verify price-adjustment and dividend conventions.
 //
 // STEP 13:
 // Replicate forward statistics externally, account for
 // overlapping outcomes and transaction costs, and test on
 // untouched time periods before asserting a trading edge.
 // ============================================================
 // 18. CENTRAL INTERPRETIVE PRINCIPLE
 // ============================================================
 //
 // A statistical extreme identifies an unusual condition.
 //
 // It does not establish why that condition exists.
 //
 // It does not establish that the condition will reverse.
 //
 // It does not establish a favourable expected return.
 //
 // Those are separate empirical questions.
 //
 // CT — Maybe the Price Is Wrong™ provides the
 // measurement framework through which those
 // questions can be investigated.
 //
 // MEASURE THE DISLOCATION.
 // EXAMINE THE OUTCOME.
 // TEST THE RELATIONSHIP.
 //
 // ============================================================
 // ============================================================
 // 19. DISCLAIMER — IMPORTANT INFORMATION
 // ============================================================
 //
 // CT — Maybe the Price Is Wrong™ is an experimental,
 // research-oriented statistical indicator developed
 // by Complexity Trading.
 //
 // It is provided solely for informational, educational,
 // and analytical purposes.
 //
 // Nothing contained in this indicator, its documentation,
 // calculations, classifications, alerts, or historical
 // observations constitutes investment advice, financial
 // advice, a recommendation, or a solicitation to buy,
 // sell, or hold any security or financial instrument.
 //
 // The terms "Discount", "Extreme Discount", and
 // "Relative Premium" describe statistical relationships
 // against a selected benchmark. They do not represent
 // determinations of intrinsic value, fair value, or
 // economic mispricing.
 //
 // The indicator does not predict market direction,
 // identify guaranteed reversals, or establish that
 // any security is suitable for investment.
 //
 // Historical results, including average forward returns,
 // win rates, and event frequencies, are descriptive
 // observations. They are not forecasts or guarantees
 // of future performance.
 //
 // Results may be affected by benchmark selection,
 // constituent composition, weighting assumptions,
 // historical data availability, corporate actions,
 // changing market regimes, and statistical estimation
 // error. Custom baskets may not faithfully reproduce
 // the historical composition or performance of the
 // indices or ETFs they are intended to approximate.
 //
 // Statistical relationships observed in historical
 // data may weaken, disappear, or reverse without warning.
 // Extreme relative underperformance can persist and
 // may precede further substantial losses.
 //
 // No representation or warranty, express or implied,
 // is made regarding the accuracy, completeness,
 // reliability, or fitness for any particular purpose
 // of the indicator or its outputs.
 //
 // Users are solely responsible for their own research,
 // investment decisions, position sizing, and risk
 // management, and should obtain independent professional
 // advice where appropriate.
 //
 // Use of this indicator is entirely at the user's
 // own discretion and risk.
 //
 //
 // V6 RESEARCH-SPECIFIC DISCLOSURE
 //
 // EVENT, BASE, EDGE, event win fractions and distribution
 // warnings are descriptive IN-SAMPLE statistics. They have
 // NOT been independently validated as predictive signals.
 // Positive EDGE does not establish causation, statistical
 // significance, independent observations, absolute returns,
 // or a profitable implementable strategy.
 //
 // Synthetic baskets use fixed USER-ENTERED weights and
 // constituents across history and can exhibit look-ahead,
 // survivor, selection and benchmark-tracking biases.
 // The displayed basket coverage is configuration coverage,
 // NOT historical coverage of any actual ETF or index.
 //
 // The source is released for open-source inspection under
 // MPL 2.0; open availability is not a validation claim.
 // Copyright (c) Complexity Trading.
 // Distributed under Mozilla Public License 2.0.
 //
 // ============================================================
 
 
 
// ====================== INPUTS =======================
 
string g1 = "01 | Stock & Benchmark"
 
string targetSymbol = input.symbol("NASDAQ:GOOGL", "Stock to assess", group=g1)
 
string benchmarkMode = input.string("Constituent Basket", "Benchmark mode", options=["Direct ETF", "Constituent Basket"], group=g1)
 
string directBenchmark = input.symbol("AMEX:XLK", "Direct ETF / Index", group=g1)
 
string weightingMode = input.string("Proportional", "Basket weighting", options=["Proportional", "Equal"], group=g1)
 
bool autoExcludeTarget = input.bool(true, "Auto-exclude target from basket", group=g1)
 
 
 
// 12 slots. A weight of zero disables a slot. Empty-symbol
 
// defaults are avoided to prevent invalid request contexts.
 
string g2 = "02 | Constituents & Exclusions"
 
string s1 = input.symbol("NASDAQ:AAPL", "01 | Symbol", inline="c1", group=g2)
 
float w1 = input.float(15.31, "Weight", minval=0, inline="c1", group=g2)
 
bool x1 = input.bool(false, "Exclude", inline="c1", group=g2)
 
string s2 = input.symbol("NASDAQ:MSFT", "02 | Symbol", inline="c2", group=g2)
 
float w2 = input.float(11.80, "Weight", minval=0, inline="c2", group=g2)
 
bool x2 = input.bool(false, "Exclude", inline="c2", group=g2)
 
string s3 = input.symbol("NASDAQ:PLTR", "03 | Symbol", inline="c3", group=g2)
 
float w3 = input.float(2.61, "Weight", minval=0, inline="c3", group=g2)
 
bool x3 = input.bool(false, "Exclude", inline="c3", group=g2)
 
string s4 = input.symbol("NASDAQ:CSCO", "04 | Symbol", inline="c4", group=g2)
 
float w4 = input.float(2.54, "Weight", minval=0, inline="c4", group=g2)
 
bool x4 = input.bool(false, "Exclude", inline="c4", group=g2)
 
string s5 = input.symbol("NASDAQ:PANW", "05 | Symbol", inline="c5", group=g2)
 
float w5 = input.float(1.84, "Weight", minval=0, inline="c5", group=g2)
 
bool x5 = input.bool(false, "Exclude", inline="c5", group=g2)
 
string s6 = input.symbol("NASDAQ:CRWD", "06 | Symbol", inline="c6", group=g2)
 
float w6 = input.float(1.57, "Weight", minval=0, inline="c6", group=g2)
 
bool x6 = input.bool(false, "Exclude", inline="c6", group=g2)
 
string s7 = input.symbol("NYSE:IBM", "07 | Symbol", inline="c7", group=g2)
 
float w7 = input.float(1.50, "Weight", minval=0, inline="c7", group=g2)
 
bool x7 = input.bool(false, "Exclude", inline="c7", group=g2)
 
string s8 = input.symbol("NYSE:ORCL", "08 | Symbol", inline="c8", group=g2)
 
float w8 = input.float(1.39, "Weight", minval=0, inline="c8", group=g2)
 
bool x8 = input.bool(false, "Exclude", inline="c8", group=g2)
 
string s9 = input.symbol("NYSE:APH", "09 | Symbol", inline="c9", group=g2)
 
float w9 = input.float(1.21, "Weight", minval=0, inline="c9", group=g2)
 
bool x9 = input.bool(false, "Exclude", inline="c9", group=g2)
 
string s10 = input.symbol("NYSE:CRM", "10 | Symbol", inline="c10", group=g2)
 
float w10 = input.float(1.16, "Weight", minval=0, inline="c10", group=g2)
 
bool x10 = input.bool(false, "Exclude", inline="c10", group=g2)
 
string s11 = input.symbol("AMEX:XLK", "11 | Symbol", inline="c11", group=g2)
 
float w11 = input.float(0.00, "Weight", minval=0, inline="c11", group=g2)
 
bool x11 = input.bool(false, "Exclude", inline="c11", group=g2)
 
string s12 = input.symbol("AMEX:XLK", "12 | Symbol", inline="c12", group=g2)
 
float w12 = input.float(0.00, "Weight", minval=0, inline="c12", group=g2)
 
bool x12 = input.bool(false, "Exclude", inline="c12", group=g2)
 
 
 
 
 
string g3 = "03 | Statistical Model"
 
int relativeWindow = input.int(63, "Relative return horizon", minval=10, maxval=252, group=g3)
 
int statWindow = input.int(252, "Statistical reference window", minval=60, maxval=750, group=g3)
 
float cheapLevel = input.float(-1.0, "Discount threshold", step=0.1, group=g3)
 
float extremeLevel = input.float(-2.0, "Extreme threshold", step=0.1, group=g3)
 
int trajectoryBars = input.int(3, "Trajectory lookback", minval=1, maxval=20, group=g3)
 
 
 
string g4 = "04 | Research Controls"
 
int cooldownBars = input.int(60, "Separated-event cooldown (days)", minval=1, maxval=252, group=g4)
 
float volatilityRatioLimit = input.float(1.75, "Volatility drift ratio limit", minval=1.1, step=0.05, group=g4)
 
float meanShiftLimit = input.float(1.0, "Mean-shift threshold (long SD)", minval=0.2, step=0.1, group=g4)
 
int minEventSamples = input.int(10, "Minimum samples to assess", minval=3, maxval=100, group=g4)
 
 
 
string g5 = "05 | Display"
 
bool showDiamonds = input.bool(true, "Show large extreme diamonds", group=g5)
 
bool showPanel = input.bool(true, "Show dashboard", group=g5)
 
bool showOutcomes = input.bool(true, "Show forward outcomes", group=g5)
 
bool showDiagnostics = input.bool(true, "Show distribution diagnostics", group=g5)
 
 
 
if not timeframe.isdaily
 
    runtime.error("Use the DAILY (1D) timeframe.")
 
if extremeLevel >= cheapLevel or cheapLevel >= 0
 
    runtime.error("Require Extreme < Discount < 0.")
 
 
 
var array<string> symbols = array.from(
 
     s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12)
 
var array<float> weights = array.from(
 
     w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12)
 
var array<bool> exclusions = array.from(
 
     x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12)
 
 
 
// =====================================================
 
// BENCHMARK: direct price series or synthetic basket.
 
// One request per active symbol; no duplicate second loop.
 
// The user-defined basket is DAILY rebalanced and uses
 
// frozen weights throughout the historical sample.
 
// =====================================================
 
bool basketMode = benchmarkMode == "Constituent Basket"
 
float targetReturn = request.security(targetSymbol, "D", close / close[1] - 1.0,
 
     gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_off,
 
     ignore_invalid_symbol=true)
 
float directReturn = na
 
if not basketMode
 
    directReturn := request.security(directBenchmark, "D", close / close[1] - 1.0,
 
         gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_off,
 
         ignore_invalid_symbol=true)
 
 
 
float weightedReturn = 0.0
 
float equalSum = 0.0
 
float includedWeight = 0.0
 
float configuredWeight = 0.0
 
int includedCount = 0
 
int configuredCount = 0
 
int excludedCount = 0
 
bool basketValid = true
 
bool duplicateFound = false
 
 
 
if basketMode
 
    for i = 0 to array.size(symbols) - 1
 
        string sym = array.get(symbols, i)
 
        float w = array.get(weights, i)
 
        bool configured = w > 0 and sym != ""
 
        bool isExcluded = array.get(exclusions, i) or (autoExcludeTarget and sym == targetSymbol)
 
        if configured
 
            configuredWeight += w
 
            configuredCount += 1
 
            if isExcluded
 
                excludedCount += 1
 
            else
 
                // Reject duplicated active symbols: otherwise one
 
                // security would be double-counted in basket weights.
 
                bool duplicate = false
 
                if i > 0
 
                    for j = 0 to i - 1
 
                        if array.get(weights, j) > 0 and not array.get(exclusions, j) and not (autoExcludeTarget and array.get(symbols, j) == targetSymbol) and array.get(symbols, j) == sym
 
                            duplicate := true
 
                if duplicate
 
                    duplicateFound := true
 
                    basketValid := false
 
                else
 
                    float r = request.security(sym, "D", close / close[1] - 1.0,
 
                         gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_off,
 
                         ignore_invalid_symbol=true)
 
                    if na(r) or r <= -1
 
                        basketValid := false
 
                    else
 
                        weightedReturn += w * r
 
                        equalSum += r
 
                        includedWeight += w
 
                        includedCount += 1
 
 
 
float basketReturn = na
 
if basketMode
 
    if basketValid and includedCount > 0 and includedWeight > 0
 
        basketReturn := weightingMode == "Proportional" ? weightedReturn / includedWeight : equalSum / includedCount
 
else
 
    basketReturn := directReturn
 
 
 
float configCoverage = configuredWeight > 0 ? 100.0 * includedWeight / configuredWeight : na
 
bool valid = not na(targetReturn) and not na(basketReturn) and targetReturn > -1 and basketReturn > -1
 
float logIncrement = valid ? math.log(1.0 + targetReturn) - math.log(1.0 + basketReturn) : na
 
float logIndex = ta.cum(nz(logIncrement, 0.0))
 
float validFlag = valid ? 1.0 : 0.0
 
// Exactly relativeWindow DAILY increments: t-relativeWindow+1 ... t.
 
bool windowValid = ta.sma(validFlag, relativeWindow) == 1.0
 
float relativeMove = windowValid and not na(logIndex[relativeWindow]) ? logIndex - logIndex[relativeWindow] : na
 
float relativePct = not na(relativeMove) ? 100.0 * (math.exp(relativeMove) - 1.0) : na
 
 
 
// =====================================================
 
// Distribution requires an UNINTERRUPTED historical sample.
 
// TradingView's ta.sma/ta.stdev can skip na observations;
 
// require all statWindow relative windows to be present.
 
// =====================================================
 
float statValidFlag = not na(relativeMove) ? 1.0 : 0.0
 
bool statSampleComplete = ta.sma(statValidFlag, statWindow) == 1.0
 
float mu = ta.sma(relativeMove, statWindow)
 
float sigma = ta.stdev(relativeMove, statWindow)
 
float zRaw = sigma > 1e-10 ? (relativeMove - mu) / sigma : na
 
float percentileRaw = ta.percentrank(relativeMove, statWindow)
 
float z = statSampleComplete and valid ? zRaw : na
 
float percentile = statSampleComplete and valid ? percentileRaw : na
 
bool ready = not na(z) and not na(percentile)
 
bool discount = ready and z <= cheapLevel
 
bool extreme = ready and z <= extremeLevel
 
 
 
// =====================================================
 
// Distribution diagnostics: two-half-window mean shift
 
// and short-to-long dispersion ratio. These are heuristics,
 
// NOT formal stationarity tests or Gaussian probabilities.
 
// =====================================================
 
int halfWindow = int(math.floor(statWindow / 2.0))
 
float recentMean = ta.sma(relativeMove, halfWindow)
 
float olderMean = ta.sma(relativeMove[halfWindow], halfWindow)
 
float shortSigma = ta.stdev(relativeMove, halfWindow)
 
float volRatio = ready and sigma > 1e-10 ? shortSigma / sigma : na
 
float meanShift = ready and sigma > 1e-10 ? (recentMean - olderMean) / sigma : na
 
bool volDrift = ready and not na(volRatio) and (volRatio > volatilityRatioLimit or volRatio < 1.0 / volatilityRatioLimit)
 
bool meanDrift = ready and not na(meanShift) and math.abs(meanShift) > meanShiftLimit
 
bool distributionUnstable = volDrift or meanDrift
 
string distributionState = not ready ? "WARMUP" : distributionUnstable ? "SHIFT / CAUTION" : "NO LARGE SHIFT"
 
 
 
float trajectoryDelta = ready and not na(relativeMove[trajectoryBars]) ? relativeMove - relativeMove[trajectoryBars] : na
 
string trajectory = na(trajectoryDelta) ? "UNAVAILABLE" : trajectoryDelta > 0 ? "IMPROVING" : trajectoryDelta < 0 ? "DETERIORATING" : "FLAT"
 
color trajectoryColor = na(trajectoryDelta) ? color.gray : trajectoryDelta > 0 ? color.aqua : trajectoryDelta < 0 ? color.orange : color.silver
 
 
 
string state = "WARMUP"
 
color stateColor = color.gray
 
if ready
 
    if extreme
 
        state := "EXTREME DISCOUNT"
 
        stateColor := color.red
 
    else if discount
 
        state := "DISCOUNT"
 
        stateColor := color.orange
 
    else if z >= 1.0
 
        state := "RELATIVE PREMIUM"
 
        stateColor := color.aqua
 
    else
 
        state := "NORMAL RANGE"
 
        stateColor := color.white
 
if basketMode and duplicateFound
 
    state := "DUPLICATE SYMBOL"
 
    stateColor := color.red
 
else if basketMode and includedCount == 0
 
    state := "EMPTY / INVALID BASKET"
 
    stateColor := color.gray
 
 
 
// =====================================================
 
// Event independence: raw episodes always identified,
 
// research events separated by cooldownBars observations.
 
// The large red diamond identifies the RAW episode start.
 
// Research event sample uses SEPARATED episodes only.
 
// =====================================================
 
bool rawEvent = barstate.isconfirmed and extreme and not extreme[1]
 
var int lastAcceptedBar = na
 
var int rawEvents = 0
 
var int separatedEvents = 0
 
bool studyEvent = false
 
if rawEvent
 
    rawEvents += 1
 
    if na(lastAcceptedBar) or bar_index - lastAcceptedBar >= cooldownBars
 
        studyEvent := true
 
        lastAcceptedBar := bar_index
 
        separatedEvents += 1
 
 
 
// =====================================================
 
// Forward outcomes: conditional separate event returns
 
// versus ALL valid starting dates (unconditional control).
 
// At bar t, we calculate t-h -> t from logIndex.
 
// Event eligibility references the starting bar t-h.
 
// Both samples require h consecutive valid daily returns.
 
// Raw episodes are counted but not used in event averages.
 
// =====================================================
 
var array<int> horizons = array.from(5, 10, 20, 60)
 
var array<float> eventSums = array.new_float(4, 0.0)
 
var array<float> eventSqSums = array.new_float(4, 0.0)
 
var array<int> eventCounts = array.new_int(4, 0)
 
var array<int> eventWins = array.new_int(4, 0)
 
var array<float> baseSums = array.new_float(4, 0.0)
 
var array<float> baseSqSums = array.new_float(4, 0.0)
 
var array<int> baseCounts = array.new_int(4, 0)
 
 
 
// Compute horizon-valid series every bar before conditional processing.
 
bool valid5 = ta.sma(validFlag, 5) == 1.0
 
bool valid10 = ta.sma(validFlag, 10) == 1.0
 
bool valid20 = ta.sma(validFlag, 20) == 1.0
 
bool valid60 = ta.sma(validFlag, 60) == 1.0
 
 
 
if barstate.isconfirmed and valid5 and ready[5] and not na(logIndex[5])
 
    float realized5 = 100.0 * (math.exp(logIndex - logIndex[5]) - 1.0)
 
    array.set(baseSums, 0, array.get(baseSums, 0) + realized5)
 
    array.set(baseSqSums, 0, array.get(baseSqSums, 0) + realized5 * realized5)
 
    array.set(baseCounts, 0, array.get(baseCounts, 0) + 1)
 
    if studyEvent[5]
 
        array.set(eventSums, 0, array.get(eventSums, 0) + realized5)
 
        array.set(eventSqSums, 0, array.get(eventSqSums, 0) + realized5 * realized5)
 
        array.set(eventCounts, 0, array.get(eventCounts, 0) + 1)
 
        if realized5 > 0
 
            array.set(eventWins, 0, array.get(eventWins, 0) + 1)
 
 
 
if barstate.isconfirmed and valid10 and ready[10] and not na(logIndex[10])
 
    float realized10 = 100.0 * (math.exp(logIndex - logIndex[10]) - 1.0)
 
    array.set(baseSums, 1, array.get(baseSums, 1) + realized10)
 
    array.set(baseSqSums, 1, array.get(baseSqSums, 1) + realized10 * realized10)
 
    array.set(baseCounts, 1, array.get(baseCounts, 1) + 1)
 
    if studyEvent[10]
 
        array.set(eventSums, 1, array.get(eventSums, 1) + realized10)
 
        array.set(eventSqSums, 1, array.get(eventSqSums, 1) + realized10 * realized10)
 
        array.set(eventCounts, 1, array.get(eventCounts, 1) + 1)
 
        if realized10 > 0
 
            array.set(eventWins, 1, array.get(eventWins, 1) + 1)
 
 
 
if barstate.isconfirmed and valid20 and ready[20] and not na(logIndex[20])
 
    float realized20 = 100.0 * (math.exp(logIndex - logIndex[20]) - 1.0)
 
    array.set(baseSums, 2, array.get(baseSums, 2) + realized20)
 
    array.set(baseSqSums, 2, array.get(baseSqSums, 2) + realized20 * realized20)
 
    array.set(baseCounts, 2, array.get(baseCounts, 2) + 1)
 
    if studyEvent[20]
 
        array.set(eventSums, 2, array.get(eventSums, 2) + realized20)
 
        array.set(eventSqSums, 2, array.get(eventSqSums, 2) + realized20 * realized20)
 
        array.set(eventCounts, 2, array.get(eventCounts, 2) + 1)
 
        if realized20 > 0
 
            array.set(eventWins, 2, array.get(eventWins, 2) + 1)
 
 
 
if barstate.isconfirmed and valid60 and ready[60] and not na(logIndex[60])
 
    float realized60 = 100.0 * (math.exp(logIndex - logIndex[60]) - 1.0)
 
    array.set(baseSums, 3, array.get(baseSums, 3) + realized60)
 
    array.set(baseSqSums, 3, array.get(baseSqSums, 3) + realized60 * realized60)
 
    array.set(baseCounts, 3, array.get(baseCounts, 3) + 1)
 
    if studyEvent[60]
 
        array.set(eventSums, 3, array.get(eventSums, 3) + realized60)
 
        array.set(eventSqSums, 3, array.get(eventSqSums, 3) + realized60 * realized60)
 
        array.set(eventCounts, 3, array.get(eventCounts, 3) + 1)
 
        if realized60 > 0
 
            array.set(eventWins, 3, array.get(eventWins, 3) + 1)
 
 
 
// Return stats (percentage-point advantage, not value discount).
 
f_stats(int idx) =>
 
    int ne = array.get(eventCounts, idx)
 
    int nb = array.get(baseCounts, idx)
 
    float eventMean = ne > 0 ? array.get(eventSums, idx) / ne : na
 
    float baseMean = nb > 0 ? array.get(baseSums, idx) / nb : na
 
    float edge = not na(eventMean) and not na(baseMean) ? eventMean - baseMean : na
 
    float win = ne > 0 ? 100.0 * array.get(eventWins, idx) / ne : na
 
    float eventVar = ne > 1 ? math.max(0.0, (array.get(eventSqSums, idx) - array.get(eventSums, idx) * array.get(eventSums, idx) / ne) / (ne - 1)) : na
 
    float baseVar = nb > 1 ? math.max(0.0, (array.get(baseSqSums, idx) - array.get(baseSums, idx) * array.get(baseSums, idx) / nb) / (nb - 1)) : na
 
    float eventSD = not na(eventVar) ? math.sqrt(eventVar) : na
 
    float baseSD = not na(baseVar) ? math.sqrt(baseVar) : na
 
    [eventMean, baseMean, edge, win, ne, nb, eventSD, baseSD]
 
 
 
color plotColor = not ready ? color.gray : extreme ? color.red : discount ? color.orange : z > 1.0 ? color.aqua : color.white
 
plot(ready ? z : na, "Relative Discount Z-Score", color=plotColor, linewidth=3)
 
hline(0.0, "Statistical Center", color=color.new(color.gray, 45), linestyle=hline.style_dotted)
 
hline(cheapLevel, "Discount", color=color.new(color.orange, 35), linestyle=hline.style_dashed)
 
hline(extremeLevel, "Extreme", color=color.new(color.red, 20), linestyle=hline.style_dashed)
 
hline(1.0, "Relative Premium", color=color.new(color.aqua, 75), linestyle=hline.style_dotted)
 
plotshape(showDiamonds and rawEvent ? z : na, title="Extreme Episode (Raw)", style=shape.diamond, location=location.absolute, color=color.red, size=size.large)
 
 
 
plot(relativePct, "Relative Return %", display=display.data_window)
 
plot(percentile, "Relative Percentile", display=display.data_window)
 
plot(volRatio, "Volatility Ratio", display=display.data_window)
 
plot(meanShift, "Mean Shift (SD)", display=display.data_window)
 
plot(float(rawEvents), "Raw Episodes", display=display.data_window)
 
plot(float(separatedEvents), "Separated Episodes", display=display.data_window)
 
 
 
// Compact dashboard: four separate forward horizons,
 
// both conditional and unconditional means, plus edge.
 
var table panel = table.new(position.top_right, 2, 18, border_width=1)
 
if barstate.islast
 
    table.clear(panel, 0, 0, 1, 17)
 
    if showPanel
 
        color bg = color.new(color.black, 15)
 
        color hdr = color.new(color.gray, 65)
 
        table.cell(panel, 0, 0, "CT MAYBE PRICE IS WRONG", text_color=color.white, bgcolor=hdr)
 
        table.cell(panel, 1, 0, "v6 | DAILY", text_color=color.white, bgcolor=hdr)
 
        table.cell(panel, 0, 1, "TARGET", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 1, targetSymbol, text_color=color.aqua, bgcolor=bg)
 
        table.cell(panel, 0, 2, "BENCHMARK", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 2, basketMode ? "CUSTOM BASKET" : directBenchmark, text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 0, 3, "STATE", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 3, state, text_color=stateColor, bgcolor=bg)
 
        table.cell(panel, 0, 4, "Z / PERCENTILE", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 4, ready ? str.tostring(z, "#.##") + " / " + str.tostring(percentile, "#.0") + "%" : "WARMUP", text_color=stateColor, bgcolor=bg)
 
        table.cell(panel, 0, 5, "REL. RETURN / PATH", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 5, (na(relativePct) ? "N/A" : str.tostring(relativePct, "#.##") + "%") + " | " + trajectory, text_color=trajectoryColor, bgcolor=bg)
 
        table.cell(panel, 0, 6, "BASKET INTEGRITY", text_color=color.white, bgcolor=bg)
 
        string integrity = basketMode ? "SYNTHETIC / FROZEN WT" : "DIRECT / ETF OR INDEX"
 
        table.cell(panel, 1, 6, integrity, text_color=basketMode ? color.orange : color.aqua, bgcolor=bg)
 
        table.cell(panel, 0, 7, "CONFIGURATION", text_color=color.white, bgcolor=bg)
 
        string coverageText = basketMode ? str.tostring(includedCount) + "/" + str.tostring(configuredCount) + " | " + str.tostring(configCoverage, "#.0") + "% OF INPUT WT" : "NO EXCLUSIONS"
 
        table.cell(panel, 1, 7, coverageText, text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 0, 8, "EPISODES RAW / SEPARATED", text_color=color.white, bgcolor=bg)
 
        table.cell(panel, 1, 8, str.tostring(rawEvents) + " / " + str.tostring(separatedEvents) + " (" + str.tostring(cooldownBars) + "D)", text_color=color.white, bgcolor=bg)
 
        if showDiagnostics
 
            table.cell(panel, 0, 9, "DISTRIBUTION", text_color=color.white, bgcolor=bg)
 
            table.cell(panel, 1, 9, distributionState, text_color=distributionUnstable ? color.orange : color.aqua, bgcolor=bg)
 
            table.cell(panel, 0, 10, "VOL RATIO / MEAN SHIFT", text_color=color.white, bgcolor=bg)
 
            table.cell(panel, 1, 10, ready ? str.tostring(volRatio, "#.##") + " / " + str.tostring(meanShift, "#.##") + " SD" : "WARMUP", text_color=color.white, bgcolor=bg)
 
        if showOutcomes
 
            table.cell(panel, 0, 11, "FORWARD RELATIVE STUDY", text_color=color.white, bgcolor=hdr)
 
            table.cell(panel, 1, 11, "EVENT / BASE / EDGE (pp)", text_color=color.white, bgcolor=hdr)
 
            for k = 0 to 3
 
                [eventMean, baseMean, edge, win, ne, nb, eventSD, baseSD] = f_stats(k)
 
                int h = array.get(horizons, k)
 
                int r = k + 12
 
                string rowLabel = str.tostring(h) + "D | N=" + str.tostring(ne) + " | W=" + (na(win) ? "--" : str.tostring(win, "#.0") + "%")
 
                string rowValue = na(eventMean) ? "NO EVENT SAMPLE" : str.tostring(eventMean, "#.2") + " / " + str.tostring(baseMean, "#.2") + " / " + str.tostring(edge, "#.2")
 
                color rowColor = ne < minEventSamples ? color.orange : edge > 0 ? color.lime : color.red
 
                table.cell(panel, 0, r, rowLabel, text_color=color.white, bgcolor=bg)
 
                table.cell(panel, 1, r, rowValue, text_color=rowColor, bgcolor=bg)
 
            table.cell(panel, 0, 16, "RESEARCH CAUTION", text_color=color.white, bgcolor=bg)
 
            table.cell(panel, 1, 16, "N < " + str.tostring(minEventSamples) + " = SMALL SAMPLE", text_color=color.orange, bgcolor=bg)
        table.cell(panel, 0, 17, "RESEARCH STATUS", text_color=color.white, bgcolor=bg)
        table.cell(panel, 1, 17, "IN-SAMPLE / NOT VALIDATED", text_color=color.orange, bgcolor=bg)
 
 
 
// Observational alert only, never a BUY/SELL.
 
alertcondition(rawEvent, title="CT Raw Extreme Relative Discount", message="CT — Maybe the Price Is Wrong™ v6: new raw extreme-discount episode.")
 
alertcondition(studyEvent, title="CT Separated Extreme Research Event", message="CT — Maybe the Price Is Wrong™ v6: separated extreme event eligible for forward study.")

← 返回列表