YURI Ratio Attribution Engine

yuri_zyt · study · 334 行 · 点赞 1 · 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/
// © yuri_zyt
 
//@version=6
indicator("YURI Ratio Attribution Engine", "YURI RAE", overlay = false, precision = 2)
 
// One market divided by another is a single number that costs two to make, and
// the division throws away the half that says which of the two moved. This
// engine keeps that half.
//
//   the share     Each series' log change over the attribution window, and the
//                 numerator's share of the two in absolute terms.
//   the distance  Where the ratio sits against its own trailing mean, as a
//                 percentage, cut into three states by two edges.
//
// Be precise about what the share is. It measures which series moved further,
// not which one drove the ratio. Both legs up 5 percent, and the numerator up 5
// against the denominator down 5, both read 50, and those are opposite events
// for the ratio. The two raw moves are printed beside the share for that reason,
// so it can be taken apart by eye rather than trusted.
//
// Why the share is worth the arithmetic, measured on the default pair over 6551
// daily bars from 2000-08-30 to 2026-09-18, 6423 of which read. On the 407
// twenty day windows where the ratio moved less than half a log point, the
// widest is 2009-01-06: the numerator up 14.47 log points, the denominator up
// 14.25, the ratio up 0.23. A chart of the ratio alone shows a flat line across
// those twenty days and the flat line is correct. It is also two markets that
// both moved about fifteen percent. From the other side, the 1095 windows where
// the ratio moved between 4 and 6 log points carry shares from 0 to 100, with
// quartiles at 29 and 77. One size of ratio move, most of the splits behind it.
//
// Fifty is an even split and is arithmetic, rather than this pair's neutral
// point. The share's median here is 58.2 with quartiles at 38.3 and 76.1, as the
// numerator is the more volatile of the two series. That is what the reference
// median in the table is for, and it is why the number of days behind it is
// printed next to it.
//
// The share and the distance are two readings rather than one, and that was
// checked by asking whether either is computable from the other before any
// correlation was looked at: holding the share inside a five point bin leaves
// 96% of the distance's spread standing. Their rank correlation is +0.056, and
// since the share is taken over overlapping twenty day windows the 6423 bars
// hold about 321 independent blocks, which puts about 0.056 of standard error on
// that figure. So it is one standard error from zero and no relation between the
// two is claimed in either direction.
//
// An earlier version of this file drew a second line, the ratio's move as a
// share of the legs' combined motion. It was removed: it is |2 x share - 100|
// when the legs move the same way and 100 when they move opposite ways, an
// identity rather than a reading, and the rank correlation that let it through
// was blind to the fold. The arithmetic is kept in the verification harness so
// that it does not come back.
//
// None of this is told to imply anything about the days after it. The default
// pair gets read as a macro gauge all over the place; that reading goes untested
// here. Orders, exits, filters and alerts are all absent, and the chart's price
// is not consulted at any point. The chart lends a row of bars, nothing more.
//
// Timing. Daily closes underlie every number below. An open bar carries a
// reading that travels with it and fixes at the close; a closed bar is left
// alone from then on. No stored list can take more than one entry per day of the
// requested series, and Pine restores each list to its previous bar's committed
// contents on every recalculation, so ticks arriving inside an open bar leave
// them untouched. Look-ahead is off on all four requests.
 
// Data ------------------------------------------------------------------------
// Two continuous front month futures by default. A continuous contract carries
// the roll between contracts inside its own price, and a roll step lands in the
// attribution as a move of that leg, so the substitutes worth knowing about are
// the cash or CFD quotes of the same two metals, which do not roll and which
// keep a broker's calendar rather than an exchange's. Either kind works here;
// they are different series and they will not give the same numbers.
numSym = input.symbol("COMEX:HG1!", "Numerator series", group = "Data", tooltip = "The ratio is this one divided by the other. Its share of the two legs' absolute motion is the reading in the pane.")
denSym = input.symbol("COMEX:GC1!", "Denominator series", group = "Data")
 
// Windows ---------------------------------------------------------------------
baseLen = input.int(125, "Baseline window, data days", minval = 20, maxval = 1000, group = "Windows", tooltip = "The trailing mean the ratio is measured against. Half a trading year by default. Shorter holds the reading closer to one and puts fewer days outside the edges; longer lets the pair's own multi year swings into it.")
moveLen = input.int(20, "Attribution window, data days", minval = 2, maxval = 250, group = "Windows", tooltip = "The span the two leg moves are taken over. One trading month by default.")
memLen  = input.int(500, "Shares kept for the reference median", minval = 50, maxval = 2000, group = "Windows", tooltip = "Oldest first out once the list is full. The table prints the median of what is in it and the number of days it holds.")
 
