YURI Term Structure Engine

yuri_zyt · study · 382 行 · 点赞 3 · 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 Term Structure Engine", "YURI TSE", overlay = false, precision = 2)
 
// A near volatility index divided by a further dated one is a single number that
// says which of the two is priced higher today. On its own that number answers
// very little, because it gives the same answer on 89% of the days in this pair's
// loaded history and the exception usually does not last. This engine keeps the
// thing the ratio does not carry.
//
//   the ledger   Every completed run of each state on the loaded history goes
//                into a list: how many days it lasted. The current run's age is
//                then read as a percentile of that list, with the number of
//                completed runs printed beside it as the sample it came from.
//                That list is a record kept as the chart runs and it is not
//                recoverable from today's ratio.
//   structure    Where today's ratio sits in its own trailing history, ranked.
//   level        Where the near series' own close sits in the same window,
//                ranked the same way. Not the same measurement as the structure:
//                on the default pair and window the two ranks come out at a
//                Spearman correlation of 0.67 over 3816 ranked bars, so a high
//                level with an unremarkable structure, and the reverse, are both
//                ordinary occurrences rather than curiosities.
//
// Why the ledger is the headline rather than a garnish. Measured on the default
// pair over 5076 daily bars from 2006-07-17 to 2026-09-18, with the state edges
// at 1.00 and 0.90, the ratio sat at or above 1.00 on 555 of them. Those days
// form 152 runs, 151 of which reach the ledger and hold 553 days between them;
// the missing one is the run that was already open when the history began, which
// is dropped because its start is out of view. The median ledgered run lasted one
// day and 72% lasted two days or fewer. So "the ratio is above 1.00" and "the
// ratio has been above 1.00 for six days" are different facts about very
// different events, and only the second one needs something kept.
//
// That 72% is as much a property of the definition as of the market, and the size
// of that is measured rather than waved at. A run ends here the moment the ratio
// crosses back over the edge. Let a run survive one day on the wrong side and the
// same history gives 114 inverted runs with a median of two days and 54% lasting
// two days or fewer; at two days of slack, 97 runs, a median of three and 45%.
// Those counts include the run that was open when the history began, which the
// ledger drops, so they read one higher per state than the 151 above.
// Moving the edge instead barely moves it: 1.02 gives 69% and 1.05 gives 65%.
// The definition is left as it is, and the reader is told what it costs.
//
// The states are three, cut by two edges the user sets: inverted at or above the
// upper edge, steep at or below the lower one, flat between them. All three are
// ledgered, because a long quiet stretch is as much an event as a short loud one
// and a script that only counts one of them is a stress detector wearing a
// readout's clothes.
//
// A run's age is not a restatement of the ratio on the bar. Measured within runs
// on the default pair: Spearman +0.54 between age and ratio inside inverted runs,
// -0.55 inside steep runs, +0.12 inside flat ones. The run's extreme, on the
// other hand, is close to a restatement of its length, at +0.72 across the 151
// inverted runs and -0.89 across the 272 steep ones. The steep figure is past the
// line the other three sit under, so the extreme is printed as a raw number in
// the table and is neither ranked nor drawn.
//
// What this will not do is say what any of it means for what happens next. There
// is no signal here, no entry, no exit, no filter and no alert. A percentile of
// a run length is a description of the run, and the description is of the past
// runs on this chart.
//
// On timing. Everything the engine holds is a function of daily closing values.
// The bar that is forming moves as it forms and settles when it closes; a bar
// that has closed is not rewritten afterwards. The ledger advances at most once
// per day of the requested series: a run gains a day on the bar where that series
// changes day, and the ledger is rebuilt from the previous bar's committed state
// on each recalculation, so the tick path inside a forming bar adds nothing to it.
// Both external series are pulled with lookahead off.
 
// Data ------------------------------------------------------------------------
nearSym = input.symbol("CBOE:VIX", "Near series", group = "Data", tooltip = "The shorter dated of the two. The ratio is this one divided by the far one.")
farSym  = input.symbol("CBOE:VIX3M", "Far series", group = "Data")
 
