IV Rank and Base Breakout Screener for Covered Calls [tfox2791]

tfox2791 · study · 493 行 · 点赞 6 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tfox2791
 
//@version=6
// ============================================================================
//  IV JUICE HUNTER — Rich Volatility on a Clean IBD Setup
//  Finds names where the premium is rich AND the chart is worth owning, then
//  gates on what makes a name actually tradeable for weekly covered calls:
//  liquidity, share price, and weekly-contract availability.
//
//  Two engines, scored separately so you can see which half is carrying:
//    IV JUICE  — how rich is the volatility, and does it fund the weekly target
//    SETUP     — EMA stack, base quality, and distance to the breakout pivot
//  "Combined Score" blends them and is the column to sort on.
//
//  WHY NOT JUST SORT BY IV?
//  Raw IV leaders are adverse selection. A name sits at the top of a raw-IV
//  list because something binary is about to happen to it (earnings, FDA,
//  takeover, or it is in free fall). What pays is vol that is high RELATIVE
//  TO ITS OWN HISTORY, on a name that is not falling apart, with no event
//  inside the expiry window.
//
//  METHOD — IV side:
//   1. Realized vol from raw log returns — Yang-Zhang by default, because it
//      is the only common estimator that prices in overnight gaps, and gaps
//      are where single-stock vol actually lives.
//   2. Scale by an IV-premium multiplier (the variance risk premium: options
//      habitually trade above realized vol; 1.10–1.25 typical for liquid
//      names). That product is the IV PROXY this script ranks on.
//   3. IV Rank + IV Percentile of that proxy against its own trailing year.
//   4. Price a call at your target delta / DTE with Black-Scholes (normal CDF
//      and inverse CDF implemented natively in Pine, r = q = 0) to convert
//      vol into an estimated weekly ROI you can compare to your 1–2% target.
//
//  METHOD — Setup side (IBD vocabulary):
//   5. EMA STACK. 21 > 50 > 200 is the healthy configuration. The script
//      reports the stack as state / age / spread, and separately enforces a
//      price gate (above the 50, the 200, either, or both — your choice).
//   6. BASE. Pivot = the highest high of the lookback, excluding today, so a
//      breakout can be detected as price crossing it. Base depth is measured
//      pivot-to-low: IBD's rough guides are ≤15% for a flat base and ≤33%
//      for a cup. Deep bases are repaired damage, not accumulation.
//   7. PROXIMITY. "Dist to pivot %" is the headline setup number — how far
//      under the breakout price you are. Approaching (inside your window),
//      in the buy zone (0 to +5% past the pivot, IBD's actionable range), or
//      broken out today on a volume surge (IBD wants ~1.4x average).
//   8. TIGHTNESS. Range contraction before a breakout is the supply-drying-up
//      tell. Lower is better.
//
//  RULE OF THUMB the math produces (7 DTE, 0.30 delta, 1.15 IV mult):
//      ~35% vol → ~1.0%/wk    ~50% vol → ~1.5%/wk    ~70% vol → ~2.0%/wk
//  (verified numerically against an independent implementation: 1.03/1.45/2.00)
//
//  WHAT THE MATH SAYS — two results that shape how to USE this screen:
//   • "Prem/risk ratio" is ~0.18 at 0.30 delta REGARDLESS of vol level. Both
//     the premium and the 1-sigma move scale with sigma·sqrt(T), so the ratio
//     is scale-invariant. Translation: at a fixed delta, hunting higher IV
//     does NOT improve risk-adjusted return — it scales premium and risk
//     together. Higher IV buys more income per dollar of capital, not a
//     better trade. That is why this ranks on IV RANK (vol rich vs its own
//     history, which mean-reverts) and on SETUP, not on raw IV.
//   • IV Rank is mathematically UNAFFECTED by the IV premium multiplier — a
//     constant scale factor cancels out of (x - min) / (max - min). Tune
//     ivMult to calibrate the premium estimates; it will not move your IV
//     Rank filter by a basis point.
//
//  ⚠ THE HONEST LIMITS — read these before trusting a row:
//    • There is no implied volatility in Pine. None. This is realized vol
//      wearing an IV costume. Good ranking signal, bad quote. Always confirm
//      the real chain and real IV before placing anything.
//    • There is no options metadata in Pine either — Pine cannot know which
//      symbols have weekly contracts. See "WEEKLIES" below.
//    • Realized vol is backward-looking by construction. It UNDERSTATES vol
//      going into a scheduled event and OVERSTATES it coming out. That is
//      what the "Earnings soon" column is for.
//    • Base detection here is a HIGHEST-HIGH pivot, not pattern recognition.
//      It will not tell a cup-with-handle from a flat base from a messy
//      consolidation. Depth, length and tightness are given so you can judge
//      that yourself on the chart. Treat it as a shortlist, not a verdict.
//
//  WEEKLIES — pick your method in the inputs (most accurate first):
//   A. Curate the watchlist.  The Pine Screener runs on a watchlist you
//      choose. Build one from the CBOE weeklies list once and the problem is
//      solved exactly, with no script logic. Set mode to "Off".
//   B. Paste the ticker list.  Mode "Ticker list" + paste symbols into the
//      Weekly-options list input (commas, spaces or newlines all fine).
//   C. Dollar-volume proxy.  Mode "Dollar volume proxy" (the default, because
//      it needs no maintenance). Approximate — it WILL produce both false
//      positives and false negatives at the edges.
//
//  HOW TO USE IN THE PINE SCREENER:
//   1. Paste into Pine Editor, Save, star it to add it to favorites.
//   2. Open the Screener, switch to the Pine tab, pick this script.
//   3. Choose a watchlist + the Daily timeframe.
//   4. Sort DESCENDING on "Combined Score" — that is the ranked answer.
//      Then filter. Common setups:
//        - "All screens pass"   = 1    (everything below, in one flag)
//      Or build it up yourself:
//        - "Liquidity OK"       = 1    (avg volume ≥ your share floor)
//        - "Price OK"           = 1    (close ≥ your price floor)
//        - "Weeklies OK"        = 1    (per the mode you chose)
//        - "IV rank OK"         = 1    (IV Rank ≥ your floor)
//        - "Funds target"       = 1    (est. weekly premium ≥ your % target)
//        - "EMA gate OK"        = 1    (above the 50 / 200 per your mode)
//        - "Earnings soon"      = 0    (no event inside the window)
//        - "Falling knife"      = 0    (not in a confirmed downtrend)
//      THE SETUP HUNT — the reason this script exists:
//        - "Approaching pivot"  = 1    (coiled under the breakout price)
//        - "In buy zone"        = 1    (0 to +5% past the pivot, actionable)
//        - "Breakout today"     = 1    (crossed the pivot this bar)
//        - "EMA stacked"        = 1    (21 > 50 > 200)
//        - "Base OK"            = 1    (base depth within your limit)
//      Quality stacking:
//        - "Dist to pivot %"    0 to 5   = coiled and close
//        - "Base depth %"       lower = tighter accumulation
//        - "Tightness %"        lower = supply drying up
//        - "Vol surge x"        ≥ 1.4 on a breakout bar (IBD guideline)
//        - "Prem/risk ratio"    higher = more premium per unit of 1-sigma risk
//        - "Avg $ vol (M)"      higher = tighter spreads in the real chain
//
//  NOTES:
//   • 1/0 and %-value columns plot to the Data Window so they stay available
//     to the screener without distorting the chart's price scale.
//   • "Earnings soon" is blank (na) when the feed has no upcoming earnings
//     date — blank means "unknown", NOT "safe".
//   • IV Rank needs ~273 daily bars (252 rank window + 21 vol lookback) and
//     the 200 EMA needs 200. The Screener carries roughly 500 bars on Daily,
//     so this is fine there, but these columns are structurally blank on
//     young symbols and on low timeframes. Run this on Daily.
//   • Column names are an API — saved screener filters depend on them.
// ============================================================================
 
