本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Macro Credit Risk", shorttitle="Macro Credit Risk", overlay=true, max_labels_count=500)
//=====================================================================
// MACRO CREDIT STRESS REGIME
//
// GREEN
// Credit conditions broadly normal.
//
// YELLOW
// CCC credit is beginning to deteriorate.
//
// ORANGE
// Credit deterioration is confirmed while equities remain near highs.
// This is the primary early macro warning.
//
// RED
// Credit stress is now accompanied by a genuine bearish equity trend.
//
// IMPORTANT:
// All user input values are hidden from the TradingView status line
// using display=display.none.
// This keeps the indicator name clean:
// "Macro Credit Risk"
//=====================================================================
//=====================================================================
// 1. DATA SOURCES
//=====================================================================
groupData = "1. Data Sources"
cccSymbol = input.symbol(
"FRED:BAMLH0A3HYC",
"CCC & Lower OAS",
group=groupData,
display=display.none)
hySymbol = input.symbol(
"FRED:BAMLH0A0HYM2",
"Broad High Yield OAS",
group=groupData,
display=display.none)
macroTF = input.timeframe(
"W",
"Macro timeframe",
group=groupData,
display=display.none)
//=====================================================================
// 2. CCC SETTINGS
//=====================================================================
groupCCC = "2. CCC Credit"
cccTrendLength = input.int(
13,
"CCC trend length",
minval=2,
group=groupCCC,
display=display.none)
cccChangeLength = input.int(
8,
"CCC widening lookback",
minval=1,
group=groupCCC,
display=display.none)
cccChangeThreshold = input.float(
0.50,
"CCC material widening",
step=0.05,
group=groupCCC,
display=display.none)
//=====================================================================
// 3. BROAD HIGH YIELD SETTINGS
//=====================================================================
groupHY = "3. Broad High Yield"
hyTrendLength = input.int(
13,
"HY trend length",
minval=2,
group=groupHY,
display=display.none)
hyChangeLength = input.int(
8,
"HY widening lookback",
minval=1,
group=groupHY,
display=display.none)
hyChangeThreshold = input.float(
0.25,
"HY material widening",
step=0.05,
group=groupHY,
display=display.none)
requireHY = input.bool(
true,
"Require broad HY confirmation",
group=groupHY,
display=display.none)
//=====================================================================
// 4. Z-SCORE SETTINGS
//=====================================================================
groupZ = "4. Credit Z-Score"
zLength = input.int(
52,
"Z-score lookback",
minval=20,
group=groupZ,
display=display.none)
zWarning = input.float(
0.50,
"Early stress Z-score",
step=0.10,
group=groupZ,
display=display.none)
zStrong = input.float(
1.00,
"Strong stress Z-score",
step=0.10,
group=groupZ,
display=display.none)
//=====================================================================
// 5. EQUITY SETTINGS
//=====================================================================
groupEquity = "5. Equity Confirmation"
highLookback = input.int(
26,
"Recent high lookback",
minval=4,
group=groupEquity,
display=display.none)
nearHighThreshold = input.float(
5.0,
"Near-high threshold %",
step=0.5,
group=groupEquity,
display=display.none)
fastDrawdownThreshold = input.float(
3.0,
"Early equity weakness %",
step=0.5,
group=groupEquity,
display=display.none)
strongDrawdownThreshold = input.float(
5.0,
"Strong equity weakness %",
step=0.5,
group=groupEquity,
display=display.none)
majorDrawdownThreshold = input.float(
8.0,
"Major drawdown override %",
step=0.5,
group=groupEquity,
display=display.none)
maFastLength = input.int(
10,
"Fast equity MA",
minval=2,
group=groupEquity,
display=display.none)
maMediumLength = input.int(
20,
"Medium equity MA",
minval=2,
group=groupEquity,
display=display.none)
maStructuralLength = input.int(
40,
"Structural equity MA",
minval=2,
group=groupEquity,
display=display.none)
//=====================================================================
// 6. RED FALSE-SIGNAL FILTER
//=====================================================================
groupFilter = "6. Red False-Signal Filter"
useTrendFilter = input.bool(
true,
"Use trend-strength filter",
group=groupFilter,
display=display.none)
slopeLookback = input.int(
4,
"20W MA slope lookback",
minval=1,
group=groupFilter,
display=display.none)
minimumNegativeSlope = input.float(
-0.40,
"Required 20W slope %",
step=0.05,
group=groupFilter,
tooltip="Example: -0.40 means the 20-week MA must have fallen at least 0.40% over the slope lookback.",
display=display.none)
adxLength = input.int(
14,
"ADX DI length",
minval=2,
group=groupFilter,
display=display.none)
adxSmoothing = input.int(
14,
"ADX smoothing",
minval=2,
group=groupFilter,
display=display.none)
minimumADX = input.float(
18.0,
"Minimum weekly ADX",
step=1.0,
group=groupFilter,
tooltip="Higher values make RED harder to trigger. 18-22 is a useful starting range.",
display=display.none)
requireBearishDI = input.bool(
true,
"Require -DI above +DI",
group=groupFilter,
display=display.none)
redPersistenceWeeks = input.int(
2,
"RED confirmation periods",
minval=1,
maxval=4,
group=groupFilter,
tooltip="Raw RED conditions must persist before RED is confirmed.",
display=display.none)
//=====================================================================
// 7. DISPLAY SETTINGS
//=====================================================================
groupDisplay = "7. Display"
showBackground = input.bool(
true,
"Show regime background",
group=groupDisplay,
display=display.none)
showSignals = input.bool(
true,
"Show regime-change signals",
group=groupDisplay,
display=display.none)
showMAs = input.bool(
true,
"Show weekly equity MAs",
group=groupDisplay,
display=display.none)
showDashboard = input.bool(
true,
"Show dashboard",
group=groupDisplay,
display=display.none)
//=====================================================================
// 8. CCC DATA
//=====================================================================
ccc = request.security(
cccSymbol,
macroTF,
close,
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccMA = request.security(
cccSymbol,
macroTF,
ta.sma(close, cccTrendLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccMAPrevious = request.security(
cccSymbol,
macroTF,
ta.sma(close, cccTrendLength)[1],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccChange = request.security(
cccSymbol,
macroTF,
close - close[cccChangeLength],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccMean = request.security(
cccSymbol,
macroTF,
ta.sma(close, zLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccStd = request.security(
cccSymbol,
macroTF,
ta.stdev(close, zLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
cccTrendRising = cccMA > cccMAPrevious
float cccZ = na
if not na(cccStd) and cccStd > 0
cccZ := (ccc - cccMean) / cccStd
//=====================================================================
// 9. BROAD HIGH YIELD DATA
//=====================================================================
hy = request.security(
hySymbol,
macroTF,
close,
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyMA = request.security(
hySymbol,
macroTF,
ta.sma(close, hyTrendLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyMAPrevious = request.security(
hySymbol,
macroTF,
ta.sma(close, hyTrendLength)[1],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyChange = request.security(
hySymbol,
macroTF,
close - close[hyChangeLength],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyMean = request.security(
hySymbol,
macroTF,
ta.sma(close, zLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyStd = request.security(
hySymbol,
macroTF,
ta.stdev(close, zLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
hyTrendRising = hyMA > hyMAPrevious
float hyZ = na
if not na(hyStd) and hyStd > 0
hyZ := (hy - hyMean) / hyStd
//=====================================================================
// 10. WEEKLY EQUITY DATA
//=====================================================================
equityClose = request.security(
syminfo.tickerid,
macroTF,
close,
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
recentHigh = request.security(
syminfo.tickerid,
macroTF,
ta.highest(high, highLookback),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA10 = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maFastLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA10Previous = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maFastLength)[1],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA20 = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maMediumLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA20Previous = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maMediumLength)[1],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA20SlopeBase = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maMediumLength)[slopeLookback],
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
equityMA40 = request.security(
syminfo.tickerid,
macroTF,
ta.sma(close, maStructuralLength),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
ma10Falling = equityMA10 < equityMA10Previous
ma20Falling = equityMA20 < equityMA20Previous
//=====================================================================
// 11. WEEKLY ADX / DIRECTIONAL MOVEMENT
//=====================================================================
[plusDI, minusDI, weeklyADX] = request.security(
syminfo.tickerid,
macroTF,
ta.dmi(adxLength, adxSmoothing),
gaps=barmerge.gaps_off,
lookahead=barmerge.lookahead_off)
bearishDI = minusDI > plusDI
adxTrendStrong = weeklyADX >= minimumADX
//=====================================================================
// 12. EQUITY POSITION
//=====================================================================
float distanceFromHigh = na
if not na(recentHigh) and recentHigh != 0
distanceFromHigh := 100.0 * (recentHigh - equityClose) / recentHigh
equityNearHigh = distanceFromHigh <= nearHighThreshold
belowMA10 = equityClose < equityMA10
belowMA20 = equityClose < equityMA20
belowMA40 = equityClose < equityMA40
float ma20SlopePct = na
if not na(equityMA20SlopeBase) and equityMA20SlopeBase != 0
ma20SlopePct := 100.0 * (equityMA20 - equityMA20SlopeBase) / equityMA20SlopeBase
meaningfulDownSlope = ma20SlopePct <= minimumNegativeSlope
majorDrawdown = distanceFromHigh >= majorDrawdownThreshold
//=====================================================================
// 13. CCC CREDIT CONDITIONS
//=====================================================================
cccAboveTrend = ccc > cccMA
cccMaterialWidening = cccChange >= cccChangeThreshold
cccZWarning = cccZ >= zWarning
cccZStrong = cccZ >= zStrong
cccEarlyStress = cccAboveTrend and cccTrendRising
cccStrongStress = cccAboveTrend and cccTrendRising and (cccMaterialWidening or cccZStrong)
//=====================================================================
// 14. BROAD HIGH YIELD CONDITIONS
//=====================================================================
hyAboveTrend = hy > hyMA
hyMaterialWidening = hyChange >= hyChangeThreshold
hyZWarning = hyZ >= zWarning
hyStress = hyAboveTrend and hyTrendRising and (hyMaterialWidening or hyZWarning)
//=====================================================================
// 15. CREDIT CONFIRMATION
//=====================================================================
creditConfirmed = cccStrongStress and (not requireHY or hyStress)
//=====================================================================
// 16. CREDIT / EQUITY DIVERGENCE
//=====================================================================
creditEquityDivergence = creditConfirmed and equityNearHigh
//=====================================================================
// 17. EQUITY WEAKNESS
//=====================================================================
fastEquityWeakness = distanceFromHigh >= fastDrawdownThreshold and belowMA10 and ma10Falling
strongEquityWeakness = distanceFromHigh >= strongDrawdownThreshold and belowMA20 and ma20Falling
structuralEquityWeakness = belowMA40
//=====================================================================
// 18. SIDEWAYS / TREND FILTER
//=====================================================================
directionFilterPassed = not requireBearishDI or bearishDI
trendStrengthFilter = adxTrendStrong and directionFilterPassed
slopeFilterPassed = meaningfulDownSlope or majorDrawdown
redTrendFilter = trendStrengthFilter and slopeFilterPassed
if not useTrendFilter
redTrendFilter := true
//=====================================================================
// 19. RAW RED CONDITION
//=====================================================================
rawRedCondition = creditConfirmed and (fastEquityWeakness or strongEquityWeakness) and redTrendFilter
//=====================================================================
// 20. RED PERSISTENCE
//=====================================================================
int redCount = 0
if rawRedCondition
redCount := nz(redCount[1]) + 1
else
redCount := 0
redPersistent = redCount >= redPersistenceWeeks
//=====================================================================
// 21. RISK SCORE
//=====================================================================
int riskScore = 0
if cccAboveTrend
riskScore += 10
if cccTrendRising
riskScore += 10
if cccMaterialWidening
riskScore += 10
if cccZStrong
riskScore += 10
else if cccZWarning
riskScore += 5
if hyAboveTrend
riskScore += 5
if hyTrendRising
riskScore += 5
if hyMaterialWidening
riskScore += 10
if hyZWarning
riskScore += 5
if creditEquityDivergence
riskScore += 15
if fastEquityWeakness
riskScore += 5
if strongEquityWeakness
riskScore += 5
if redTrendFilter
riskScore += 5
if structuralEquityWeakness
riskScore += 5
riskScore := math.min(riskScore, 100)
//=====================================================================
// 22. REGIME ENGINE
//=====================================================================
yellowCondition = cccEarlyStress or (cccAboveTrend and cccZWarning)
orangeCondition = creditEquityDivergence
redCondition = redPersistent
int regime = 0
if redCondition
regime := 3
else if orangeCondition
regime := 2
else if yellowCondition
regime := 1
else
regime := 0
//=====================================================================
// 23. REGIME TRANSITIONS
//=====================================================================
previousRegime = nz(regime[1], 0)
newYellow = regime == 1 and previousRegime == 0
newOrange = regime == 2 and previousRegime < 2
newRed = regime == 3 and previousRegime < 3
riskCleared = regime == 0 and previousRegime > 0
//=====================================================================
// 24. COLORS
//=====================================================================
color regimeColor = color.green
if regime == 1
regimeColor := color.yellow
else if regime == 2
regimeColor := color.orange
else if regime == 3
regimeColor := color.red
color backgroundColor = na
if regime == 1
backgroundColor := color.new(color.yellow, 92)
else if regime == 2
backgroundColor := color.new(color.orange, 88)
else if regime == 3
backgroundColor := color.new(color.red, 85)
//=====================================================================
// 25. BACKGROUND
//=====================================================================
bgcolor(showBackground ? backgroundColor : na)
//=====================================================================
// 26. MOVING AVERAGES
//=====================================================================
plot(
showMAs ? equityMA10 : na,
title="10 Week MA",
color=color.blue,
linewidth=1)
plot(
showMAs ? equityMA20 : na,
title="20 Week MA",
color=color.orange,
linewidth=2)
plot(
showMAs ? equityMA40 : na,
title="40 Week MA",
color=color.purple,
linewidth=2)
//=====================================================================
// 27. SIGNAL MARKERS
//=====================================================================
plotshape(
showSignals and newYellow,
title="Yellow Credit Warning",
style=shape.circle,
location=location.abovebar,
color=color.yellow,
textcolor=color.black,
size=size.small,
text="Y")
plotshape(
showSignals and newOrange,
title="Orange Credit Divergence",
style=shape.triangledown,
location=location.abovebar,
color=color.orange,
textcolor=color.white,
size=size.large,
text="CREDIT")
plotshape(
showSignals and newRed,
title="Red Trend Confirmation",
style=shape.triangledown,
location=location.abovebar,
color=color.red,
textcolor=color.white,
size=size.large,
text="RISK")
plotshape(
showSignals and riskCleared,
title="Risk Cleared",
style=shape.triangleup,
location=location.belowbar,
color=color.green,
textcolor=color.white,
size=size.small,
text="CLEAR")
//=====================================================================
// 28. DATA WINDOW
//=====================================================================
plot(
ccc,
title="CCC OAS",
display=display.data_window)
plot(
cccChange,
title="CCC Spread Change",
display=display.data_window)
plot(
cccZ,
title="CCC Z-Score",
display=display.data_window)
plot(
hy,
title="Broad HY OAS",
display=display.data_window)
plot(
hyChange,
title="HY Spread Change",
display=display.data_window)
plot(
hyZ,
title="HY Z-Score",
display=display.data_window)
plot(
distanceFromHigh,
title="Drawdown From 26W High %",
display=display.data_window)
plot(
ma20SlopePct,
title="20W MA Slope %",
display=display.data_window)
plot(
weeklyADX,
title="Weekly ADX",
display=display.data_window)
plot(
plusDI,
title="Weekly +DI",
display=display.data_window)
plot(
minusDI,
title="Weekly -DI",
display=display.data_window)
plot(
riskScore,
title="Macro Risk Score",
display=display.data_window)
//=====================================================================
// 29. DASHBOARD TEXT
//=====================================================================
string regimeText = "GREEN"
if regime == 1
regimeText := "YELLOW"
else if regime == 2
regimeText := "ORANGE"
else if regime == 3
regimeText := "RED"
string equityText = "HEALTHY"
if structuralEquityWeakness and strongEquityWeakness
equityText := "STRUCTURAL WEAKNESS"
else if strongEquityWeakness
equityText := "STRONG WEAKNESS"
else if fastEquityWeakness
equityText := "EARLY WEAKNESS"
string trendText = "SIDEWAYS / WEAK"
if trendStrengthFilter and meaningfulDownSlope
trendText := "BEAR TREND"
else if trendStrengthFilter
trendText := "TRENDING"
else if weeklyADX < minimumADX
trendText := "LOW ADX"
//=====================================================================
// 30. DASHBOARD COLORS
//=====================================================================
color regimeTextColor = color.white
if regime == 1
regimeTextColor := color.black
color cccColor = color.green
if cccChange > 0
cccColor := color.red
color hyColor = color.green
if hyChange > 0
hyColor := color.red
color divergenceColor = color.green
if creditEquityDivergence
divergenceColor := color.orange
color equityColor = color.green
if strongEquityWeakness
equityColor := color.red
else if fastEquityWeakness
equityColor := color.orange
color trendColor = color.green
if trendStrengthFilter and meaningfulDownSlope
trendColor := color.red
else if not trendStrengthFilter
trendColor := color.gray
color structureColor = color.green
if belowMA40
structureColor := color.red
//=====================================================================
// 31. DASHBOARD
//=====================================================================
var table dash = table.new(
position.top_right,
2,
15,
border_width=1)
if barstate.islast and showDashboard
table.cell(
dash,
0,
0,
"MACRO CREDIT",
text_color=color.white,
bgcolor=color.black)
table.cell(
dash,
1,
0,
regimeText,
text_color=regimeTextColor,
bgcolor=regimeColor)
table.cell(
dash,
0,
1,
"Risk Score")
table.cell(
dash,
1,
1,
str.tostring(riskScore) + " / 100",
text_color=regimeColor)
table.cell(
dash,
0,
2,
"CCC OAS")
table.cell(
dash,
1,
2,
str.tostring(ccc, "#.##") + "%")
table.cell(
dash,
0,
3,
"CCC 8W Change")
table.cell(
dash,
1,
3,
str.tostring(cccChange, "#.##") + " pp",
text_color=cccColor)
table.cell(
dash,
0,
4,
"CCC Z-Score")
table.cell(
dash,
1,
4,
str.tostring(cccZ, "#.##"))
table.cell(
dash,
0,
5,
"HY OAS")
table.cell(
dash,
1,
5,
str.tostring(hy, "#.##") + "%")
table.cell(
dash,
0,
6,
"HY 8W Change")
table.cell(
dash,
1,
6,
str.tostring(hyChange, "#.##") + " pp",
text_color=hyColor)
table.cell(
dash,
0,
7,
"HY Z-Score")
table.cell(
dash,
1,
7,
str.tostring(hyZ, "#.##"))
table.cell(
dash,
0,
8,
"From 26W High")
table.cell(
dash,
1,
8,
"-" + str.tostring(distanceFromHigh, "#.##") + "%")
table.cell(
dash,
0,
9,
"Credit Divergence")
table.cell(
dash,
1,
9,
creditEquityDivergence ? "YES" : "NO",
text_color=divergenceColor)
table.cell(
dash,
0,
10,
"Equity Weakness")
table.cell(
dash,
1,
10,
equityText,
text_color=equityColor)
table.cell(
dash,
0,
11,
"Weekly Trend")
table.cell(
dash,
1,
11,
trendText,
text_color=trendColor)
table.cell(
dash,
0,
12,
"ADX")
table.cell(
dash,
1,
12,
str.tostring(weeklyADX, "#.0"))
table.cell(
dash,
0,
13,
"20W Slope")
table.cell(
dash,
1,
13,
str.tostring(ma20SlopePct, "#.##") + "%")
table.cell(
dash,
0,
14,
"40W Structure")
table.cell(
dash,
1,
14,
belowMA40 ? "BELOW" : "ABOVE",
text_color=structureColor)
//=====================================================================
// 32. ALERTS
//=====================================================================
alertcondition(
newYellow,
title="Macro Credit - YELLOW",
message="CCC credit conditions are beginning to deteriorate.")
alertcondition(
newOrange,
title="Macro Credit - ORANGE",
message="Credit deterioration is confirmed while equities remain near recent highs.")
alertcondition(
newRed,
title="Macro Credit - RED",
message="Credit stress is now confirmed by a genuine bearish equity trend.")
alertcondition(
riskCleared,
title="Macro Credit - GREEN",
message="Macro credit stress has returned to GREEN.")
riskScoreAbove70 = riskScore >= 70 and nz(riskScore[1], 0) < 70
alertcondition(
riskScoreAbove70,
title="Macro Credit Risk Score Above 70",
message="Macro credit risk score has crossed above 70 out of 100.")