// States ----------------------------------------------------------------------
// 1.00 is parity, the point where the near series is priced at the far one, and
// it is arithmetic rather than a chosen threshold. 0.90 is a round distance below
// it and is the one edge here that is a judgement; it is exposed, it has a wide
// range, and nothing in this file argues that it is the right number.
invLine  = input.float(1.00, "Inverted at or above", minval = 0.50, maxval = 2.00, step = 0.01, group = "States")
calmLine = input.float(0.90, "Steep at or below", minval = 0.50, maxval = 2.00, step = 0.01, group = "States", tooltip = "Has to sit below the inverted edge. The engine refuses to read if it does not.")
 
// Ranking ---------------------------------------------------------------------
lvlLen = input.int(1260, "Ranking window, data days", minval = 100, maxval = 5000, group = "Ranking", tooltip = "How much history the structure rank and the level rank are measured against. Nothing is ranked until this many days of the series have been seen.")
 
// Ledger ----------------------------------------------------------------------
maxRuns = input.int(500, "Runs the ledger holds per state", minval = 20, maxval = 2000, group = "Ledger", tooltip = "Oldest first out once the list is full. On the default pair the loaded history produces fewer runs than this in every state, so the cap does not engage.")
minRuns = input.int(20, "Completed runs before the ledger reads", minval = 5, maxval = 200, group = "Ledger")
 
// Display ---------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showAge   = input.bool(true, "Draw the run age percentile", group = "Display")
showLevel = input.bool(true, "Draw the level percentile", group = "Display")
showFill  = input.bool(true, "Shade between level and structure", group = "Display")
showBg    = input.bool(true, "Tint the pane by state", group = "Display")
 
// The share of a list that sits at or below a value, as a percentage. The n > 0
// guard is load bearing rather than defensive: a for loop written 0 to n - 1 on
// an empty list runs 0 then -1 in Pine, counting down instead of not running, and
// the second pass would read index -1 of an empty array.
f_share(array<float> a, float v) =>
    int n = array.size(a)
    int c = 0
    if n > 0
        for i = 0 to n - 1
            if array.get(a, i) <= v
                c += 1
    n > 0 ? c * 100.0 / n : na
 
// Median by sorting a copy, rather than through a median builtin, so the tie and
// even length conventions are visible in the file and can be transcribed exactly.
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
 
f_longest(array<float> a) =>
    int n = array.size(a)
    float out = na
    if n > 0
        out := array.max(a)
    out
 
// A Heikin Ashi, Renko, Kagi, Line Break, Point and Figure or Range chart is
// refused before anything else, and the reason is specific to a script that
// reads two other symbols. request.security serves the requested symbol under
// the chart's own type, so on such a chart neither close below is the close the
// exchange printed: both are constructions, the ratio between them is a ratio of
// two constructions, and the ledger fills with the run lengths of a quantity the
// two exchanges did not quote. Every other test in this file passes there. The
// timeframe is right, the edges are in order, the pair resolves, the two bar
// times agree, and the status line reads ok while the whole record is built out
// of prices nothing traded at. It is the one refusal a reader cannot spot from
// the pane on their own, which is why it is tested first.
//
// The method counts days of the requested series against a distribution of past
// days, so a chart bar has to be a day. timeframe.isdaily is true on a 2D, 3D and
// 5D chart as well, with the multiple living in timeframe.multiplier, and on such
// a chart a run of six chart bars would be eighteen days while the ledger it is
// compared against was built the same way, which is coherent and is not what the
// table would be saying. Both halves of the test are needed, and the same line
// turns away a tick chart, where timeframe.isdaily is false.
bool stdOk   = chart.is_standard
bool tfOk    = timeframe.isdaily and timeframe.multiplier == 1
bool bandsOk = calmLine < invLine
 