indicator("IV Juice Hunter [tfox2791]", overlay=true, max_lines_count=100, max_labels_count=100)
 
// ── Inputs: volatility engine ───────────────────────────────────────────────
volModel = input.string("Yang-Zhang", "Realized vol estimator", options=["Yang-Zhang", "Parkinson", "Garman-Klass", "Close-to-Close"], group="Volatility engine")
volLen   = input.int(21, "Vol lookback (bars)", minval=5, group="Volatility engine")
ivMult   = input.float(1.15, "IV premium multiplier", minval=0.5, maxval=3.0, step=0.05, group="Volatility engine", tooltip="The variance risk premium. Options habitually trade above realized vol; 1.10–1.25 is typical for liquid names. Does NOT affect IV Rank — a constant cancels out of the rank formula.")
rankLen  = input.int(252, "IV Rank / Percentile window (bars)", minval=20, group="Volatility engine", tooltip="252 = one trading year.")
 
// ── Inputs: option to price ─────────────────────────────────────────────────
dteDays  = input.int(7, "Days to expiry (calendar)", minval=1, maxval=60, group="Option pricing")
tgtDelta = input.float(0.30, "Target call delta", minval=0.10, maxval=0.50, step=0.05, group="Option pricing", tooltip="0.50 = at-the-money. 0.30 is a common covered-call strike.")
wkTarget = input.float(1.0, "Weekly premium target (%)", minval=0.1, step=0.1, group="Option pricing")
 
