本页源码来自 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/
// © tfox2791
//@version=6
// ============================================================================
// DEBASEMENT MONITOR (M2, LIQUIDITY, REAL YIELDS, DOLLAR)
// Chart-only pane indicator. Scores, from 0 to 5, how many of the usual
// macro drivers of the "debasement trade" (owning gold and bitcoin against
// a currency that is being diluted) are switched on, and checks whether gold
// and bitcoin are actually rising faster than the money supply.
// Companion to "Gold & Bitcoin Market Buying": this script covers the macro
// backdrop, that one covers who is buying.
//
// THE FIVE DRIVERS (each scores 1 when met):
// 1. M2 growing - US M2 money supply is up year on year by more than
// the threshold (default 0%).
// 2. M2 accelerating - M2 year-on-year growth is higher than it was N
// months earlier (default 3).
// 3. Liquidity rising - Fed net liquidity (Fed balance sheet minus the
// Treasury's account minus reverse repo) is above its
// N-week average (default 13).
// 4. Real yield falling - the 10-year inflation-protected Treasury yield is
// below its N-day average (default 50).
// 5. Dollar weak - the dollar index is below its N-day average
// (default 200).
//
// THE RESPONSE CHECK (does not add to the score):
// - Gold outrunning M2: gold's 52-week price change is greater than M2's
// year-on-year growth.
// - Bitcoin outrunning M2: the same for bitcoin.
//
// THE STATE:
// - "Debasement backdrop ON" = score at or above the minimum (default 3)
// AND, if the response check is required (default yes), at least one of
// gold or bitcoin is outrunning M2 - held for N weekdays in a row
// (default 3) before the state changes, so one-day flips are ignored.
// Saturdays and Sundays never count, because the macro data cannot
// update then, so a 24/7 bitcoin chart confirms the same way as a gold
// chart. On Weekly and Monthly charts N counts chart bars (weeks or
// months). The score alerts use the same confirmation.
//
// HOW TO READ IT:
// - Columns = the raw score today, 0 to 5. Green at or above the minimum,
// orange one below it, gray otherwise. Dotted line = the minimum.
// - Shaded background = backdrop ON. Up triangle = it switched on, down
// triangle = it switched off.
// - Table (top right) = the five drivers on the left; the backdrop state,
// score and the gold and bitcoin checks on the right. "Table text size"
// shrinks it for a short pane. Everything is also in the Data Window.
// - Alerts: backdrop ON, backdrop OFF, score reached the minimum, score
// fell below it, M2 growth turned positive, M2 growth turned negative.
//
// TIMING AND REPAINTING:
// - A Daily chart is the reference. Alerts and markers fire only on a
// closed chart bar, on every timeframe.
// - On charts of 1 day or lower: liquidity, real yield, dollar and asset
// returns are the last COMPLETED bar of their own timeframe (weekly or
// daily), requested with an offset of one bar. A reading does not change
// once shown, and the state is the same on every such timeframe.
// - On Weekly and Monthly charts: each CLOSED bar shows those readings as
// they stood at that bar's close and does not change afterwards. The bar
// still forming updates until it closes. Because the readings are taken
// at week or month ends and confirmation counts weeks or months, the
// state and markers can differ from those on a Daily chart.
// - M2 is chosen by calendar month, not by bar count: a chart bar in month
// M shows M2 for month M-1 minus the extra lag (default 1, so November
// shows September). M2 is published about four weeks after its month
// ends, so with the default lag the figure shown was always public on
// that date, and live readings match what history draws. With the extra
// lag at 0, history shows most figures BEFORE they were published, and
// the live reading can be one month older than history for the same date.
// - Two history-versus-live differences remain on charts of 1 day or
// lower. Each day's real yield is posted after the US close on the next
// business day, so during the US session, and when a Daily bar closes,
// the live reading is TWO trading days older than what history shows for
// that date (one day older once it posts). Fed data is released on
// Thursday for the week ending Wednesday, and early in a week the live
// liquidity reading can be the week before last. As a result about 6
// markers in 10 land on the same bar or one bar apart, about 4 in 10
// land two bars later live than on history, and roughly 1 in 12 appears
// in one view and not the other, when a short spell is long enough to
// confirm in one and not in the other.
//
// LIMITS (read these):
// - "M2 growing" is met most of the time (money supply usually grows), and
// two of the five points come from the one monthly M2 series. A minimum
// of 3 is in practice two of the other four drivers.
// - Even with the 3-weekday confirmation the state changes several times a
// year, mostly from the real yield and liquidity crossing their averages.
// Raise "Confirm" for a slower, steadier state.
// - Bar Replay does not support spread symbols, so the liquidity driver
// reads "n/a" in replay.
// - History uses TODAY'S revised figures. M2 and the Fed series are revised
// after first release, so past readings look cleaner than they did live.
// - The score counts conditions. It does not weigh them, and the default
// lengths and the minimum of 3 are judgment calls, not optimised values.
// - It describes the backdrop. It does not predict price, and gold and
// bitcoin have both fallen hard while money supply was growing.
// - The link between bitcoin and M2 is loose and unstable. Treat the
// bitcoin check as context.
// - Daily reverse repo data starts in September 2013, so the liquidity
// driver may be blank ("n/a", scores 0) or unreliable before then.
// Bitcoin data starts later than gold. A symbol that fails to load shows
// "n/a" for its driver instead of stopping the script.
// - Not designed for the Pine Screener.
// ============================================================================
indicator("Debasement Monitor (M2, Liquidity, Real Yields, Dollar)", shorttitle="Debasement", overlay=false, format=format.price, precision=2)
// ── Inputs: symbols ─────────────────────────────────────────────────────────
m2Sym = input.symbol("ECONOMICS:USM2", "US M2 money supply", group="Symbols")
fedSym = input.symbol("FRED:WALCL", "Fed balance sheet (total assets)", group="Symbols")
tgaSym = input.symbol("FRED:WTREGEN", "Treasury General Account", group="Symbols")
rrpSym = input.symbol("FRED:RRPONTSYD", "Overnight reverse repo", group="Symbols")
rySym = input.symbol("FRED:DFII10", "10-year real yield", group="Symbols")
dxySym = input.symbol("TVC:DXY", "US dollar index", group="Symbols")
goldSym = input.symbol("OANDA:XAUUSD", "Gold spot price", group="Symbols")
btcSym = input.symbol("COINBASE:BTCUSD", "Bitcoin spot price", group="Symbols")
// ── Inputs: M2 ──────────────────────────────────────────────────────────────
m2Lag = input.int(1, "Extra M2 lag (months)", minval=0, maxval=6, group="M2 money supply", tooltip="A chart bar in month M shows M2 for month M-1 minus this lag. M2 is published about four weeks after its month ends, so 1 means the figure shown was always public on that date.")
m2Min = input.float(0.0, "M2 growing: year-on-year growth above (%)", step=0.5, group="M2 money supply")
accelLen = input.int(3, "M2 accelerating: compare growth with N months earlier", minval=1, maxval=24, group="M2 money supply")
// ── Inputs: liquidity, real yield, dollar ───────────────────────────────────
liqLen = input.int(13, "Liquidity rising: above its N-week average", minval=2, maxval=260, group="Liquidity, real yield, dollar")
ryLen = input.int(50, "Real yield falling: below its N-day average", minval=2, maxval=500, group="Liquidity, real yield, dollar")
dxyLen = input.int(200, "Dollar weak: below its N-day average", minval=2, maxval=500, group="Liquidity, real yield, dollar")
// ── Inputs: score ───────────────────────────────────────────────────────────
scoreMin = input.int(3, "Minimum score for 'backdrop ON'", minval=1, maxval=5, group="Score")
needAsset = input.bool(true, "Also require gold or bitcoin to be outrunning M2", group="Score")
confirmN = input.int(3, "Confirm: state must hold for N weekdays", minval=1, maxval=20, group="Score", tooltip="The backdrop and the score alerts change only after the new state has held this many weekdays in a row (Saturdays and Sundays never count). On Weekly and Monthly charts it counts chart bars instead. 1 = no confirmation.")
// ── Inputs: display ─────────────────────────────────────────────────────────
showTable = input.bool(true, "Show driver table", group="Display")
tablePos = input.string("Top right", "Table position", options=["Top right", "Top left", "Bottom right", "Bottom left"], group="Display")
tableSize = input.string("Small", "Table text size", options=["Tiny", "Small", "Normal"], group="Display")
showBg = input.bool(true, "Shade the pane while the backdrop is ON", group="Display")
showMarks = input.bool(true, "Show ON / OFF markers", group="Display")
// ── Helpers ─────────────────────────────────────────────────────────────────
// All "pack" helpers run INSIDE the requested symbol's context. lvlPack and
// yoyPack take an offset: 1 (completed bars only) on charts of 1 day or
// lower, 0 on Weekly and Monthly charts. m2Pack can read offset 0 by design:
// M2 is requested without lookahead and picked by calendar month.
// Percent change of _now over _then; na when either is missing or _then is 0.
pctChg(series float _now, series float _then) =>
not na(_now) and not na(_then) and _then != 0 ? (_now / _then - 1) * 100 : na
// One M2 candidate, _o monthly bars back from the newest: level, year-on-year
// growth, and that growth _accel months earlier.
m2Cand(simple int _o, simple int _accel) =>
int o = math.max(_o, 0)
[close[o], pctChg(close[o], close[o + 12]), pctChg(close[o + _accel], close[o + _accel + 12])]
// Month number of the newest M2 bar, plus candidates _k, _k-1 and _k-2 bars
// back. The caller picks one by calendar month, so history and live agree.
m2Pack(simple int _k, simple int _accel) =>
[l0, y0, p0] = m2Cand(_k, _accel)
[l1, y1, p1] = m2Cand(_k - 1, _accel)
[l2, y2, p2] = m2Cand(_k - 2, _accel)
[year * 12 + month, l0, y0, p0, l1, y1, p1, l2, y2, p2]
// A state that changes only after _raw has held its new value _n WEEKDAYS in a
// row. Counting days (not bars) gives the same result on every timeframe up to
// Daily; skipping weekends gives the same result on 24/7 and weekday charts.
// A change partway through a day starts counting at the next day. On charts
// above Daily (_barMode) every bar counts, so _n is weeks or months.
held(series bool _raw, simple int _n, simple bool _barMode) =>
var bool state = false
var bool last = false // _raw on the previous bar
var int days = 0 // whole weekdays _raw has kept its value
int dow = dayofweek(time_tradingday, "UTC")
bool dataDay = dow != dayofweek.saturday and dow != dayofweek.sunday // macro data cannot update at a weekend
bool newDay = _barMode or (timeframe.change("1D") and dataDay)
if _raw != last or bar_index == 0
last := _raw
days := newDay ? 1 : 0
else if newDay
days += 1
if days >= _n
state := _raw
state
// Value _off bars back and its _len-bar average at the same bar.
lvlPack(simple int _len, simple int _off) =>
[close[_off], ta.sma(close, _len)[_off]]
// Weekly asset price: 52-week percent change, _off weeks back.
yoyPack(simple int _off) =>
pctChg(close[_off], close[_off + 52])
// Text helpers for the table.
fmt(series float _x, simple string _suffix) =>
na(_x) ? "n/a" : str.tostring(_x, "#,##0.00") + _suffix
// Two readings joined; a single "n/a" when either is missing.
fmt2(series float _a, simple string _mid, series float _b, simple string _end) =>
na(_a) or na(_b) ? "n/a" : fmt(_a, _mid) + fmt(_b, _end)
metTxt(series bool _met, series bool _known) =>
not _known ? "n/a" : _met ? "YES" : "no"
metCol(series bool _met, series bool _known) =>
not _known ? color.gray : _met ? color.green : color.new(color.red, 20)
// ── Calculations: requests (completed bars only) ────────────────────────────
// Net liquidity as one spread series: the three legs combined weekly, in dollars.
liqSym = fedSym + "-" + tgaSym + "-" + rrpSym
// M2: no lookahead. The month shown is picked by calendar below.
[m2Ym, a0, b0, c0, a1, b1, c1, a2, b2, c2] = request.security(m2Sym, "1M", m2Pack(1 + m2Lag, accelLen), ignore_invalid_symbol=true)
// Trading-day month, so a futures session that opens the evening before stays in its own month.
int m2Behind = year(time_tradingday, "UTC") * 12 + month(time_tradingday, "UTC") - m2Ym // months the newest M2 bar trails this chart bar
float m2Lvl = m2Behind <= 0 ? a0 : m2Behind == 1 ? a1 : a2
float m2Yoy = m2Behind <= 0 ? b0 : m2Behind == 1 ? b1 : b2
float m2YoyPrev = m2Behind <= 0 ? c0 : m2Behind == 1 ? c1 : c2
// The rest, requested two ways. Only one set is used on any given chart.
// - Charts of 1 day or lower: last completed bar (offset 1) with lookahead on,
// the standard non-repainting pattern. Readings never change once shown.
// - Weekly and Monthly charts: offset 0 without lookahead. A closed chart bar
// holds the reading as of its close; the forming bar updates until it closes.
// (Offset 1 with lookahead on would read the wrong intrabar there.)
aboveDaily = timeframe.in_seconds() > 86400
[liqA, liqAvgA] = request.security(liqSym, "1W", lvlPack(liqLen, 1), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[ryA, ryAvgA] = request.security(rySym, "1D", lvlPack(ryLen, 1), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[dxyA, dxyAvgA] = request.security(dxySym, "1D", lvlPack(dxyLen, 1), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
goldYoyA = request.security(goldSym, "1W", yoyPack(1), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
btcYoyA = request.security(btcSym, "1W", yoyPack(1), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[liqB, liqAvgB] = request.security(liqSym, "1W", lvlPack(liqLen, 0), ignore_invalid_symbol=true)
[ryB, ryAvgB] = request.security(rySym, "1D", lvlPack(ryLen, 0), ignore_invalid_symbol=true)
[dxyB, dxyAvgB] = request.security(dxySym, "1D", lvlPack(dxyLen, 0), ignore_invalid_symbol=true)
goldYoyB = request.security(goldSym, "1W", yoyPack(0), ignore_invalid_symbol=true)
btcYoyB = request.security(btcSym, "1W", yoyPack(0), ignore_invalid_symbol=true)
liq = aboveDaily ? liqB : liqA
liqAvg = aboveDaily ? liqAvgB : liqAvgA
ry = aboveDaily ? ryB : ryA
ryAvg = aboveDaily ? ryAvgB : ryAvgA
dxy = aboveDaily ? dxyB : dxyA
dxyAvg = aboveDaily ? dxyAvgB : dxyAvgA
goldYoy = aboveDaily ? goldYoyB : goldYoyA
btcYoy = aboveDaily ? btcYoyB : btcYoyA
// ── Calculations: drivers ───────────────────────────────────────────────────
// "known" = the data needed for the test exists on this bar.
m2Known = not na(m2Yoy)
accelKnown = not na(m2Yoy) and not na(m2YoyPrev)
liqKnown = not na(liq) and not na(liqAvg)
ryKnown = not na(ry) and not na(ryAvg)
dxyKnown = not na(dxy) and not na(dxyAvg)
m2Growing = m2Known and m2Yoy > m2Min // money supply is expanding
m2Accel = accelKnown and m2Yoy > m2YoyPrev // and expanding faster than before
liqRising = liqKnown and liq > liqAvg // net liquidity above its average
ryFalling = ryKnown and ry < ryAvg // real yield below its average
dxyWeak = dxyKnown and dxy < dxyAvg // dollar below its average
score = (m2Growing ? 1 : 0) + (m2Accel ? 1 : 0) + (liqRising ? 1 : 0) + (ryFalling ? 1 : 0) + (dxyWeak ? 1 : 0)
known = (m2Known ? 1 : 0) + (accelKnown ? 1 : 0) + (liqKnown ? 1 : 0) + (ryKnown ? 1 : 0) + (dxyKnown ? 1 : 0)
// ── Calculations: response check ────────────────────────────────────────────
goldExcess = goldYoy - m2Yoy // percentage points; na if either is missing
btcExcess = btcYoy - m2Yoy
goldOut = not na(goldExcess) and goldExcess > 0 // gold rising faster than money supply
btcOut = not na(btcExcess) and btcExcess > 0
// ── Calculations: state and events ──────────────────────────────────────────
scoreOk = score >= scoreMin // raw, this bar
rawBackdrop = scoreOk and (not needAsset or goldOut or btcOut)
scoreHeld = held(scoreOk, confirmN, aboveDaily) // confirmed: held N weekdays in a row
backdrop = held(rawBackdrop, confirmN, aboveDaily)
// Events fire only on a closed chart bar. The two backdrop events also draw a marker.
isDone = barstate.isconfirmed
turnedOn = isDone and backdrop and not backdrop[1] // backdrop switched ON
turnedOff = isDone and not backdrop and backdrop[1] // backdrop switched OFF
scoreUp = isDone and scoreHeld and not scoreHeld[1] // score reached the minimum
scoreDown = isDone and not scoreHeld and scoreHeld[1] // score fell below the minimum
// The M2 alerts test growth against ZERO on purpose (the sign change), not
// against the "M2 growing" threshold input.
m2TurnedUp = isDone and m2Known and m2Known[1] and m2Yoy > 0 and m2Yoy[1] <= 0
m2TurnedDn = isDone and m2Known and m2Known[1] and m2Yoy <= 0 and m2Yoy[1] > 0
liqTrn = liq / 1e12 // trillions of dollars, for display
liqAvgTrn = liqAvg / 1e12
// ── Pane visuals ────────────────────────────────────────────────────────────
scoreColor = score >= scoreMin ? color.new(color.green, 20) : score == scoreMin - 1 ? color.new(color.orange, 20) : color.new(color.gray, 30)
plot(known > 0 ? score : na, "Debasement score (0-5)", color=scoreColor, style=plot.style_columns)
hline(scoreMin, "Minimum score", color=color.gray, linestyle=hline.style_dotted)
hline(5, "Maximum", color=color.new(color.gray, 70), linestyle=hline.style_dotted)
bgcolor(showBg and backdrop ? color.new(color.green, 88) : na, title="Backdrop ON shading")
plotshape(showMarks and turnedOn, "Backdrop turned ON", shape.triangleup, location.bottom, color.new(color.lime, 0), size=size.small)
plotshape(showMarks and turnedOff, "Backdrop turned OFF", shape.triangledown, location.top, color.new(color.red, 0), size=size.small)
// ── Driver table ────────────────────────────────────────────────────────────
tblPos = switch tablePos
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
tblSize = switch tableSize
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
var table tbl = showTable ? table.new(tblPos, 6, 6, bgcolor=color.new(color.black, 20), border_width=1, border_color=color.new(color.gray, 60)) : na
// Two blocks side by side (drivers on the left, score and state on the right) so the table is 6 rows tall.
row(int _c, int _r, string _name, string _reading, string _met, color _col) =>
table.cell(tbl, _c, _r, _name, text_color=color.white, text_halign=text.align_left, text_size=tblSize)
table.cell(tbl, _c + 1, _r, _reading, text_color=color.white, text_halign=text.align_right, text_size=tblSize)
table.cell(tbl, _c + 2, _r, _met, text_color=color.white, bgcolor=_col, text_size=tblSize)
if barstate.islast and showTable
row(0, 0, "Driver", "Reading", "Met", color.new(color.gray, 40))
row(0, 1, "M2 growing", fmt(m2Yoy, "% y/y"), metTxt(m2Growing, m2Known), metCol(m2Growing, m2Known))
row(0, 2, "M2 accelerating", fmt(m2Yoy - m2YoyPrev, " pts vs " + str.tostring(accelLen) + "m ago"), metTxt(m2Accel, accelKnown), metCol(m2Accel, accelKnown))
row(0, 3, "Liquidity rising", fmt2(liqTrn, "T vs ", liqAvgTrn, "T avg"), metTxt(liqRising, liqKnown), metCol(liqRising, liqKnown))
row(0, 4, "Real yield falling", fmt2(ry, "% vs ", ryAvg, "% avg"), metTxt(ryFalling, ryKnown), metCol(ryFalling, ryKnown))
row(0, 5, "Dollar weak", fmt2(dxy, " vs ", dxyAvg, " avg"), metTxt(dxyWeak, dxyKnown), metCol(dxyWeak, dxyKnown))
row(3, 0, "State", "Reading", "Met", color.new(color.gray, 40))
row(3, 1, "BACKDROP", rawBackdrop == backdrop ? "confirmed" : "change pending", backdrop ? "ON" : "OFF", metCol(backdrop, known > 0))
row(3, 2, "SCORE", str.tostring(score) + " of 5 (min " + str.tostring(scoreMin) + ")" + (scoreOk == scoreHeld ? "" : ", pending"), metTxt(scoreOk, known > 0), metCol(scoreOk, known > 0))
row(3, 3, "Gold vs M2", fmt(goldExcess, " pts"), metTxt(goldOut, not na(goldExcess)), metCol(goldOut, not na(goldExcess)))
row(3, 4, "Bitcoin vs M2", fmt(btcExcess, " pts"), metTxt(btcOut, not na(btcExcess)), metCol(btcOut, not na(btcExcess)))
// ── Alerts (values are completed-bar readings; they do not repaint) ─────────
alertcondition(turnedOn, "Debasement backdrop ON", "Debasement backdrop switched ON ({{ticker}}, {{interval}})")
alertcondition(turnedOff, "Debasement backdrop OFF", "Debasement backdrop switched OFF ({{ticker}}, {{interval}})")
alertcondition(scoreUp, "Score reached the minimum", "Debasement score reached the minimum ({{ticker}}, {{interval}})")
alertcondition(scoreDown, "Score fell below the minimum", "Debasement score fell below the minimum ({{ticker}}, {{interval}})")
alertcondition(m2TurnedUp, "M2 growth turned positive", "US M2 year-on-year growth turned positive ({{ticker}}, {{interval}})")
alertcondition(m2TurnedDn, "M2 growth turned negative", "US M2 year-on-year growth turned negative ({{ticker}}, {{interval}})")
// ── Data Window outputs ─────────────────────────────────────────────────────
plot(m2Yoy, "M2 growth % y/y", display=display.data_window)
plot(m2YoyPrev, "M2 growth % y/y, N months earlier", display=display.data_window)
plot(m2Lvl / 1e12, "M2 level (trillions)", display=display.data_window)
plot(liqTrn, "Net liquidity (trillions)", display=display.data_window)
plot(liqAvgTrn, "Net liquidity average (trillions)", display=display.data_window)
plot(ry, "Real yield %", display=display.data_window)
plot(ryAvg, "Real yield average %", display=display.data_window)
plot(dxy, "Dollar index", display=display.data_window)
plot(dxyAvg, "Dollar index average", display=display.data_window)
plot(goldYoy, "Gold 52-week change %", display=display.data_window)
plot(btcYoy, "Bitcoin 52-week change %", display=display.data_window)
plot(goldExcess, "Gold minus M2 growth (pct pts)", display=display.data_window)
plot(btcExcess, "Bitcoin minus M2 growth (pct pts)", display=display.data_window)
plot(m2Growing ? 1 : 0, "M2 growing", display=display.data_window)
plot(m2Accel ? 1 : 0, "M2 accelerating", display=display.data_window)
plot(liqRising ? 1 : 0, "Liquidity rising", display=display.data_window)
plot(ryFalling ? 1 : 0, "Real yield falling", display=display.data_window)
plot(dxyWeak ? 1 : 0, "Dollar weak", display=display.data_window)
plot(goldOut ? 1 : 0, "Gold outrunning M2", display=display.data_window)
plot(btcOut ? 1 : 0, "Bitcoin outrunning M2", display=display.data_window)
plot(known, "Drivers with data (0-5)", display=display.data_window)
plot(m2Behind, "M2 months behind chart bar", display=display.data_window)
plot(rawBackdrop ? 1 : 0, "Backdrop raw (unconfirmed)", display=display.data_window)
plot(backdrop ? 1 : 0, "Backdrop ON", display=display.data_window)