// Both series and both of their own bar times, all with lookahead off, so a
// historical bar is served the value that was available when it closed.
//
// These requests use Pine's default gap handling, which repeats the previous
// value on a bar the requested series has no data for rather than returning na.
// So a close here is rarely absent once a symbol resolves, and the failure that
// actually happens is not an absent value at all: it is the two series landing on
// different days, today's near over yesterday's far, arithmetic that works
// perfectly and means nothing. Checking the closes would pass every one of those
// bars. That is the only reason both bar times are requested.
float nearC = request.security(nearSym, "D", close, lookahead = barmerge.lookahead_off)
float farC  = request.security(farSym, "D", close, lookahead = barmerge.lookahead_off)
int   nearT = request.security(nearSym, "D", time, lookahead = barmerge.lookahead_off)
int   farT  = request.security(farSym, "D", time, lookahead = barmerge.lookahead_off)
 
// Each bar time is reduced to a calendar day before the two are compared, so a
// pair whose sessions open some minutes or hours apart on the same day is still a
// pair, while a one day desync is not. A pair whose sessions fall either side of
// a day boundary here would be refused on every single bar. That is a loud
// failure rather than a quiet wrong number, it is the intended trade, and it is
// the first thing to look at on a real chart.
float nearDay = na(nearT) ? na : math.floor(nearT / 86400000.0)
float farDay  = na(farT) ? na : math.floor(farT / 86400000.0)
 
bool  haveBoth = not na(nearC) and not na(farC) and farC > 0.0
bool  sameDay  = not na(nearDay) and not na(farDay) and nearDay == farDay
bool  dataOk   = stdOk and tfOk and bandsOk and haveBoth and sameDay
float ratio    = dataOk ? nearC / farC : na
 
// A chart can carry more bars than the series does. On a symbol that trades seven
// days a week, a request for a daily CBOE series hands back the same Friday value
// on Saturday and on Sunday, and a run counted in chart bars would be half again
// as long as the run that happened. The ledger advances only when the requested
// series changes day, which is what this detects. na() takes an int here, not a
// bool.
bool newDay = not na(nearT) and (na(nearT[1]) or nearT != nearT[1])
 
// A chart property rather than a statistic, so it is measured over a short fixed
// window instead of the ranking window: a mismatch that takes 1260 bars to
// announce itself is not a warning. Two repeats in seven bars is 29%, an ordinary
// listed calendar against a listed series is 0%, and the line sits between them.
float dupFlag  = newDay ? 0.0 : 1.0
float dupShare = ta.sma(dupFlag, 60) * 100.0
bool  calMiss  = not na(dupShare) and dupShare > 10.0
 
var int dayCount = 0
if dataOk and newDay
    dayCount += 1
 
// The ranking source is held across a bar the pair is unusable on, rather than
// passed through as na. ta.percentrank over a 1260 bar window that contains one
// na is a window that may return nothing for 1260 bars, and two desynced prints
// are not a reason to blank five years of the pane. The count of bars that were
// held is carried in the data window so the holding is visible rather than
// silent, and on the default pair over its whole loaded history that count is 2.
var float ratioHold = na
var float nearHold  = na
var int   staleBars = 0
if dataOk
    ratioHold := ratio
    nearHold  := nearC
else if stdOk and tfOk and bandsOk and not na(ratioHold)
    staleBars += 1
 
float structRank = ta.percentrank(ratioHold, lvlLen)
float levelRank  = ta.percentrank(nearHold, lvlLen)
 
// State on this bar. -1 is not a state, it is the absence of one.
int    rawCode  = not dataOk ? -1 : ratio >= invLine ? 2 : ratio <= calmLine ? 0 : 1
string rawName  = rawCode == 2 ? "inverted" : rawCode == 1 ? "flat" : rawCode == 0 ? "steep" : "no data"
color  stateCol = rawCode == 2 ? color.red : rawCode == 1 ? color.gray : rawCode == 0 ? color.teal : color.silver
 
// The ledger. One list per state, so the cap applies per state and the sample
// behind a percentile is the sample for that state alone. A shared list capped at
// the same size would quietly starve the rarest state, which is the inverted one
// and the one anybody is looking at.
var array<float> lenStp = array.new<float>()
var array<float> lenFlt = array.new<float>()
var array<float> lenInv = array.new<float>()
 
var int   runCode   = -1
var int   runAge    = 0
var float runExt    = na
var bool  firstDone = false
 