// ── Inputs: trend structure ─────────────────────────────────────────────────
emaFastLen = input.int(21,  "EMA fast",   minval=1, group="Trend structure")
emaMidLen  = input.int(50,  "EMA mid",    minval=1, group="Trend structure")
emaSlowLen = input.int(200, "EMA slow",   minval=1, group="Trend structure")
emaGate    = input.string("Above either 50 or 200", "Price gate", options=["Above either 50 or 200", "Above both 50 and 200", "Above 50 only", "Above 200 only", "Off"], group="Trend structure", tooltip="The hard trend requirement folded into 'All screens pass'.")
reqStacked = input.bool(false, "Also require EMAs stacked (21 > 50 > 200)", group="Trend structure", tooltip="Strict. Leave off to let 'EMA stacked' be a ranking input rather than a gate.")
 
// ── Inputs: base & breakout ─────────────────────────────────────────────────
baseLen      = input.int(60, "Base lookback (bars)", minval=10, group="Base & breakout", tooltip="Bars used to find the pivot (highest high, excluding today). 60 daily bars ≈ a 12-week base.")
maxBaseDepth = input.float(33.0, "Max base depth (%)", minval=1.0, group="Base & breakout", tooltip="Pivot-to-low depth. IBD rough guides: ≤15% flat base, ≤33% cup. Deeper = repaired damage, not accumulation.")
approachPct  = input.float(5.0, "'Approaching pivot' window (%)", minval=0.1, group="Base & breakout", tooltip="How far under the pivot still counts as coiled.")
buyZonePct   = input.float(5.0, "Buy zone above pivot (%)", minval=0.1, group="Base & breakout", tooltip="IBD's actionable range is 0 to +5% past the pivot.")
tightLen     = input.int(10, "Tightness lookback (bars)", minval=3, group="Base & breakout")
volSurgeMin  = input.float(1.4, "Breakout volume surge (x avg)", minval=1.0, step=0.1, group="Base & breakout", tooltip="IBD wants roughly 1.4x the 50-day average volume on a breakout bar.")
 
// ── Inputs: hard screens ────────────────────────────────────────────────────
minPrice   = input.float(15.0, "Min share price ($)", minval=0.0, group="Hard screens")
minShares  = input.int(1000000, "Min avg daily volume (shares)", minval=0, group="Hard screens")
liqLen     = input.int(50, "Volume average length", minval=5, group="Hard screens")
minIVRank  = input.float(50.0, "Min IV Rank", minval=0.0, maxval=100.0, group="Hard screens")
earnWindow = input.int(7, "Earnings warning window (days)", minval=1, group="Hard screens")
 
// ── Inputs: weekly contracts ────────────────────────────────────────────────
wkMode = input.string("Dollar volume proxy", "Weekly-options check", options=["Dollar volume proxy", "Ticker list", "Off"], group="Weekly contracts", tooltip="Pine has no options metadata. 'Off' assumes you curated the watchlist (most accurate). 'Ticker list' matches the list below (exact). 'Dollar volume proxy' approximates by liquidity (no maintenance).")
minDolVol = input.float(50.0, "Proxy: min avg dollar volume ($M/day)", minval=0.0, group="Weekly contracts", tooltip="Weekly contracts track institutional liquidity closely. $50M/day captures most of the weeklies universe. Approximate.")
weekliesRaw = input.text_area("AAPL,MSFT,NVDA,AMZN,META,GOOGL,TSLA,AMD,NFLX,AVGO,INTC,MU,COIN,PLTR,SMCI,MARA,RIOT,SOFI,F,BAC,JPM,XOM,CVX,WMT,DIS,BA,CAT,GE,UBER,SHOP,SQ,PYPL,CRM,ORCL,ADBE,QCOM,TXN,MRNA,PFE,LLY,UNH,JNJ,ABBV,COST,HD,LOW,TGT,NKE,SBUX,MCD", "Weekly-options ticker list", tooltip="Used only when mode = 'Ticker list'. Commas, spaces or newlines all work. This seed list is the obvious liquid names only — replace it with the current CBOE weeklies list for real coverage.", group="Weekly contracts")
 
