Earnings Reaction [ITA]

itamardrori_ · study · 222 行 · 点赞 16 · TradingView 原页

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

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Earnings Reaction [ITA]
//
// Thousands of people use a tool that marks the earnings date. Almost nobody
// publishes one that says what happened afterwards. A search for "post
// earnings" on this platform returns four scripts.
//
// So this marks the report and then counts the three things a trader is
// actually asking before one: how far this stock usually gaps on the day, how
// often that gap closes in the same session, and how often it is still higher
// a week later.
//
// Two decisions worth stating, because they are where a tool like this quietly
// lies:
//
//   the session   most companies report after the close, so the reaction is
//                 the session after the marked date, and that is the default.
//                 A company that reports before the open is the other case and
//                 the setting exists for it. Picking whichever of the two
//                 moved more would fit the answer to the data.
//
//   the drift     a report whose week has not finished yet is not counted as a
//                 failure, and it is not counted as a success either. It is
//                 left out of that row and the row says how many it has.
// =============================================================================
 
indicator("Earnings Reaction [ITA]", overlay = true, max_labels_count = 500)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc  = "Calculation"
whenStr  = input.string("Next Session", "The Reaction Is",
     options = ["Next Session", "Same Session"], group = grpCalc,
     tooltip = "Most companies report after the close, so the market's answer is the following session. Switch this for a company that reports before the open.")
driftLen = input.int(5, "Sessions In The Drift", minval = 1, maxval = 60, group = grpCalc,
     tooltip = "How long after the reaction the later comparison is made. Five is one trading week.")
 
grpShow   = "Display"
showBand  = input.bool(true, "Shade The Reaction And The Drift", group = grpShow)
showMark  = input.bool(true, "Mark The Report", group = grpShow)
showGap   = input.bool(true, "Label The Gap", group = grpShow)
showLevel = input.bool(true, "Draw The Pre-Report Close", group = grpShow,
     tooltip = "The level the gap would have to come back to in order to be filled.")