if dataOk and newDay
    if rawCode == runCode
        runAge += 1
        // math.max and math.min propagate an na rather than ignoring one, so
        // this depends on runExt having been set on the bar the run started,
        // which the branch below does for every state that tracks an extreme.
        // The dependency is named because it is invisible from here.
        runExt := rawCode == 2 ? math.max(runExt, ratio) : rawCode == 0 ? math.min(runExt, ratio) : na
    else
        // The run that was open when the chart's history began is cut off at the
        // left edge, so its length is a property of how much history loaded. It
        // is dropped rather than ledgered. One run out of several hundred, and
        // the only one whose start the chart cannot see.
        if runAge > 0
            if not firstDone
                firstDone := true
            else if runCode == 0
                array.push(lenStp, runAge * 1.0)
                if array.size(lenStp) > maxRuns
                    array.shift(lenStp)
            else if runCode == 1
                array.push(lenFlt, runAge * 1.0)
                if array.size(lenFlt) > maxRuns
                    array.shift(lenFlt)
            else if runCode == 2
                array.push(lenInv, runAge * 1.0)
                if array.size(lenInv) > maxRuns
                    array.shift(lenInv)
        runCode := rawCode
        runAge  := 1
        runExt  := rawCode == 1 ? na : ratio
 
string runName = runCode == 2 ? "inverted" : runCode == 1 ? "flat" : runCode == 0 ? "steep" : "none"
int    runN    = runCode == 0 ? array.size(lenStp) : runCode == 1 ? array.size(lenFlt) : runCode == 2 ? array.size(lenInv) : 0
 
// One list is scanned per bar rather than three. f_share reads an array and does
// no ta.* work of any kind, so putting the call inside a branch costs it no
// history and is not the lazy evaluation hazard that moving a ta.* call into a
// conditional would be. It is written this way on purpose and is not tidying.
float ageShare = na
if runCode == 0
    ageShare := f_share(lenStp, runAge * 1.0)
else if runCode == 1
    ageShare := f_share(lenFlt, runAge * 1.0)
else if runCode == 2
    ageShare := f_share(lenInv, runAge * 1.0)
 
// Two independent readiness gates, because the two halves of the pane warm up at
// different speeds and on a short history the ledger reads long before the ranks
// do. An explicit dayCount test rather than only a na check on the rank, since
// ta.percentrank's behaviour on a window that has held values is not something
// this file should be guessing at.
bool hasRun    = dataOk and runCode >= 0 and runAge > 0
bool rankReady = dataOk and dayCount >= lvlLen and not na(structRank) and not na(levelRank)
bool ledgerOk  = hasRun and runN >= minRuns
 
float ageRank = ledgerOk ? ageShare : na
float rankGap = rankReady ? levelRank - structRank : na
 
// Every reason there is no read gets named, in the order they are tested. The
// chart type comes first because it is the one nothing else would catch, then
// the two refusals, then the chart property, then the two warmups. A setting
// that is wrong is wrong before anything has warmed up.
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 steep edge has to sit below the inverted edge" : not haveBoth ? "no reading from " + nearSym + " or " + farSym : not sameDay ? nearSym + " and " + farSym + " 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 rankReady and not ledgerOk ? "warming up, " + str.tostring(dayCount) + " of " + str.tostring(lvlLen) + " data days and " + str.tostring(runN) + " of " + str.tostring(minRuns) + " completed runs" : not rankReady ? "runs are reading, the percentiles want " + str.tostring(lvlLen) + " data days and have " + str.tostring(dayCount) : not ledgerOk ? "percentiles are reading, the ledger holds " + str.tostring(runN) + " of " + str.tostring(minRuns) + " completed " + runName + " runs" : "ok"
 
// The pane. The run age percentile is the thick line because it is the reading
// this file exists for; it climbs through a run and drops when the state changes,
// so a sawtooth is the correct shape and not an artefact. The two ranks are drawn
// thin with the distance between them shaded.
pA = plot(showAge ? ageRank : na, "Run age percentile", color.new(color.purple, 0), 2)
pS = plot(rankReady ? structRank : na, "Structure percentile", color.new(color.orange, 0), 1)
pL = plot(rankReady and showLevel ? levelRank : na, "Level percentile", color.new(color.gray, 0), 1)
 