// ── Inputs: scoring ─────────────────────────────────────────────────────────
ivWeight = input.float(55.0, "IV weight in Combined Score (%)", minval=0.0, maxval=100.0, step=5.0, group="Scoring", tooltip="Remainder goes to the Setup score. 55/45 leans slightly toward premium richness.")
 
// ── Inputs: display ─────────────────────────────────────────────────────────
showEMAs    = input.bool(true,  "Plot EMAs",                      group="Display")
showPivot   = input.bool(true,  "Draw pivot line + label",        group="Display")
showMarks   = input.bool(true,  "Show breakout / buy-zone marks", group="Display")
showTable   = input.bool(true,  "Show readout table",             group="Display")
showBg      = input.bool(true,  "Highlight when all screens pass", group="Display")
 
// ── Helpers ─────────────────────────────────────────────────────────────────
// safe log-ratio: na instead of blowing up on zero/na prices
slog(series float _num, series float _den) =>
    _num > 0 and _den > 0 ? math.log(_num / _den) : na
 
// Normal CDF via Abramowitz & Stegun 7.1.26 erf approximation (max err ~7e-8)
f_erf(series float _x) =>
    _t = 1.0 / (1.0 + 0.3275911 * math.abs(_x))
    _y = 1.0 - (((((1.061405429 * _t - 1.453152027) * _t + 1.421413741) * _t - 0.284496736) * _t + 0.254829592) * _t) * math.exp(-_x * _x)
    _x >= 0 ? _y : -_y
 
f_ncdf(series float _x) =>
    0.5 * (1.0 + f_erf(_x / math.sqrt(2.0)))
 
// Inverse normal CDF — Beasley-Springer-Moro central region.
// Valid for p in ~[0.08, 0.92]; delta input is clamped to [0.10, 0.50].
f_invNcdf(series float _p) =>
    _y = _p - 0.5
    _r = _y * _y
    _y * (((-25.44106049637 * _r + 41.39119773534) * _r - 18.61500062529) * _r + 2.50662823884) / ((((3.13082909833 * _r - 21.06224101826) * _r + 23.08336743743) * _r - 8.47351093090) * _r + 1.0)
 
// ── Calculations: realized volatility (annualized, decimal) ─────────────────
ANN = math.sqrt(252.0)
 
// per-bar log terms — computed unconditionally (ta.* consistency)
rCC = slog(close, close[1])        // close-to-close return
rHL = slog(high, low)              // Parkinson term
rCO = slog(close, open)            // open-to-close
rOC = slog(open, close[1])         // overnight gap
rHC = slog(high, close)
rHO = slog(high, open)
rLC = slog(low, close)
rLO = slog(low, open)
 
volCC = ta.stdev(rCC, volLen) * ANN
 
parkTerm = rHL * rHL
volPark  = math.sqrt(ta.sma(parkTerm, volLen) / (4.0 * math.log(2.0))) * ANN
 
// Garman-Klass (clamp mean at zero before sqrt — can go slightly negative)
gkTerm = 0.5 * rHL * rHL - (2.0 * math.log(2.0) - 1.0) * rCO * rCO
gkMean = ta.sma(gkTerm, volLen)
volGK  = math.sqrt(math.max(gkMean, 0.0)) * ANN
 
// Yang-Zhang (overnight variance + k·open-to-close + (1-k)·Rogers-Satchell)
varO   = ta.variance(rOC, volLen)
varC   = ta.variance(rCO, volLen)
rsTerm = rHC * rHO + rLC * rLO
varRS  = ta.sma(rsTerm, volLen)
kYZ    = 0.34 / (1.34 + (volLen + 1.0) / (volLen - 1.0))
volYZ  = math.sqrt(math.max(varO + kYZ * varC + (1.0 - kYZ) * varRS, 0.0)) * ANN
 
rv = volModel == "Yang-Zhang" ? volYZ : volModel == "Parkinson" ? volPark : volModel == "Garman-Klass" ? volGK : volCC
 
// ── Calculations: the IV proxy and its rank ─────────────────────────────────
ivProxy = rv * ivMult
 
ivHi   = ta.highest(ivProxy, rankLen)
ivLo   = ta.lowest(ivProxy, rankLen)
ivRank = not na(ivHi) and not na(ivLo) and (ivHi - ivLo) != 0 ? (ivProxy - ivLo) / (ivHi - ivLo) * 100.0 : na
 