// States ----------------------------------------------------------------------
// Two symmetric edges on the ratio's distance from its own mean, with no
// latching of any kind: the state is recomputed from the distance on every data
// day. Five percent on each side is round, and it is a judgement: the input
// range is wide, and no case is made anywhere here that the number is correct.
upLine = input.float(1.05, "Above at or over", minval = 0.50, maxval = 2.00, step = 0.01, group = "States")
dnLine = input.float(0.95, "Below at or under", minval = 0.50, maxval = 2.00, step = 0.01, group = "States", tooltip = "Has to sit below the upper edge. The engine refuses to read if it does not.")
 
// Display ---------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showShare = input.bool(true, "Draw the numerator share", group = "Display")
showBg    = input.bool(true, "Tint the pane by state", group = "Display")
 
// Averages a list. Do not simplify away the size test above the loop: given an
// empty array, a Pine loop bounded 0 to n - 1 walks downward from 0 to -1 rather
// than sitting the iteration out, and index -1 of an empty array is where that
// ends up.
f_mean(array<float> a) =>
    int n = array.size(a)
    float out = na
    if n > 0
        float s = 0.0
        for i = 0 to n - 1
            s += array.get(a, i)
        out := s / n
    out
 
// Sorts a duplicate and indexes it instead of calling a median builtin, which
// puts the tie and even count conventions on the page where they can be copied.
f_median(array<float> a) =>
    int n = array.size(a)
    float out = na
    if n > 0
        array<float> tmp = array.copy(a)
        array.sort(tmp, order.ascending)
        int h = int(math.floor(n / 2.0))
        out := n % 2 == 1 ? array.get(tmp, h) : (array.get(tmp, h - 1) + array.get(tmp, h)) / 2.0
    out
 
// A sign written out rather than left to a format string, because a "+" in a
// format string is a literal prefix and would print in front of a negative
// number too. The format is hardcoded, since every caller wants the same one.
f_signed(float v) =>
    (v >= 0.0 ? "+" : "-") + str.tostring(math.abs(v), "0.00")
 
// Bars on a Heikin Ashi, Renko, Kagi, Line Break, Point and Figure or Range
// chart are constructed rather than traded, and a requested series comes back in
// whatever type the chart is set to. Nothing else in this file would object: the
// status would sit at ok while each figure rested on prices nobody paid. Hence
// the first question asked.
bool stdOk = chart.is_standard
 
// Days of the requested series are what gets counted, which makes a one day bar
// a precondition. Beware that a 2D, 3D or 5D chart answers yes to isdaily, its
// multiple sitting separately in timeframe.multiplier; on a 3D chart a window of
// twenty would quietly cover sixty days while still calling itself twenty. That
// is why the multiplier is tested alongside.
bool tfOk    = timeframe.isdaily and timeframe.multiplier == 1
bool bandsOk = dnLine < upLine
 
// Four requests: a close and a bar time for each leg, none of them allowed to
// look ahead, so a historical bar gets what was knowable as it closed.
//
// Gap handling is left at Pine's default, which repeats a series' last value
// through any bar it has nothing of its own for instead of handing back na. An
// absent close is therefore rare once a symbol resolves, and the breakage that
// does occur wears no such warning: the numerator has moved to today while the
// denominator still sits on yesterday, and today over yesterday divides
// perfectly into a number about nothing. No test of the two closes would catch
// a single such bar. The two bar times exist for that and for nothing else.
float numC = request.security(numSym, "D", close, lookahead = barmerge.lookahead_off)
float denC = request.security(denSym, "D", close, lookahead = barmerge.lookahead_off)
int   numT = request.security(numSym, "D", time, lookahead = barmerge.lookahead_off)
int   denT = request.security(denSym, "D", time, lookahead = barmerge.lookahead_off)
 
// Comparison happens after each timestamp has been collapsed to its calendar
// day, so two sessions opening hours apart within one day still count as a pair
// while a genuine one day lag does not. The price of drawing the line there: two
// series whose sessions straddle midnight get stopped on every bar they have.
// Preferred to the alternative of dividing mismatched days in silence, and worth
// checking before anything else once this is on a chart.
float numDay = na(numT) ? na : math.floor(numT / 86400000.0)
float denDay = na(denT) ? na : math.floor(denT / 86400000.0)
 
// Both legs are logged, so both have to be strictly positive. A ratio on its own
// would only need the denominator to be.
bool  haveBoth = not na(numC) and not na(denC) and numC > 0.0 and denC > 0.0
bool  sameDay  = not na(numDay) and not na(denDay) and numDay == denDay
 