// Blue when the level is ranked above the structure, orange when the structure is
// ranked above the level. An exact tie is neither and is left uncoloured.
fill(pS, pL, showFill and not na(rankGap) and rankGap != 0.0 ? (rankGap > 0.0 ? color.new(color.blue, 85) : color.new(color.orange, 85)) : na)
 
hline(50, "Middle", 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 dataOk ? color.new(stateCol, 93) : na)
 
// Every one of these is explicitly gated. Four of them are arithmetic on the
// requested series or on a counter and would otherwise survive a refused chart
// with a plausible looking value, which is the failure worth writing out rather
// than assuming away. What a refused chart does leave standing is the three
// reference lines above, which take constants, and the fixed labels in the
// table's left column. Every value goes to a dash.
plot(dataOk ? ratio : na, "Structure ratio", display = display.data_window)
plot(dataOk ? nearC : na, "Near close", display = display.data_window)
plot(dataOk ? farC : na, "Far close", display = display.data_window)
plot(dataOk ? runExt : na, "Extreme this run", display = display.data_window)
plot(hasRun ? runAge * 1.0 : na, "Days in this run", display = display.data_window)
plot(hasRun ? runN * 1.0 : na, "Completed runs of this state", display = display.data_window)
plot(rankGap, "Level rank minus structure rank", display = display.data_window)
plot(dataOk ? staleBars * 1.0 : na, "Bars held over an unusable pair", display = display.data_window)
 
// Format strings are "0" and "0.000" rather than "#", which suppresses a lone
// zero and would print a percentile cell reading "%" with nothing in front of it.
// An exact zero is one of the values a run age percentile takes, on the first day
// of a run in a state whose shortest past run was longer.
string ratioTxt = not dataOk ? "-" : str.tostring(ratio, "0.000") + "   " + rawName + (rankReady ? "   p" + str.tostring(structRank, "0") : "")
string levelTxt = not dataOk ? "-" : str.tostring(nearC, "0.00") + (rankReady ? "   p" + str.tostring(levelRank, "0") : "")
string runTxt   = not hasRun ? "-" : runName + ", day " + str.tostring(runAge)
string cmpTxt   = not hasRun ? "-" : not ledgerOk ? "ledger holds " + str.tostring(runN) + " of " + str.tostring(minRuns) : "longer than " + str.tostring(ageRank, "0") + "% of " + str.tostring(runN) + " completed " + runName + " runs"
string extTxt   = not dataOk or na(runExt) ? "-" : str.tostring(runExt, "0.000")
string srcTxt   = not dataOk ? "-" : nearSym + " over " + farSym + ", daily closes"
 
if showTable and barstate.islast
    // The median and the longest are read once, on the last bar, rather than on
    // every bar. Both sort a copy of a list that can hold hundreds of entries and
    // neither is needed by a plot.
    float medRun = na
    float maxRun = na
    if runCode == 0
        medRun := f_median(lenStp)
        maxRun := f_longest(lenStp)
    else if runCode == 1
        medRun := f_median(lenFlt)
        maxRun := f_longest(lenFlt)
    else if runCode == 2
        medRun := f_median(lenInv)
        maxRun := f_longest(lenInv)
    string pastTxt = not hasRun or na(medRun) ? "-" : "median " + str.tostring(medRun, "0.#") + " days, longest " + str.tostring(maxRun, "0")
 
    var table t = table.new(position.top_right, 2, 8, border_width = 1)
    table.cell(t, 0, 0, "Structure", 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, "Near level", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 1, levelTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 2, "This run", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 2, runTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 3, "Against past runs", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 3, cmpTxt, text_color = color.white, bgcolor = color.new(color.purple, 80), text_size = size.small)
    table.cell(t, 0, 4, "Those past runs", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 4, pastTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 5, "Extreme this run", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 5, extTxt, text_color = color.gray, text_size = size.small)
    table.cell(t, 0, 6, "Series", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 6, srcTxt, text_color = color.gray, text_size = size.small)
    table.cell(t, 0, 7, "Status", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 7, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)

← 返回列表