// IV Percentile: share of the trailing year spent BELOW today's vol.
// Different question from rank, and more robust to a single vol spike.
ivPctile = ta.percentrank(ivProxy, rankLen)
 
// Vol regime: fast vs slow close-to-close vol (rising → richer premium ahead)
rvFast   = ta.stdev(rCC, 10) * ANN
volRatio = not na(volCC) and volCC != 0 ? rvFast / volCC : na
 
// ── Calculations: Black-Scholes premium estimate ────────────────────────────
sigma = ivProxy
T     = dteDays / 365.0
sigT  = sigma * math.sqrt(T)
 
d1atm   = sigT / 2.0
premATM = not na(sigT) and sigT > 0 ? (f_ncdf(d1atm) - f_ncdf(-d1atm)) * 100.0 : na
 
// Target-delta call: solve the strike implied by the delta, then price it
d1tgt   = f_invNcdf(tgtDelta)                                  // negative for OTM deltas
kOverS  = not na(sigT) and sigT > 0 ? math.exp(sigT * sigT / 2.0 - d1tgt * sigT) : na
premTgt = not na(kOverS) ? (f_ncdf(d1tgt) - kOverS * f_ncdf(d1tgt - sigT)) * 100.0 : na
otmPct  = not na(kOverS) ? (kOverS - 1.0) * 100.0 : na         // strike distance above spot
premDollars = not na(premTgt) ? close * premTgt : na           // est. $ per 100-share contract
 
oneSigma   = not na(sigT) ? sigT * 100.0 : na
premToRisk = not na(premTgt) and not na(oneSigma) and oneSigma != 0 ? premTgt / oneSigma : na
 
// ── Calculations: trend structure (EMA stack) ───────────────────────────────
emaFast = ta.ema(close, emaFastLen)
emaMid  = ta.ema(close, emaMidLen)
emaSlow = ta.ema(close, emaSlowLen)
 
above50  = not na(emaMid)  and close > emaMid
above200 = not na(emaSlow) and close > emaSlow
 
emaGateOK = emaGate == "Off" ? true : emaGate == "Above 50 only" ? above50 : emaGate == "Above 200 only" ? above200 : emaGate == "Above both 50 and 200" ? (above50 and above200) : (above50 or above200)
 
// 21 > 50 > 200 — the healthy configuration
emaStacked = not na(emaSlow) and emaFast > emaMid and emaMid > emaSlow
stackPartial = not na(emaMid) and emaFast > emaMid        // halfway there
stackBars  = ta.barssince(not emaStacked)                 // how long the stack has held
stackAge   = not na(stackBars) and emaStacked ? stackBars : na
// Spread from fast to slow — a widening stack is a trending stack
stackGapPct = not na(emaSlow) and emaSlow != 0 ? (emaFast - emaSlow) / emaSlow * 100.0 : na
 
extPct = not na(emaFast) and emaFast != 0 ? (close - emaFast) / emaFast * 100.0 : na
 
// Falling knife — a covered-call writer's real enemy
fallingKnife = not na(emaSlow) and close < emaMid and emaMid < emaSlow
 
// ── Calculations: base & breakout ───────────────────────────────────────────
// Pivot excludes today ([1]) so a breakout reads as price CROSSING the level.
pivot   = ta.highest(high, baseLen)[1]
baseLow = ta.lowest(low, baseLen)[1]
 
baseDepthPct   = not na(pivot) and pivot != 0 ? (pivot - baseLow) / pivot * 100.0 : na
distToPivotPct = not na(pivot) and pivot != 0 ? (pivot - close) / pivot * 100.0 : na   // + = below pivot
baseOK         = not na(baseDepthPct) and baseDepthPct <= maxBaseDepth
 
approaching   = not na(distToPivotPct) and distToPivotPct > 0 and distToPivotPct <= approachPct
inBuyZone     = not na(pivot) and close > pivot and close <= pivot * (1.0 + buyZonePct / 100.0)
// ta.crossover is stateful, so it must run on EVERY bar. v6's `and` short-
// circuits, which would skip it whenever pivot is na — compute it globally
// and gate only the USE.
xUpPivot      = ta.crossover(close, pivot)
breakoutToday = not na(pivot) and xUpPivot
 
// Bars since the base high was set — a proxy for how long the base has built
barsSinceHi = ta.barssince(high >= pivot)
baseAge     = not na(barsSinceHi) ? barsSinceHi : na
 
// Tightness: recent range as a % of price. Lower = supply drying up.
tightHi      = ta.highest(high, tightLen)
tightLo      = ta.lowest(low, tightLen)
tightnessPct = close != 0 and not na(tightHi) and not na(tightLo) ? (tightHi - tightLo) / close * 100.0 : na
 