// Charts can hold more bars than the series they ask about. Put a daily
// exchange series on something trading all week and Saturday and Sunday come
// back repeating Friday, at which point twenty of the chart's bars would cover
// fourteen days of data. Growth of the stored lists is therefore keyed to the
// requested series showing a new day, which is what this line finds. The
// argument to na() here is an int, not a bool.
bool newDay = not na(numT) and (na(numT[1]) or numT != numT[1])
 
// This describes the chart, not the market, so a short fixed window suits it: a
// complaint arriving 500 bars late would be no use to anybody. Seven day charts
// repeat two bars in every seven, which is 29%; matched listed calendars repeat
// none at all, which is 0%; the cut sits between the two. The result feeds the
// refusal rather than a warning line, since a table of perfectly correct figures
// printed underneath a sentence saying the chart is wrong is precisely the shape
// this file is built to avoid.
float dupFlag  = newDay ? 0.0 : 1.0
float dupShare = ta.sma(dupFlag, 60) * 100.0
bool  calMiss  = not na(dupShare) and dupShare > 10.0
 
bool  dataOk   = stdOk and tfOk and bandsOk and haveBoth and sameDay and not calMiss
 
// The stored histories. Each holds values of the requested series' own days, not
// of chart bars, and each is capped at what its reading needs. The two log
// histories are one longer than the attribution window, because a change over N
// days is taken between N + 1 values.
var array<float> ratHist   = array.new<float>()
var array<float> lnNumHist = array.new<float>()
var array<float> lnDenHist = array.new<float>()
var array<float> drvHist   = array.new<float>()
 
var int   dayCount  = 0
var int   staleBars = 0
var float ratioV = na
var float baseV  = na
var float rrV    = na
var float dNumV  = na
var float dDenV  = na
var float dRatV  = na
var float drvV   = na
 
if dataOk and newDay
    dayCount += 1
    float r = numC / denC
    ratioV := r
    array.push(ratHist, r)
    if array.size(ratHist) > baseLen
        array.shift(ratHist)
    if array.size(ratHist) >= baseLen
        baseV := f_mean(ratHist)
        rrV   := baseV > 0.0 ? r / baseV : na
    else
        baseV := na
        rrV   := na
    array.push(lnNumHist, math.log(numC))
    array.push(lnDenHist, math.log(denC))
    if array.size(lnNumHist) > moveLen + 1
        array.shift(lnNumHist)
    if array.size(lnDenHist) > moveLen + 1
        array.shift(lnDenHist)
    if array.size(lnNumHist) == moveLen + 1
        // Log changes, so the two legs subtract to the ratio's own change
        // exactly rather than approximately. That identity is the whole reason
        // the split is a split and not an estimate of one.
        dNumV := (math.log(numC) - array.get(lnNumHist, 0)) * 100.0
        dDenV := (math.log(denC) - array.get(lnDenHist, 0)) * 100.0
        dRatV := dNumV - dDenV
        float pull = math.abs(dNumV) + math.abs(dDenV)
        if pull > 0.0
            drvV := math.abs(dNumV) / pull * 100.0
            array.push(drvHist, drvV)
            if array.size(drvHist) > memLen
                array.shift(drvHist)
        else
            drvV := na
    else
        dNumV := na
        dDenV := na
        dRatV := na
        drvV  := na
 
// Suspended bars get tallied instead of slipping by unrecorded, and the tally is
// published in the data window. Written as its own statement deliberately: hung
// off the preceding block as an else, it would sweep in every bar on which the
// requested series had merely not moved to a new day.
bool held = stdOk and tfOk and bandsOk and not calMiss and not dataOk and not na(ratioV)
if held
    staleBars += 1
 
// Which of the three bands this bar sits in. -1 means none of them apply.
int    rawCode  = not dataOk or na(rrV) ? -1 : rrV >= upLine ? 2 : rrV <= dnLine ? 0 : 1
string rawName  = rawCode == 2 ? "above" : rawCode == 1 ? "within" : rawCode == 0 ? "below" : "no read"
color  stateCol = rawCode == 2 ? color.orange : rawCode == 1 ? color.gray : rawCode == 0 ? color.teal : color.silver
 
// The two halves fill at different rates, so each has its own readiness test.
// The attribution wants moveLen + 1 data days where the baseline wants baseLen,
// which is why a young chart shows a share for some time before a distance.
bool baseReady = dataOk and not na(rrV)
bool moveReady = dataOk and not na(drvV)
 
