本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ─────────────────────────────────────────────────────────────
// Yield Spread FX
// Built by Jake Koel · © jakekoel
// ─────────────────────────────────────────────────────────────
// Shows the spread between two government bond yields, in basis points.
// Auto: the two currencies of the chart (EUR/USD 2Y: German 2Y − US 2Y). Maturity 2Y, 5Y or 10Y.
// Manual: any two yields you choose (e.g. French 2Y − German 2Y).
// The table shows both yields and the spread now, and their change over 1 day, 1 week and 1 month.
//
// Data timing: each yield is matched to the chart's trading day by its trading date, so the spread never
// mixes bond prices from different days. Today's values update live (no delay).
indicator("Yield Spread FX", shorttitle = "Yield Spread FX", overlay = false, precision = 0)
// ───────────────────────── Inputs ─────────────────────────
string G_Y = "Yields"
string modeIn = input.string("Auto", "Mode", options = ["Auto", "Manual"], group = G_Y, display = display.none, tooltip = "Auto: picks the yields from the forex pair on the chart (EUR/USD → German and US yields) and changes them when you switch charts.\nManual: uses the two yields chosen below, whatever the chart.")
// The maturity is the only setting shown next to the indicator's name on the chart
string matIn = input.string("2Y", "Maturity (Auto)", options = ["2Y", "5Y", "10Y"], group = G_Y, display = display.status_line, tooltip = "Used in Auto mode.\n2Y (default): follows expected central bank rates over the next two years. The standard choice for rate expectations.\n5Y: a mix of the rate path and the medium-term economic outlook.\n10Y: long-term growth and inflation expectations, plus the extra yield investors demand for long-term government debt.\nEUR uses Germany, the standard euro-area benchmark.")
string manB = input.symbol("TVC:DE02Y", "First yield (Manual)", group = G_Y, display = display.none, tooltip = "Used in Manual mode. Spread = first yield − second yield.\nChoose a symbol quoted as a yield in percent, e.g. TVC:FR02Y, TVC:DE02Y, TVC:US02Y.")
string manQ = input.symbol("TVC:US02Y", "Second yield (Manual)", group = G_Y, display = display.none, tooltip = "Used in Manual mode.")
string G_P = "Display"
string viewIn = input.string("Spread", "Show", options = ["Spread", "Both yields"], group = G_P, display = display.none, tooltip = "Spread: one line, the gap between the two yields (in bp).\nBoth yields: the two yields as separate lines (in %). The gap between them is the spread, and the line that moves more is the one driving it.")
color lineCol = input.color(#2962FF, "Spread line", inline = "ln", group = G_P, display = display.none)
int lineW = input.int(2, "Width", minval = 1, maxval = 4, inline = "ln", group = G_P, display = display.none)
// Line colours for the "Both yields" view. Auto mode: each currency's colour. Manual mode: first / second yield.
string G_YC = "Yield line colours"
color cUSD = input.color(#4CAF50, "USD", inline = "c1", group = G_YC, display = display.none)
color cEUR = input.color(#2962FF, "EUR", inline = "c1", group = G_YC, display = display.none)
color cGBP = input.color(#9C27B0, "GBP", inline = "c1", group = G_YC, display = display.none)
color cJPY = input.color(#00BCD4, "JPY", inline = "c1", group = G_YC, display = display.none)
color cCAD = input.color(#F44336, "CAD", inline = "c2", group = G_YC, display = display.none)
color cAUD = input.color(#FF9800, "AUD", inline = "c2", group = G_YC, display = display.none)
color cNZD = input.color(#C9A400, "NZD", inline = "c2", group = G_YC, display = display.none)
color cCHF = input.color(#8D6E63, "CHF", inline = "c2", group = G_YC, display = display.none)
color colB = input.color(#2962FF, "Manual: first", inline = "m", group = G_YC, display = display.none)
color colQ = input.color(#FF9800, "Manual: second", inline = "m", group = G_YC, display = display.none)
string G_T = "Table"
bool showTbl = input.bool(true, "Show table", group = G_T, display = display.none)
string tPosIn = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_T, display = display.none)
string tSizeIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = G_T, display = display.none)
color upCol = input.color(#26A69A, "Spread change up", inline = "c", group = G_T, display = display.none)
color dnCol = input.color(#EF5350, "Spread change down", inline = "c", group = G_T, display = display.none)
// ───────────────────────── Yields ─────────────────────────
// Country code of each currency's government bond on TradingView (TVC data)
countryOf(string ccy) =>
switch ccy
"USD" => "US"
"EUR" => "DE" // Germany: the standard euro-area benchmark
"GBP" => "GB"
"JPY" => "JP"
"CHF" => "CH"
"CAD" => "CA"
"AUD" => "AU"
"NZD" => "NZ"
=> ""
// Maturity code used in the symbol: 2Y -> 02Y, 5Y -> 05Y, 10Y -> 10Y (e.g. TVC:US02Y, TVC:DE10Y)
string matCode = matIn == "10Y" ? "10Y" : matIn == "5Y" ? "05Y" : "02Y"
yieldSym(string ccy) =>
string c = countryOf(ccy)
c == "" ? "" : "TVC:" + c + matCode
// Short name of a symbol, e.g. "TVC:FR02Y" -> "FR02Y"
shortName(string sym) =>
array<string> parts = str.split(sym, ":")
parts.size() > 0 ? parts.last() : sym
bool manual = modeIn == "Manual"
string bC = str.upper(syminfo.basecurrency)
string qC = str.upper(syminfo.currency)
string bSym = manual ? manB : yieldSym(bC)
string qSym = manual ? manQ : yieldSym(qC)
bool okB = bSym != ""
bool okQ = qSym != ""
bool ok = okB and okQ
// Names used in the table
string bName = manual ? shortName(manB) : bC + " " + matIn
string qName = manual ? shortName(manQ) : qC + " " + matIn
string head = manual ? shortName(manB) + " − " + shortName(manQ) + " · yield spread" : bC + " − " + qC + " · " + matIn + " government bond yields"
const int DAY_MS = 86400000
// ───────────────────────── Yield for a trading day ─────────────────────────
// Returns the yield that belongs to the chart's trading date (day).
// Candidates: the bond's official daily close and its latest hourly value. Only values dated on or
// before that day are used, and the most recent one wins (official close preferred on a tie).
// Bond markets that close after forex (e.g. US) are read from their hourly data up to the forex close.
// A value older than 7 days is treated as missing (stale-data guard).
// Also returns the bond's previous official close (the close before the value's own date), used for the
// 1-day change. So the 1-day change is always the bond's latest daily move, even late in the evening
// when a new forex day has started but the bond market has not traded yet.
yieldFor(string sym, int day) =>
[d0, t0, d1, t1, d2] = request.security(sym, "D", [close, time_tradingday, close[1], time_tradingday[1], close[2]])
[h0, ht] = request.security(sym, "60", [close, time_tradingday])
float v = na
float p = na
int vt = na
if not na(d0) and not na(t0) and t0 <= day
v := d0
p := d1
vt := t0
if not na(h0) and not na(ht) and ht <= day and (na(vt) or ht > vt)
v := h0
p := not na(t0) and t0 < ht ? d0 : d1
vt := ht
if na(vt) and not na(d1) and not na(t1) and t1 <= day
v := d1
p := d2
vt := t1
if not na(vt) and day - vt > 7 * DAY_MS
v := na
p := na
[v, p]
// ───────────────────────── Daily calculation ─────────────────────────
// Runs on the daily bars of the chart symbol: both yields, the spread and their changes
// over 1 day (since each bond's previous close), 1 week (5 trading days) and 1 month (21 trading days).
// off = 1 returns the previous completed day (used on intraday charts, see below).
dailyCalc(string symB, string symQ, int off) =>
int day = time_tradingday
[b, bPrev] = yieldFor(symB, day)
[q, qPrev] = yieldFor(symQ, day)
float s = b - q
float b1 = b - bPrev
float q1 = q - qPrev
float s1 = b1 - q1
float b5 = b - b[5]
float q5 = q - q[5]
float s5 = s - s[5]
float b21 = b - b[21]
float q21 = q - q[21]
float s21 = s - s[21]
[b[off], q[off], s[off], b1[off], q1[off], s1[off], b5[off], q5[off], s5[off], b21[off], q21[off], s21[off]]
// A valid placeholder symbol is requested when a yield is not available; its values are hidden below.
string sB = okB ? bSym : "TVC:US02Y"
string sQ = okQ ? qSym : "TVC:US02Y"
bool intra = timeframe.isintraday
// Chart line. Daily and higher charts: the day's spread (today updates live, like price).
// Intraday charts: the last completed day, offset by one day so history never changes (no repainting).
[cB, cQ, cS, c1B, c1Q, c1S, c5B, c5Q, c5S, c21B, c21Q, c21S] = request.security(syminfo.tickerid, "D", dailyCalc(sB, sQ, intra ? 1 : 0), lookahead = intra ? barmerge.lookahead_on : barmerge.lookahead_off)
// Latest values for the table (today's live readings on every timeframe)
[nB, nQ, nS, n1B, n1Q, n1S, n5B, n5Q, n5S, n21B, n21Q, n21S] = request.security(syminfo.tickerid, "D", dailyCalc(sB, sQ, 0))
float spr = ok ? cS : na
// ───────────────────────── Plots ─────────────────────────
// Colour of a currency's yield line (from the "Yield line colours" settings)
ccyColor(string ccy, color fallback) =>
switch ccy
"USD" => cUSD
"EUR" => cEUR
"GBP" => cGBP
"JPY" => cJPY
"CAD" => cCAD
"AUD" => cAUD
"NZD" => cNZD
"CHF" => cCHF
=> fallback
bool bothView = viewIn == "Both yields"
color lnB = manual ? colB : ccyColor(bC, colB)
color lnQ = manual ? colQ : ccyColor(qC, colQ)
// Spread view: one line in basis points
// (each view's plots are fully hidden in the other view, so no empty values appear next to the name)
plot(not bothView ? spr * 100 : na, "Spread (bp)", lineCol, lineW, display = bothView ? display.none : display.all)
// Both yields view: the two yields in percent
plot(bothView and ok ? cB : na, "First yield (%)", lnB, lineW, precision = 2, display = bothView ? display.all : display.none)
plot(bothView and ok ? cQ : na, "Second yield (%)", lnQ, lineW, precision = 2, display = bothView ? display.all : display.none)
// ───────────────────────── Alerts ─────────────────────────
// Tip: TradingView's own alerts on "Spread (bp)" can also trigger at any level you choose.
alertcondition(ta.crossover(spr, 0), "Spread crossed above zero", "{{ticker}}: the yield spread has crossed above zero")
alertcondition(ta.crossunder(spr, 0), "Spread crossed below zero", "{{ticker}}: the yield spread has crossed below zero")
// ───────────────────────── Table ─────────────────────────
tPos = switch tPosIn
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
tSize = switch tSizeIn
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
// Solid table colours chosen from the chart background, so the text is readable on light and dark charts
bool DARK = 0.2126 * color.r(chart.bg_color) + 0.7152 * color.g(chart.bg_color) + 0.0722 * color.b(chart.bg_color) < 128
color TXT = DARK ? #E0E3EB : #131722
color MUTED = DARK ? #9598A1 : #6A6D78
color HEAD_BG = DARK ? #2A2E39 : #E0E3EB
color ROW_BG = DARK ? #1E222D : #F8F9FD
color LINE_C = DARK ? #363A45 : #D1D4DC
fmtPct(float v) =>
na(v) ? "—" : str.tostring(v, "0.00") + "%"
// Spread level in basis points
fmtLvl(float v) =>
na(v) ? "—" : str.tostring(math.round(v * 100)) + " bp"
// Change in basis points, with a sign
fmtChg(float v) =>
if na(v)
"—"
else
int bp = math.round(v * 100)
(bp > 0 ? "+" : "") + str.tostring(bp) + " bp"
chgCol(float v) =>
na(v) or math.round(v * 100) == 0 ? TXT : v > 0 ? upCol : dnCol
var table tb = table.new(tPos, 5, 5, border_width = 1, border_color = LINE_C, frame_width = 1, frame_color = LINE_C)
cell(int c, int r, string txt, color txtCol, color bg, string align) =>
table.cell(tb, c, r, txt, text_color = txtCol, bgcolor = bg, text_size = tSize, text_halign = align)
// One row: name, level, then the 1-day, 1-week and 1-month changes
row(int r, string name, color nameCol, string lvl, float c1, float c5, float c21, bool colour) =>
cell(0, r, name, nameCol, ROW_BG, text.align_left)
cell(1, r, lvl, TXT, ROW_BG, text.align_right)
cell(2, r, fmtChg(c1), colour ? chgCol(c1) : TXT, ROW_BG, text.align_right)
cell(3, r, fmtChg(c5), colour ? chgCol(c5) : TXT, ROW_BG, text.align_right)
cell(4, r, fmtChg(c21), colour ? chgCol(c21) : TXT, ROW_BG, text.align_right)
if barstate.isfirst and showTbl
table.merge_cells(tb, 0, 0, 4, 0)
if barstate.islast and showTbl
string missing = not okB and not okQ ? (bC == "" or qC == "" ? "" : bC + " and " + qC) : not okB ? bC : qC
string title = ok ? head : "No government bond yield for " + (missing == "" ? "this symbol" : missing) + ". Choose Manual mode in the settings."
cell(0, 0, title, TXT, HEAD_BG, text.align_left)
cell(0, 1, "", MUTED, HEAD_BG, text.align_left)
cell(1, 1, "Now", MUTED, HEAD_BG, text.align_right)
cell(2, 1, "1 day", MUTED, HEAD_BG, text.align_right)
cell(3, 1, "1 week", MUTED, HEAD_BG, text.align_right)
cell(4, 1, "1 month", MUTED, HEAD_BG, text.align_right)
// Yields: changes in neutral colour (a rising yield helps one side and hurts the other)
// In the "Both yields" view the yield names take their line colours, so the table doubles as a legend
row(2, bName, bothView ? lnB : MUTED, fmtPct(ok ? nB : na), ok ? n1B : na, ok ? n5B : na, ok ? n21B : na, false)
row(3, qName, bothView ? lnQ : MUTED, fmtPct(ok ? nQ : na), ok ? n1Q : na, ok ? n5Q : na, ok ? n21Q : na, false)
// Spread: changes coloured (up = towards the first yield / base currency)
row(4, "Spread", TXT, fmtLvl(ok ? nS : na), ok ? n1S : na, ok ? n5S : na, ok ? n21S : na, true)
// ───────────────────────── Signature ─────────────────────────
var table sig = table.new(tPosIn == "Bottom right" ? position.bottom_left : position.bottom_right, 1, 1)
if barstate.islast
table.cell(sig, 0, 0, "@jakekoel", text_color = color.new(color.gray, 30), text_size = size.small)