// ── Calculations: hard screens ──────────────────────────────────────────────
avgVol     = ta.sma(volume, liqLen)
dollarVolM = not na(avgVol) ? close * avgVol / 1000000.0 : na
liqOK      = not na(avgVol) and avgVol >= minShares
priceOK    = close >= minPrice
ivRankOK   = not na(ivRank) and ivRank >= minIVRank
volSurge   = not na(avgVol) and avgVol != 0 ? volume / avgVol : na
surgeOK    = not na(volSurge) and volSurge >= volSurgeMin
 
// Weekly contracts — Pine has no options metadata, so this is mode-dependent.
// Normalize the pasted list once: strip whitespace, upper-case, comma-fence it
// so a substring match cannot hit a partial ticker (",F," never matches ",FB,").
var string wkNorm = "," + str.upper(str.replace_all(str.replace_all(str.replace_all(weekliesRaw, " ", ""), "\n", ""), "\t", "")) + ","
inWkList = str.contains(wkNorm, "," + str.upper(syminfo.ticker) + ",")
proxyOK  = not na(dollarVolM) and dollarVolM >= minDolVol
weekOK   = wkMode == "Off" ? true : wkMode == "Ticker list" ? inWkList : proxyOK
 
meetsTarget = not na(premTgt) and premTgt >= wkTarget
 
// Earnings proximity — guarded; the feed may not supply a date
earnMs   = earnings.future_time
earnDays = not na(earnMs) ? (earnMs - time) / 86400000.0 : na
earnSoon = not na(earnDays) and earnDays >= 0 and earnDays <= earnWindow
 
// ── Calculations: scores ────────────────────────────────────────────────────
// IV Juice (0–100): weighted toward RICHNESS (IV Rank) over raw vol, because
// raw vol leaders are adverse selection.
//   40 IV Rank + 30 premium vs target (capped 1.5x) + 15 liquidity + 15 trend
rankComponent  = not na(ivRank) ? ivRank / 100.0 * 40.0 : 0.0
premComponent  = not na(premTgt) ? math.min(premTgt / wkTarget, 1.5) / 1.5 * 30.0 : 0.0
liqComponent   = not na(dollarVolM) ? math.min(dollarVolM / 100.0, 1.0) * 15.0 : 0.0
trendComponent = fallingKnife ? 0.0 : above50 ? 15.0 : 8.0
ivJuice = rankComponent + premComponent + liqComponent + trendComponent
 
// Setup (0–100): the IBD half.
//   30 EMA stack + 25 proximity to pivot + 20 base quality + 15 tightness + 10 volume
stackScore = emaStacked ? 30.0 : stackPartial ? 15.0 : 0.0
// Proximity: full marks inside the buy zone, scaled down across the approach window
proxScore = inBuyZone ? 25.0 : not na(distToPivotPct) and distToPivotPct > 0 and distToPivotPct <= approachPct ? (1.0 - distToPivotPct / approachPct) * 25.0 : 0.0
// Base quality: shallower is better, scaled against your max
baseScore = not na(baseDepthPct) and baseDepthPct <= maxBaseDepth ? (1.0 - baseDepthPct / maxBaseDepth) * 20.0 : 0.0
// Tightness: 15% range over the window scores zero, 0% scores full
tightScore = not na(tightnessPct) ? math.max(0.0, 1.0 - tightnessPct / 15.0) * 15.0 : 0.0
volScore   = not na(volSurge) ? math.min(volSurge / volSurgeMin, 1.0) * 10.0 : 0.0
setupScore = stackScore + proxScore + baseScore + tightScore + volScore
 
combined = ivJuice * (ivWeight / 100.0) + setupScore * (1.0 - ivWeight / 100.0)
 
allPass = priceOK and liqOK and weekOK and ivRankOK and meetsTarget and emaGateOK and not fallingKnife and not earnSoon and (not reqStacked or emaStacked)
 
// ── On-chart visuals ────────────────────────────────────────────────────────
plot(showEMAs ? emaFast : na, "EMA 21",  color=color.new(color.fuchsia, 0))
plot(showEMAs ? emaMid  : na, "EMA 50",  color=color.new(color.yellow, 0))
plot(showEMAs ? emaSlow : na, "EMA 200", color=color.new(color.blue, 0), linewidth=2)
 