// Whatever is stopping the reading gets said out loud, in testing order: chart
// type, then the setting, then the pair, then the calendar, with the two warmups
// after all of them. The first five are refusals and not warnings. Warmup is
// last because a broken chart or a reversed setting is broken from bar one and
// waiting for a window to fill will not mend either.
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not tfOk ? "needs a one day chart" : not bandsOk ? "the lower edge has to sit below the upper edge" : not haveBoth ? "no reading from " + numSym + " or " + denSym : not sameDay ? numSym + " and " + denSym + " are not on the same day here; if this shows on every bar the two symbols keep different calendars" : calMiss ? "this chart carries more bars than the series does, use one with the same sessions" : not baseReady and not moveReady ? "warming up, " + str.tostring(dayCount) + " data days of the " + str.tostring(baseLen) + " the baseline wants and the " + str.tostring(moveLen + 1) + " the attribution wants" : not baseReady ? "the attribution is reading, the baseline wants " + str.tostring(baseLen) + " data days and has " + str.tostring(dayCount) : not moveReady ? "the baseline is reading, the attribution wants " + str.tostring(moveLen + 1) + " data days and has " + str.tostring(dayCount) : "ok"
 
// One series is drawn: the numerator's portion of the legs' motion, scaled 0 to
// 100, guided at 0, 50 and 100. Note that 50 marks an even split rather than a
// neutral level, which is what the pair's own median in the table is there for.
plot(showShare and moveReady ? drvV : na, "Numerator share of motion", color.new(color.purple, 0), 2, precision = 4)
 
hline(50, "Even split", color.new(color.gray, 80), hline.style_dotted)
hline(100, "Top", color.new(color.gray, 90))
hline(0, "Bottom", color.new(color.gray, 90))
 
bgcolor(showBg and baseReady ? color.new(stateCol, 92) : na)
 
// A gate on each line here, none of them decorative. These mostly do arithmetic
// on stored values, and a stored value outlives the bar that made it, so on a
// refused chart they would go on printing something entirely believable. Two
// things do survive a refusal and are meant to: the horizontal guides drawn
// above, whose inputs are constants, and the fixed labels running down the left
// of the table. Everything with a number in it becomes a dash.
plot(dataOk ? ratioV : na, "Ratio", display = display.data_window, precision = 8)
plot(baseReady ? baseV : na, "Baseline mean", display = display.data_window, precision = 8)
plot(baseReady ? rrV : na, "Ratio over baseline", display = display.data_window, precision = 6)
plot(moveReady ? dNumV : na, "Numerator log change x100", display = display.data_window, precision = 6)
plot(moveReady ? dDenV : na, "Denominator log change x100", display = display.data_window, precision = 6)
plot(moveReady ? dRatV : na, "Ratio log change x100", display = display.data_window, precision = 6)
plot(dataOk ? numC : na, "Numerator close", display = display.data_window, precision = 6)
plot(dataOk ? denC : na, "Denominator close", display = display.data_window, precision = 6)
plot(dataOk ? dayCount * 1.0 : na, "Data days seen", display = display.data_window, precision = 0)
plot(dataOk ? staleBars * 1.0 : na, "Bars held over an unusable pair", display = display.data_window, precision = 0)
 
// "0" and "0.00" are used in preference to "#", which drops a solitary zero and
// would leave a cell showing "%" with an empty space ahead of it; a leg change
// of exactly zero does occur. Two decimals in the cells against more in the data
// window plots above is also the reason the three printed leg figures need not
// subtract exactly to each other: over this history they miss by one in the last
// place on 25.0% of read bars.
string ratioTxt = not baseReady ? "-" : f_signed((rrV - 1.0) * 100.0) + "%   " + rawName
string legsTxt  = not moveReady ? "-" : "num " + f_signed(dNumV) + "   den " + f_signed(dDenV) + "   ratio " + f_signed(dRatV)
string drvTxt   = not moveReady ? "-" : str.tostring(drvV, "0") + "% of the motion is the numerator"
string srcTxt   = not dataOk ? "-" : numSym + " over " + denSym + ", daily closes"
 
if showTable and barstate.islast
    // Taken on the final bar only. Sorting a duplicate of a list holding up to
    // two thousand entries is not worth doing every bar when nothing plotted
    // depends on the result.
    float medDrv = f_median(drvHist)
    string refTxt = not moveReady or na(medDrv) ? "-" : "median " + str.tostring(medDrv, "0") + "% over " + str.tostring(array.size(drvHist)) + " data days"
 
    var table t = table.new(position.top_right, 2, 6, border_width = 1)
    table.cell(t, 0, 0, "Ratio vs baseline", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 0, ratioTxt, text_color = color.white, bgcolor = color.new(stateCol, 80), text_size = size.small)
    table.cell(t, 0, 1, "Legs, log x100", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 1, legsTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 2, "Numerator share", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 2, drvTxt, text_color = color.white, bgcolor = color.new(color.purple, 80), text_size = size.small)
    table.cell(t, 0, 3, "Past shares", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 3, refTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 4, "Series", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 4, srcTxt, text_color = color.gray, text_size = size.small)
    table.cell(t, 0, 5, "Status", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 5, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)

← 返回列表