showStats = input.bool(true, "Show The Count", group = grpShow)
statPos   = input.string("Top Right", "Count Position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
statSizeStr = input.string("Normal", "Count Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
 
grpCol  = "Colors"
upCol   = input.color(#089981, "Gapped Up", group = grpCol)
dnCol   = input.color(#f23645, "Gapped Down", group = grpCol)
lvlCol  = input.color(color.new(#e5c56b, 20), "Pre-Report Close", group = grpCol)
bandUp  = input.color(color.new(#089981, 88), "Shading, Up", group = grpCol)
bandDn  = input.color(color.new(#f23645, 88), "Shading, Down", group = grpCol)
 
sizeOf(string s) =>
    r = size.normal
    if s == "Tiny"
        r := size.tiny
    else if s == "Small"
        r := size.small
    else if s == "Large"
        r := size.large
    else if s == "Huge"
        r := size.huge
    r
 
statSize = sizeOf(statSizeStr)
 
posOf(string s) =>
    r = position.top_right
    if s == "Top Left"
        r := position.top_left
    else if s == "Bottom Right"
        r := position.bottom_right
    else if s == "Bottom Left"
        r := position.bottom_left
    r
 
// ─── THE REPORT ──────────────────────────────────────────────────────────────
// gaps_on means this is na on every bar except the one the report lands on,
// which is exactly the event.
//
// lookahead_on, and that is deliberate. With lookahead off this function hands
// the report to the bar AFTER the report date, because the time of day is not
// known, and then "next session" lands two days out, where the gap has already
// closed. NVDA came out at an average gap of 1.1% that way. Nothing here uses
// the EPS figure itself, only the fact that a report exists on this date, and
// a date is not something a bar can peek at. The reaction is still measured
// on open, high, low and close of bars that have already happened.
eps = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on,
     barmerge.lookahead_on, ignore_invalid_symbol = true)
report = not na(eps)
 
// This counts sessions, so a session has to be a bar. On a weekly chart the
// gap and the week after it are inside the same candle and there is nothing
// left to measure.
wrongTf = not timeframe.isdaily
 
// ─── THE REACTION ────────────────────────────────────────────────────────────
isReact = (whenStr == "Next Session" ? report[1] : report) and not wrongTf and bar_index > 0
 
anchor  = close[1]                      // the last close before the market answered
gapPct  = isReact ? (open - anchor) / anchor * 100.0 : na
gapUp   = isReact and open > anchor
// A gap is filled when price trades back to the level it came from. Touching
// it is enough: the gap is closed the moment the market has been there again.
filled  = isReact and (gapUp ? low <= anchor : high >= anchor)
 
// ─── THE DRIFT, RESOLVED LATER ───────────────────────────────────────────────
var float reactClose = na
var int   driftLeft  = na
var bool  driftUp    = false
 
var int reports  = 0
var int fills    = 0
var int resolved = 0
var int higher   = 0
var float gapSum = 0.0
 
if isReact
    reports += 1
    gapSum  += math.abs(gapPct)
    if filled
        fills += 1
    reactClose := close
    driftLeft  := driftLen
    driftUp    := gapUp
 
if not na(driftLeft) and not isReact
    driftLeft -= 1
    if driftLeft <= 0
        resolved += 1
        if close > reactClose
            higher += 1
        driftLeft := na
 
// ─── THE DRAWING ─────────────────────────────────────────────────────────────
// The shaded stretch is the reaction plus the week that follows it, which is
// the whole claim in one shape. On a chart of a stock it repeats four times a
// year, and that repetition is what makes it readable at thumbnail size.
inWindow = showBand and not na(driftLeft)
bgcolor(inWindow ? (driftUp ? bandUp : bandDn) : na, title = "Reaction Window")
 
// The level the gap has to come back to. Flat for the length of the window,
// so a stepped plot rather than a straight one, which would draw a slope
// between two unrelated reports.
var float lvl = na
if isReact
    lvl := anchor
// linebr, not stepline: a stepline bridges the gap between two windows and
// drew the level across the months in between, where it means nothing.
plot(showLevel and inWindow ? lvl : na, "Pre-Report Close", color = lvlCol,
     linewidth = 1, style = plot.style_linebr)
 
// The triangle is for when the gap label is off. With the label on they sat
// on top of each other and neither could be read.
plotshape(showMark and not showGap and isReact and gapUp, "Gapped up", shape.triangleup,
     location.belowbar, color = upCol, size = size.small)
plotshape(showMark and not showGap and isReact and not gapUp, "Gapped down", shape.triangledown,
     location.abovebar, color = dnCol, size = size.small)
 
// Pushed clear of the candles. At the bar's own low or high the label sat
// among the neighbouring candles, and coloured like them it vanished into
// them: a small green box between green candles is not a label, it is a
// candle. So it sits an ATR and a half away from the bar, in gold, which no
// candle on the chart is.
lblGap = ta.atr(14) * 1.5
if showGap and isReact
    label.new(bar_index, gapUp ? low - lblGap : high + lblGap,
         (gapUp ? "+" : "") + str.tostring(gapPct, "#.#") + "%",
         style = gapUp ? label.style_label_up : label.style_label_down,
         color = #e5c56b, textcolor = #0b0e13, size = size.normal)
 
// ─── THE COUNT ───────────────────────────────────────────────────────────────
avgGap   = reports  > 0 ? gapSum / reports * 1.0 : 0.0
fillRate = reports  > 0 ? fills  / reports  * 100.0 : 0.0
upRate   = resolved > 0 ? higher / resolved * 100.0 : 0.0
 
var table stats = na
if showStats and barstate.islast
    if na(stats)
        stats := table.new(posOf(statPos), 2, 5, border_width = 1)
    table.cell(stats, 0, 0, "EARNINGS REACTION", text_color = #e5c56b, text_size = statSize)
    table.cell(stats, 1, 0, "", text_size = statSize)
 
    if wrongTf or reports == 0
        // Four rows of "no data" look like a broken script. An ETF or an index
        // has no earnings, so the honest message is that there is nothing here
        // to count, not that the count failed.
        table.cell(stats, 0, 1, wrongTf ? "Chart timeframe" : "This symbol",
             text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 1, 1, wrongTf ? "needs a daily chart" : "has no earnings reports",
             text_color = color.white, text_size = statSize)
        table.cell(stats, 0, 2, "", text_size = statSize)
        table.cell(stats, 1, 2, wrongTf ? "" : "try a stock, not an ETF or index",
             text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 0, 3, "", text_size = statSize)
        table.cell(stats, 1, 3, "", text_size = statSize)
        table.cell(stats, 0, 4, "", text_size = statSize)
        table.cell(stats, 1, 4, "", text_size = statSize)
    else
        table.cell(stats, 0, 1, "Reports", text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 1, 1, str.tostring(reports), text_color = color.white, text_size = statSize)
        table.cell(stats, 0, 2, "Average gap", text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 1, 2, reports > 0 ? str.tostring(avgGap, "#.#") + "%" : "no data",
             text_color = color.white, text_size = statSize)
        table.cell(stats, 0, 3, "Gap filled same day", text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 1, 3, reports > 0 ? str.tostring(fillRate, "#.#") + "%" : "no data",
             text_color = color.white, text_size = statSize)
        table.cell(stats, 0, 4, "Higher " + str.tostring(driftLen) + " days later",
             text_color = color.new(color.white, 25), text_size = statSize)
        table.cell(stats, 1, 4, resolved > 0 ? str.tostring(upRate, "#.#") + "%  of " + str.tostring(resolved) : "no data",
             text_color = upRate >= 50 ? upCol : dnCol, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(isReact, "Earnings reaction",
     "This session is the market's reaction to an earnings report.")
alertcondition(isReact and filled, "Earnings gap filled",
     "The earnings gap was filled in the same session.")

← 返回列表