// Shape grammar follows the other screeners: triangles = major event,
// circles = proximity, diamonds = structure.
// display.pane keeps these OUT of the Data Window and the screener column list.
// They are chart decoration, they are gated on showMarks, and the first one would
// otherwise collide with the 1/0 "Breakout today" screener column below — two
// outputs sharing a column name, with a display toggle leaking into the data.
plotshape(showMarks and breakoutToday, "Breakout marker", shape.triangleup,
     location.belowbar, color.new(color.lime, 0), size=size.small, display=display.pane)
plotshape(showMarks and approaching and not approaching[1], "Approach marker", shape.circle,
     location.belowbar, color.new(color.aqua, 0), size=size.tiny, display=display.pane)
plotshape(showMarks and emaStacked and not emaStacked[1], "Stack formed marker", shape.diamond,
     location.belowbar, color.new(color.teal, 0), size=size.tiny, display=display.pane)
 
// Pivot line + label, drawn only on the last bar (cheap, and the screener
// ignores drawings anyway). Dashed, matching the strike optimizer's grammar.
var line  pivLine = na
var label pivLabel = na
if barstate.islast and showPivot and not na(pivot)
    line.delete(pivLine)
    label.delete(pivLabel)
    pivCol = inBuyZone ? color.lime : approaching ? color.aqua : color.gray
    pivLine := line.new(bar_index - baseLen, pivot, bar_index + 5, pivot, color=pivCol, width=1, style=line.style_dashed)
    pivLabel := label.new(bar_index + 5, pivot, "Pivot " + str.tostring(pivot, format.mintick) + "  (" + (na(distToPivotPct) ? "n/a" : str.tostring(distToPivotPct, "0.0") + "%") + ")",
         color=color.new(pivCol, 70), textcolor=pivCol, style=label.style_label_left, size=size.tiny)
 
bgcolor(showBg and allPass ? color.new(color.green, 88) : na)
 
// ── Readout table ───────────────────────────────────────────────────────────
// Same grammar as the strike optimizer: top-right, dark, color-coded cells,
// legend in the footer row.
f_col(series float _v, simple float _good, simple float _ok) =>
    na(_v) ? color.gray : _v >= _good ? color.lime : _v >= _ok ? color.yellow : color.red
 
var table tbl = table.new(position.top_right, 2, 9, bgcolor=color.new(color.black, 15), border_width=1)
if barstate.islast and showTable
    hdr  = color.new(color.gray, 60)
    rowBg = color.new(color.black, 30)
    foot = color.new(color.gray, 70)
    table.cell(tbl, 0, 0, "IV Juice Hunter", bgcolor=hdr, text_color=color.white, text_size=size.small)
    table.cell(tbl, 1, 0, allPass ? "PASS" : "—",  bgcolor=hdr, text_color=allPass ? color.lime : color.silver, text_size=size.small)
 
    table.cell(tbl, 0, 1, "Combined", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 1, str.tostring(combined, "0.0"), bgcolor=rowBg, text_color=f_col(combined, 70, 50), text_size=size.small)
 
    table.cell(tbl, 0, 2, "IV Juice / Setup", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 2, str.tostring(ivJuice, "0") + " / " + str.tostring(setupScore, "0"), bgcolor=rowBg, text_color=color.white, text_size=size.small)
 
    table.cell(tbl, 0, 3, "IV Rank", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 3, na(ivRank) ? "n/a" : str.tostring(ivRank, "0.0"), bgcolor=rowBg, text_color=f_col(ivRank, 50, 30), text_size=size.small)
 
    table.cell(tbl, 0, 4, "Est prem %/wk", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 4, na(premTgt) ? "n/a" : str.tostring(premTgt, "0.00") + "%", bgcolor=rowBg, text_color=f_col(premTgt, wkTarget, wkTarget * 0.7), text_size=size.small)
 
    table.cell(tbl, 0, 5, "Dist to pivot", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 5, na(distToPivotPct) ? "n/a" : str.tostring(distToPivotPct, "0.0") + "%", bgcolor=rowBg, text_color=inBuyZone ? color.lime : approaching ? color.aqua : color.silver, text_size=size.small)
 
    table.cell(tbl, 0, 6, "Base depth", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 6, na(baseDepthPct) ? "n/a" : str.tostring(baseDepthPct, "0.0") + "%", bgcolor=rowBg, text_color=baseOK ? color.lime : color.red, text_size=size.small)
 
    table.cell(tbl, 0, 7, "EMA 21/50/200", bgcolor=rowBg, text_color=color.silver, text_size=size.small)
    table.cell(tbl, 1, 7, emaStacked ? "stacked" : stackPartial ? "partial" : fallingKnife ? "inverted" : "mixed", bgcolor=rowBg, text_color=emaStacked ? color.lime : stackPartial ? color.yellow : color.red, text_size=size.small)
 
    table.cell(tbl, 0, 8, inBuyZone ? "IN BUY ZONE" : breakoutToday ? "BREAKOUT" : approaching ? "approaching" : "watch", bgcolor=foot, text_color=color.yellow, text_size=size.tiny)
    table.cell(tbl, 1, 8, "lime=good", bgcolor=foot, text_color=color.gray, text_size=size.tiny)
 
