本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// 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 Dual Momentum Engine", "YURI DME", overlay = false, precision = 1)
// Dual momentum is Gary Antonacci's, published as Global Equities Momentum in
// Dual Momentum Investing (2014). The method is his: rank two equity sleeves by
// their trailing return, and require the winner's return to clear a cash rate
// before it counts. None of that is this script's idea and none of it is claimed
// as one.
//
// What this file adds is a record of how the ranking has behaved, which the
// ranking on its own does not carry:
//
// the ledger Every month the leading sleeve is written down. When the lead
// changes hands, the length of the spell that just ended is
// stored. Today's open spell is then read against that list as a
// percentile, printed with the number of spells behind it and,
// where there is one to give, the standard error with it.
// the spread The same ranking computed at three lookbacks at once, reported
// as agreeing or split. Which lookback a reader picked is a
// choice that moves the headline, so it is printed as a reading
// rather than buried in a setting.
//
// Both were measured before being kept. On daily bars of a US equity fund against
// a world ex-US fund, 2007-05 to 2026-09, the ledger holds 21 completed spells
// with a median of 4 months and a longest of 52. Twenty one is a small ledger and
// it is the reason the spell count and the standard error sit beside the
// percentile rather than under it: a percentile near the middle of 21 spells
// carries a standard error of 10.9 points, so the middle half of the scale is
// one error wide. Read the percentile as a rough position, not as a measurement.
//
// On the default pair the tenure only starts reading in the chart's tenth year:
// of 4857 daily bars it prints on 2253, the first on 2017-10-02, and before that
// the pane is empty and the status line counts the ledger up. A short chart shows
// nothing here at all.
//
// At the two ends of the scale no error is printed. A percentile of 0 or 100
// means every spell in the list is on one side of the reading, and the error is
// zero there by arithmetic rather than by precision.
//
// Neither reading is the size of the lead in other clothes, and that was tested
// as an identity before it was tested as a correlation, because a rank
// correlation goes blind to a folded relationship. Once both are put on their own
// rank scale the two differ by as much as 78.2 points on the default pair and
// 74.4 on a longer one, which no formula relation could produce. The rank
// correlation between the tenure percentile and the size of the lead is +0.29 and
// +0.50, and the folded comparison is -0.15 and -0.01.
//
// The lookback spread correlates -0.40 and -0.41 with the size of the lead. The
// largest correlation in this file is the +0.50 above; this is the next one, and
// both are put here rather than left for a reader to find: the three lookbacks
// tend to disagree when the lead is narrow, which is what they ought to do. They disagree on 39.2% and 38.4% of the
// months read. What that reading adds over the size of the lead is which of the
// three lookbacks is the one out of step.
//
// On the cash leg, and this is the part most likely to mislead. A chart carries a
// price series, and a Treasury bill fund pays out almost everything it earns, so
// its price series is close to flat whatever the rate is. Measured over 12 month
// windows on the default cash proxy, the price-only return runs below the
// distribution-adjusted one by a median of 0.25 points and by as much as 5.38 in
// a high rate stretch. So the cash figure in the table is labelled price only and
// the absolute momentum line is a hurdle input in percent, set by hand, rather
// than a comparison against a cash series this script cannot read correctly.
// Antonacci's own absolute momentum is excess return over Treasury bills; the
// zero default here is the simpler variant of the same idea and is not his.
//
// Every series is requested at the monthly timeframe with a one bar offset, so a
// reading is built from the last month that has closed and is fixed for the whole
// of the month you are looking at. The September close becomes visible on the
// first chart bar of October and does not move afterwards.
//
// No order, no holding, no sizing and no alert lives in this file, and it does not
// nominate a sleeve to own. It reports which one has led, for how long, how that
// length sits among the spells already on record, and whether three lookbacks tell
// the same story about it.
// Series -----------------------------------------------------------------------
symA = input.symbol("AMEX:SPY", "Equity sleeve A", group = "Series")
symB = input.symbol("AMEX:VEU", "Equity sleeve B", group = "Series", tooltip = "The two sleeves are ranked against each other. The published method pairs a domestic equity sleeve with a world ex-domestic one, which is what the defaults are.")
symBond = input.symbol("AMEX:AGG", "Bond series", group = "Series", tooltip = "Reported as a third trailing return. It takes no part in the ranking and the file does not suggest holding it.")
symCash = input.symbol("AMEX:BIL", "Cash proxy", group = "Series", tooltip = "Printed as a reference only, and price only. A bill fund distributes almost all of its return, so its price series does not carry the cash rate.")
// Lookbacks --------------------------------------------------------------------
lbMain = input.int(12, "Lookback, months", minval = 1, maxval = 36, group = "Lookbacks", tooltip = "The headline. Everything in the ledger is built at this lookback.")
lbAlt1 = input.int(3, "Second lookback for the agreement reading", minval = 1, maxval = 36, group = "Lookbacks")
lbAlt2 = input.int(9, "Third lookback for the agreement reading", minval = 1, maxval = 36, group = "Lookbacks", tooltip = "These two do not feed the ledger. They exist so the table can say whether the choice of lookback changes the answer on this bar.")
// Absolute momentum ------------------------------------------------------------
hurdlePct = input.float(0.0, "Absolute momentum hurdle, percent", minval = -20.0, maxval = 20.0, step = 0.25, group = "Absolute momentum", tooltip = "The line a sleeve's own trailing return is compared against. Zero is the simple variant. Set it to a bill rate by hand if you want the published form, since the cash series on a chart is price only.")
// Ledger -----------------------------------------------------------------------
maxSpells = input.int(200, "Spells the ledger holds", minval = 10, maxval = 1000, group = "Ledger", tooltip = "Oldest out first. A monthly chart of these funds produces spells in the tens, so this is a ceiling rather than a setting.")
minSpells = input.int(8, "Completed spells before the tenure reads", minval = 6, maxval = 100, group = "Ledger", tooltip = "At 8 spells a percentile near the middle carries a standard error of about 17.7 points, which is most of the scale. Raising it delays the reading and does not make it sharper.")
// Display ----------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showSplit = input.bool(true, "Mark months where the lookbacks disagree", group = "Display")
showTint = input.bool(true, "Tint the pane by which sleeve leads", group = "Display")
// The share of an array's values that are at or below v, in percent. Written out
// rather than taken from a builtin so the convention is visible: at or below, not
// below, so a spell exactly as long as the median counts as having reached it.
f_share(array<float> a, float v) =>
int n = array.size(a)
float out = na
if n > 0
int c = 0
for i = 0 to n - 1
if array.get(a, i) <= v
c += 1
out := c * 100.0 / n
out
// The standard error of a share, in percentage points. The spells are treated as
// independent draws here, which they are not: a long spell and the spell after it
// are both drawn from the same stretch of one relationship between two funds, and
// the true error is the larger of the two. Read the printed figure as a floor.
//
// Nothing is returned at either end of the scale. When the tenure comes out at 0
// or at 100 the whole ledger has fallen on one side of the open spell, and the
// binomial formula then evaluates to zero because there is no spread left in it
// to measure, not because the figure is exact. A zero in that cell would read as
// precision on the one number this file spends a paragraph calling thin, so the
// table prints a sentence there instead.
f_se(float p, int n) =>
float out = na
if n > 0 and not na(p) and p > 0.0 and p < 100.0
out := math.sqrt(p / 100.0 * (1.0 - p / 100.0) / n) * 100.0
out
f_median(array<float> a) =>
float out = na
if array.size(a) > 0
out := array.median(a)
out
f_max(array<float> a) =>
float out = na
if array.size(a) > 0
out := array.max(a)
out
// A synthetic chart carries a close that nothing traded at, and every other gate
// in this file would pass on one: the timeframe is still daily, the symbols still
// resolve, the months still line up, and the status line would read ok while the
// ranking was computed on prices nothing traded at. It is tested first for that
// reason.
bool stdOk = chart.is_standard
// One day to a bar is required. A daily test on its own is not enough to get
// that: charts of two, three and five days report as daily too, with the multiple
// held apart in timeframe.multiplier, and on such a chart the bar a fresh month is
// first seen on moves. The seconds and ticks tests are already implied by the
// daily one and are written out anyway, since a refusal chain that holds only by
// implication stops holding the first time someone edits it.
bool tfOk = stdOk and timeframe.isdaily and timeframe.multiplier == 1 and not timeframe.isseconds and not timeframe.isticks
// Every series is pulled from the monthly timeframe with a one bar offset and
// lookahead on. That pairing is what keeps a historical bar and a live bar
// looking at the same monthly bar: the offset moves the read back to the last
// month that has closed, so neither is served a month that is still forming.
// Without the offset, lookahead on would hand a historical bar a month that had
// not finished at the time that bar printed, which is the failure this pairing
// exists to avoid. A value here settles when its month closes and is not
// rewritten afterwards.
//
// Every leg of every symbol carries the same one bar shift, including the time
// legs, so the value and the stamp that says which month it came from are taken
// from the same bar.
int oMain = 1 + lbMain
int oAlt1 = 1 + lbAlt1
int oAlt2 = 1 + lbAlt2
float aNow = request.security(symA, "M", close[1], lookahead = barmerge.lookahead_on)
float aMain = request.security(symA, "M", close[oMain], lookahead = barmerge.lookahead_on)
float aAlt1 = request.security(symA, "M", close[oAlt1], lookahead = barmerge.lookahead_on)
float aAlt2 = request.security(symA, "M", close[oAlt2], lookahead = barmerge.lookahead_on)
int aTime = request.security(symA, "M", time[1], lookahead = barmerge.lookahead_on)
float bNow = request.security(symB, "M", close[1], lookahead = barmerge.lookahead_on)
float bMain = request.security(symB, "M", close[oMain], lookahead = barmerge.lookahead_on)
float bAlt1 = request.security(symB, "M", close[oAlt1], lookahead = barmerge.lookahead_on)
float bAlt2 = request.security(symB, "M", close[oAlt2], lookahead = barmerge.lookahead_on)
int bTime = request.security(symB, "M", time[1], lookahead = barmerge.lookahead_on)
float dNow = request.security(symBond, "M", close[1], lookahead = barmerge.lookahead_on)
float dMain = request.security(symBond, "M", close[oMain], lookahead = barmerge.lookahead_on)
int dTime = request.security(symBond, "M", time[1], lookahead = barmerge.lookahead_on)
float cNow = request.security(symCash, "M", close[1], lookahead = barmerge.lookahead_on)
float cMain = request.security(symCash, "M", close[oMain], lookahead = barmerge.lookahead_on)
int cTime = request.security(symCash, "M", time[1], lookahead = barmerge.lookahead_on)
// Which month each series says its own reading came from. The default gaps off
// setting carries the last known value forward onto bars the other series did not
// print, so a stale read and a fresh one are indistinguishable from the price
// by itself. The four stamps are what give a drift between them any visibility.
// The comparison is on the calendar month rather than the exact timestamp, so two
// funds whose month opens on different days are not refused for that alone.
int aMonth = na(aTime) ? na : year(aTime) * 12 + month(aTime)
int bMonth = na(bTime) ? na : year(bTime) * 12 + month(bTime)
int dMonth = na(dTime) ? na : year(dTime) * 12 + month(dTime)
int cMonth = na(cTime) ? na : year(cTime) * 12 + month(cTime)
bool haveRank = not na(aNow) and not na(aMain) and not na(bNow) and not na(bMain) and aMain > 0.0 and bMain > 0.0
bool haveStamp = not na(aMonth) and not na(bMonth) and not na(dMonth) and not na(cMonth)
bool sameMonth = haveStamp and aMonth == bMonth and bMonth == dMonth and dMonth == cMonth
// The gate sits on the values themselves and not only on what is drawn. A
// trailing return is arithmetic on two requested closes and meets no other test on
// its way to the screen, so without this line a refused chart would still fill two
// plots and two cells with figures underneath a status line calling the chart
// wrong. Everything downstream picks the refusal up from here.
bool dataOk = tfOk and haveRank and sameMonth
// The two trailing returns the ranking is made of, and the ones at the other two
// lookbacks. Percent rather than a ratio, because that is how the table reads.
float mA = dataOk ? (aNow / aMain - 1.0) * 100.0 : na
float mB = dataOk ? (bNow / bMain - 1.0) * 100.0 : na
float mA1 = dataOk and not na(aAlt1) and aAlt1 > 0.0 ? (aNow / aAlt1 - 1.0) * 100.0 : na
float mB1 = dataOk and not na(bAlt1) and bAlt1 > 0.0 ? (bNow / bAlt1 - 1.0) * 100.0 : na
float mA2 = dataOk and not na(aAlt2) and aAlt2 > 0.0 ? (aNow / aAlt2 - 1.0) * 100.0 : na
float mB2 = dataOk and not na(bAlt2) and bAlt2 > 0.0 ? (bNow / bAlt2 - 1.0) * 100.0 : na
float mBond = dataOk and not na(dNow) and not na(dMain) and dMain > 0.0 ? (dNow / dMain - 1.0) * 100.0 : na
float mCash = dataOk and not na(cNow) and not na(cMain) and cMain > 0.0 ? (cNow / cMain - 1.0) * 100.0 : na
// The lead, and who holds it. An exact tie is not a lead: it leaves the ledger
// alone rather than being handed to a side. It did not happen once on the history
// measured, which is a reason to name the case rather than to assume it away.
int leadNow = not dataOk ? 0 : mA > mB ? 1 : mB > mA ? -1 : 0
float margin = dataOk ? math.abs(mA - mB) : na
int lead1 = na(mA1) or na(mB1) ? 0 : mA1 > mB1 ? 1 : mB1 > mA1 ? -1 : 0
int lead2 = na(mA2) or na(mB2) ? 0 : mA2 > mB2 ? 1 : mB2 > mA2 ? -1 : 0
bool haveAll3 = dataOk and leadNow != 0 and lead1 != 0 and lead2 != 0
bool isSplit = haveAll3 and (lead1 != leadNow or lead2 != leadNow)
// A new month is the bar on which the requested stamp changes. Written against
// the stamp rather than against the chart's own calendar so that the ledger
// advances on the bar the data advanced on, whatever the chart did.
bool newMonth = not na(aMonth) and (na(aMonth[1]) or aMonth != aMonth[1])
// The ledger. One entry per completed spell, in months.
var array<float> spellHist = array.new<float>()
var int curLead = 0
var int spellLen = 0
var bool firstSeen = false
var int truncLen = 0
var int tieMonths = 0
if dataOk and newMonth
if leadNow == 0
tieMonths += 1
else if curLead == 0
curLead := leadNow
spellLen := 1
else if leadNow == curLead
spellLen += 1
else
// The first spell on the chart was already running when the history
// began, so its length is whatever the chart happens to start at. It is
// set aside rather than counted short, and the table says so.
if not firstSeen
firstSeen := true
truncLen := spellLen
else
array.push(spellHist, spellLen)
if array.size(spellHist) > maxSpells
array.shift(spellHist)
curLead := leadNow
spellLen := 1
int spellN = array.size(spellHist)
bool ledgerOk = dataOk and spellN >= minSpells and spellLen > 0
float tenure = ledgerOk ? f_share(spellHist, spellLen) : na
float tenureSE = ledgerOk ? f_se(tenure, spellN) : na
float spellMed = f_median(spellHist)
float spellMax = f_max(spellHist)
color leadCol = leadNow == 1 ? color.teal : leadNow == -1 ? color.orange : color.gray
// Every reason there is no reading gets named. The synthetic chart test is first
// because it is the one every other gate would pass.
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not timeframe.isdaily or timeframe.multiplier != 1 or timeframe.isseconds or timeframe.isticks ? "needs a one day chart" : not haveStamp ? "one of the four series returned nothing here" : not sameMonth ? "the four series are not on the same month here; if this shows on every bar they keep different calendars" : not haveRank ? "warming up, the ranking wants " + str.tostring(lbMain) + " months of both sleeves" : leadNow == 0 ? "the two sleeves are exactly level this month" : not ledgerOk ? "ledger filling, " + str.tostring(spellN) + " of " + str.tostring(minSpells) + " completed spells" : "ok"
// The pane is the ledger, on a nought to one hundred scale. The size of the lead
// is not drawn: it is one subtraction from two figures that are both in the
// table, and drawing it would make the pane look like a ranking chart with a
// percentile bolted on rather than a percentile with its inputs listed.
plot(tenure, "Tenure percentile of the open spell", color.new(color.purple, 0), 2, style = plot.style_linebr)
mid = hline(50, "Half the spells", color.new(color.gray, 60), hline.style_dotted)
top = hline(100, "Top", color.new(color.gray, 90))
bot = hline(0, "Bottom", color.new(color.gray, 90))
// Pinned to an absolute level rather than location.top, which would sit the mark
// outside the pane's range and pad the scale out to fit it.
plotshape(showSplit and isSplit ? 95 : na, "Lookbacks disagree", shape.xcross, location.absolute, color.new(color.red, 20), size = size.tiny)
bgcolor(showTint and dataOk and leadNow != 0 ? color.new(leadCol, 92) : na, title = "Which sleeve leads")
plot(mA, "Sleeve A trailing return, percent", display = display.data_window)
plot(mB, "Sleeve B trailing return, percent", display = display.data_window)
plot(margin, "Size of the lead, points", display = display.data_window)
plot(mBond, "Bond series trailing return, percent", display = display.data_window)
plot(mCash, "Cash proxy trailing return, price only", display = display.data_window)
plot(dataOk ? spellLen : na, "Months the open spell has run", display = display.data_window)
plot(ledgerOk ? spellN : na, "Completed spells in the ledger", display = display.data_window)
plot(tenureSE, "Standard error of the tenure percentile", display = display.data_window)
// Text for the table. Every cell that carries a number is built from a value that
// has already passed through dataOk or ledgerOk, so a refused chart empties all of
// them and leaves the status line as the only cell that speaks. The three that do
// not inherit a gate, the month stamp and the two ledger summaries, carry the test
// explicitly.
// Built from the two integer parts rather than from a date format string, so the
// leading zero on a single digit month is explicit and nothing depends on how a
// format pattern is interpreted.
int aYr = na(aTime) ? na : year(aTime)
int aMo = na(aTime) ? na : month(aTime)
string monthTxt = not dataOk or na(aYr) ? "-" : str.tostring(aYr) + "-" + (aMo < 10 ? "0" : "") + str.tostring(aMo)
string leadTxt = not dataOk ? "-" : leadNow == 1 ? "A by " + str.tostring(margin, "0.0") + " points" : leadNow == -1 ? "B by " + str.tostring(margin, "0.0") + " points" : "level"
string aTxt = na(mA) ? "-" : str.tostring(mA, "0.0") + "% " + (mA > hurdlePct ? "above the hurdle" : "at or below the hurdle")
string bTxt = na(mB) ? "-" : str.tostring(mB, "0.0") + "% " + (mB > hurdlePct ? "above the hurdle" : "at or below the hurdle")
string bondTxt = na(mBond) or not dataOk ? "-" : str.tostring(mBond, "0.0") + "%"
string cashTxt = na(mCash) or not dataOk ? "-" : str.tostring(mCash, "0.0") + "% price only"
string spellTxt = not dataOk ? "-" : str.tostring(spellLen) + " months, still open"
string seTxt = na(tenureSE) ? "every spell on one side, no error printed" : "SE " + str.tostring(tenureSE, "0.0")
string tenureTxt = not ledgerOk ? "-" : str.tostring(tenure, "0") + "% of " + str.tostring(spellN) + " spells were no longer, " + seTxt
string splitTxt = not haveAll3 ? "-" : (isSplit ? "split: " : "agreed: ") + str.tostring(lbAlt1) + "m " + (lead1 == 1 ? "A" : "B") + ", " + str.tostring(lbAlt2) + "m " + (lead2 == 1 ? "A" : "B") + ", " + str.tostring(lbMain) + "m " + (leadNow == 1 ? "A" : "B")
string truncTxt = firstSeen ? "1 truncated of " + str.tostring(truncLen) + " months" : "0 truncated"
string ledgerTxt = not dataOk or spellN == 0 ? "-" : str.tostring(spellN) + " spells, median " + str.tostring(spellMed, "0") + ", longest " + str.tostring(spellMax, "0") + ", set aside " + truncTxt + " and " + str.tostring(tieMonths) + " level months"
string hurdleTxt = dataOk ? str.tostring(hurdlePct, "0.00") + "%, set by hand" : "-"
if showTable and barstate.islast
var table t = table.new(position.top_right, 2, 12, border_width = 1)
table.cell(t, 0, 0, "Data month", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 0, monthTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 1, "Leads", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 1, leadTxt, text_color = color.white, bgcolor = color.new(leadCol, 80), text_size = size.small)
table.cell(t, 0, 2, "Sleeve A return", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 2, aTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 3, "Sleeve B return", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 3, bTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 4, "Absolute hurdle", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 4, hurdleTxt, text_color = color.gray, text_size = size.small)
table.cell(t, 0, 5, "Bond series", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 5, bondTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 6, "Cash proxy", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 6, cashTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 7, "Open spell", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 7, spellTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 8, "Tenure", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 8, tenureTxt, text_color = color.white, bgcolor = color.new(color.purple, 80), text_size = size.small)
table.cell(t, 0, 9, "Lookbacks", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 9, splitTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 10, "Ledger", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 10, ledgerTxt, text_color = color.gray, text_size = size.small)
table.cell(t, 0, 11, "Status", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 11, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)