// ── Screener columns (Data Window keeps the chart scale clean) ──────────────
// Flags
plot(allPass ? 1 : 0,       "All screens pass",  display=display.data_window)
plot(priceOK ? 1 : 0,       "Price OK",          display=display.data_window)
plot(liqOK ? 1 : 0,         "Liquidity OK",      display=display.data_window)
plot(weekOK ? 1 : 0,        "Weeklies OK",       display=display.data_window)
plot(ivRankOK ? 1 : 0,      "IV rank OK",        display=display.data_window)
plot(meetsTarget ? 1 : 0,   "Funds target",      display=display.data_window)
plot(emaGateOK ? 1 : 0,     "EMA gate OK",       display=display.data_window)
plot(emaStacked ? 1 : 0,    "EMA stacked",       display=display.data_window)
plot(above50 ? 1 : 0,       "Above 50 EMA",      display=display.data_window)
plot(above200 ? 1 : 0,      "Above 200 EMA",     display=display.data_window)
plot(fallingKnife ? 1 : 0,  "Falling knife",     display=display.data_window)
plot(na(earnMs) ? na : (earnSoon ? 1 : 0), "Earnings soon", display=display.data_window)
 
// Setup flags — the three-layer pattern: event today / event recent / state now
plot(breakoutToday ? 1 : 0, "Breakout today",    display=display.data_window)
plot(inBuyZone ? 1 : 0,     "In buy zone",       display=display.data_window)
plot(approaching ? 1 : 0,   "Approaching pivot", display=display.data_window)
plot(baseOK ? 1 : 0,        "Base OK",           display=display.data_window)
plot(surgeOK ? 1 : 0,       "Vol surge OK",      display=display.data_window)
 
// Ranking
plot(combined,   "Combined Score", display=display.data_window)
plot(ivJuice,    "IV Juice Score", display=display.data_window)
plot(setupScore, "Setup Score",    display=display.data_window)
 
// IV numerics
plot(ivRank,          "IV Rank",             display=display.data_window)
plot(ivPctile,        "IV Percentile",       display=display.data_window)
plot(ivProxy * 100.0, "IV proxy %",          display=display.data_window)
plot(rv * 100.0,      "Realized vol %",      display=display.data_window)
plot(premTgt,         "Est prem % (delta)",  display=display.data_window)
plot(premATM,         "Est prem % (ATM)",    display=display.data_window)
plot(premDollars,     "Prem $/contract",     display=display.data_window)
plot(otmPct,          "Strike % OTM",        display=display.data_window)
plot(oneSigma,        "1-sigma move %",      display=display.data_window)
plot(premToRisk,      "Prem/risk ratio",     display=display.data_window)
plot(volRatio,        "Vol ratio fast/slow", display=display.data_window)
 
// Setup numerics
plot(distToPivotPct, "Dist to pivot %",  display=display.data_window)
plot(pivot,          "Pivot price",      display=display.data_window)
plot(baseDepthPct,   "Base depth %",     display=display.data_window)
plot(baseAge,        "Bars since high",  display=display.data_window)
plot(tightnessPct,   "Tightness %",      display=display.data_window)
plot(volSurge,       "Vol surge x",      display=display.data_window)
plot(stackGapPct,    "Stack gap %",      display=display.data_window)
plot(stackAge,       "Stack age (bars)", display=display.data_window)
plot(extPct,         "Ext vs 21EMA %",   display=display.data_window)
plot(dollarVolM,     "Avg $ vol (M)",    display=display.data_window)
 
// ── Alerts ──────────────────────────────────────────────────────────────────
alertcondition(allPass and approaching and barstate.isconfirmed, "IV Juice: coiled under pivot", "{{ticker}}: rich IV, clean trend, approaching breakout pivot")
alertcondition(allPass and breakoutToday and barstate.isconfirmed, "IV Juice: breakout today", "{{ticker}}: rich IV, clean trend, crossed the pivot")

← 返回列表