本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © millerrh based on an idea from Jody Miller
// ============================================================================
// The SPX Intraday Mood Indicator tries to gauge the intraday market direction of the S&P 500 (SPX) by focusing on internal market data.
// Overall strength/weakness is converted into a directional Mood percentage.
// Based on the 0DTE Mood Indicator concept. Key improvements focus on parameter weighting as opposed to binary conditions.
// Calculation methods enhanced to better represent trend data.
// Use at your own risk and discretion. Potential trade ideas offer no guarantees. Intraday Charts Only. Turn off extended hours data. Only works on SPX.
// ============================================================================
//@version=4
// need to remove these two variables...not sure what this is.
asd1 = float(0)
stage = string('empty')
study('SPX Intraday Mood', overlay = false)
// === USER INPUTS ===
// Configuration Inputs
smoothingLength = input(defval = 3, minval = 1, maxval = 10, title = "Smoothing Length", group = "Configuration Inputs",
tooltip = "Smooths out plotted Mood Value by using an exponential average. \n• To remove smoothing set = 1 \n• Recommended Value = 3 \n• Max Value = 10")
avgLength = input(defval = 5, minval = 1, maxval = 10, title = "Average Length", group = "Configuration Inputs",
tooltip = "Used for many interal average calculations. Fast calculations excluding averages are used at market open. Normal calculation resumes after average length.\n• Recommeded Value = 5 \n• Max Value = 10")
moodRecommendationPercent = input(defval = 40, minval = 0, maxval = 100, title = "Mood Recommendation Percent", group = "Configuration Inputs",
tooltip = "Mood Value used to make a directional call. Lower values are more aggressive. \n• Recommended value = 30-50")
potentialTrade = input(defval = true, type = input.bool, title = "Show Potential Trade?", group = "Configuration Inputs",
tooltip = "Shows the 0 DTE trade recommendation - Put/Call Spread or Iron Condor.")
showMoodRanges = input(defval = true, type = input.bool, title = "Show Mood Ranges?", group = "Configuration Inputs",
tooltip = "Plots the Mood Recommendation (Bullish/Bearish) lines.")
showInternalDivergence = input(defval = true, type = input.bool, title = "Show Internal Divergence?", group = "Configuration Inputs",
tooltip = "Indicates a potential trend change or end of current trend.")
// alerts = input(defval = true, type = bool, title = "Alerts?") // This may not be relevant for TV
// Sector Weight Inputs - UPDATE VALUES AT LEAST ONCE PER YEAR TO MATCH S&P 500 VALUES!
informationTechnologyWeight = input(defval = 27.61, type = input.float, title = "Information Technology", group = "Sector Weighting - Percent of S&P 500")
healthCareWeight = input(defval = 13.46, type = input.float, title = "Healthcare", group = "Sector Weighting - Percent of S&P 500")
consumerDiscretionaryWeight = input(defval = 12.72, type = input.float, title = "Consumer Discretionary", group = "Sector Weighting - Percent of S&P 500")
communicationsWeight = input(defval = 10.77, type = input.float, title = "Communications", group = "Sector Weighting - Percent of S&P 500")
financialsWeight = input(defval = 10.44, type = input.float, title = "Financials", group = "Sector Weighting - Percent of S&P 500")
industrialsWeight = input(defval = 8.4, type = input.float, title = "Industrials", group = "Sector Weighting - Percent of S&P 500")
consumerStaplesWeight = input(defval = 6.51, type = input.float, title = "Consumer Staples", group = "Sector Weighting - Percent of S&P 500")
utilitiesWeight = input(defval = 2.76, type = input.float, title = "Utilities", group = "Sector Weighting - Percent of S&P 500")
materialsWeight = input(defval = 2.63, type = input.float, title = "Materials", group = "Sector Weighting - Percent of S&P 500")
realEstateWeight = input(defval = 2.42, type = input.float, title = "Real Estate", group = "Sector Weighting - Percent of S&P 500")
energyWeight = input(defval = 2.28, type = input.float, title = "Energy", group = "Sector Weighting - Percent of S&P 500")
// Sector Weighted Error Check
sectorWeightSum = informationTechnologyWeight + healthCareWeight + consumerDiscretionaryWeight + communicationsWeight + financialsWeight + industrialsWeight + consumerStaplesWeight + utilitiesWeight + materialsWeight + realEstateWeight + energyWeight
// need to figure out a way to show this error and maybe one for if you look at this on other charts? OR maybe also when not in session since uses internal data?
// consider using a boolean to check to see if sectorWeightSum is not equal to 100. If so, throw up a table cell error and maybe turn off visuals as well?
// === SPX PERCENT CHANGE ===
closeSPX = security(syminfo.tickerid, "D", close) // SPX Close - assumes chart is on SPX
SPXchg = (close - closeSPX)/closeSPX * 100
SPXchgRnd = round(SPXchg, 2) // ~ variable for populating into table
// plot(SPXchg)
trendUp = .25
trendDown = -.25
SPXPctChangePoints = if SPXchg > trendUp * 6
2
else if SPXchg > trendUp * 4
1.5
else if SPXchg > trendUp
1
else if SPXchg < trendDown * 6
-2
else if SPXchg < trendDown * 4
-1.5
else if SPXchg < trendDown
-1
else
0
// === SECTOR WEIGHTED CHANGE ===
// Functions to define the change
dailyCloseSec(sec) => security("sec", "D", close) // Daily close of the sector
closeSec(sec) => security("sec", "", close) // current chart timeframe bar close of the sector
// Variables for each sector with weights
XLKchg = (closeSec("AMEX:XLK") - dailyCloseSec("AMEX:XLK")) / dailyCloseSec("AMEX:XLK") * 100 * informationTechnologyWeight
XLVchg = (closeSec("AMEX:XLV") - dailyCloseSec("AMEX:XLV")) / dailyCloseSec("AMEX:XLV") * 100 * healthCareWeight
XLYchg = (closeSec("AMEX:XLY") - dailyCloseSec("AMEX:XLY")) / dailyCloseSec("AMEX:XLY") * 100 * consumerDiscretionaryWeight
XLCchg = (closeSec("AMEX:XLC") - dailyCloseSec("AMEX:XLC")) / dailyCloseSec("AMEX:XLC") * 100 * communicationsWeight
XLFchg = (closeSec("AMEX:XLF") - dailyCloseSec("AMEX:XLF")) / dailyCloseSec("AMEX:XLF") * 100 * financialsWeight
XLIchg = (closeSec("AMEX:XLI") - dailyCloseSec("AMEX:XLI")) / dailyCloseSec("AMEX:XLI") * 100 * industrialsWeight
XLPchg = (closeSec("AMEX:XLP") - dailyCloseSec("AMEX:XLP")) / dailyCloseSec("AMEX:XLP") * 100 * consumerStaplesWeight
XLUchg = (closeSec("AMEX:XLU") - dailyCloseSec("AMEX:XLU")) / dailyCloseSec("AMEX:XLU") * 100 * utilitiesWeight
XLBchg = (closeSec("AMEX:XLB") - dailyCloseSec("AMEX:XLB")) / dailyCloseSec("AMEX:XLB") * 100 * materialsWeight
XLREchg =(closeSec("AMEX:XLRE") - dailyCloseSec("AMEX:XLRE")) / dailyCloseSec("AMEX:XLRE") * 100 * realEstateWeight
XLEchg =(closeSec("AMEX:XLE") - dailyCloseSec("AMEX:XLE")) / dailyCloseSec("AMEX:XLE") * 100 * energyWeight
sectorChg = (XLKchg + XLVchg + XLYchg + XLCchg + XLFchg + XLIchg + XLPchg + XLUchg + XLBchg + XLREchg + XLEchg) / 100
sectorDif = sectorChg - SPXchg
sectorDifRnd = round(sectorDif, 3) // ~ variable for sector pull in table
sectorPctChangePoints = sectorChg > SPXchg ? 1 : -1
emaSector = ema(sectorDif, avgLength)
sectorAvgPoints = sectorDif > emaSector ? 1 : sectorDif < emaSector ? -1 : 0
// === MARKET INTERNALS ===
// S&P Tick (uses NYSE tick data instead of S&P)
tickTrend = 50
instantTick = security("USI:TICK", "", close) // ~ varaible for tick information for table
smoothedTick = security("USI:TICK", "", hlc3)
tickspPoints = smoothedTick > tickTrend ? 1 : smoothedTick < tickTrend * -1 ? -1 : 0
emaTick = ema(smoothedTick, avgLength)
tickspAvgPoints = smoothedTick > emaTick ? 1 : smoothedTick < emaTick ? -1 : 0
// this code above for tickspAvgPoints uses "smoothedTick" instead of "tikAvg" because I couldn't tell the difference between the two in the original code
// Circle back to this if something breaks.
// S&P UVOL-DVOL
volTrend = 1.2
UVOL = security("USI:UVOL", "", close)
DVOL = security("USI:DVOL", "", close)
UvolDvolRatio = UVOL >= DVOL ? UVOL/DVOL : -DVOL/UVOL
UvolDvolRatioRnd = round(UvolDvolRatio, 2) // ~ varaible for Uvol/dvol for table
UDRatioPoints = if UvolDvolRatio > volTrend * 3
3
else if UvolDvolRatio > volTrend * 2
2
else if UvolDvolRatio > volTrend
1
else if UvolDvolRatio < volTrend * -3
-3
else if UvolDvolRatio < volTrend * -2
-2
else if UvolDvolRatio < volTrend
-1
else
0
emaUD = ema(UvolDvolRatio, avgLength)
UDRatioAvgPoints = UvolDvolRatio > emaUD ? 1 : UvolDvolRatio < emaUD ? -1 : 0
// S&P Advance/Decline
adspd = security("USI:ADVDEC.NY", "", close)
ADPoints = if adspd > 300
3
else if adspd > 200
2
else if adspd > 50
1
else if adspd < -300
-3
else if adspd < -200
-2
else if adspd < -50
-1
else
0
emaAD = ema(ADPoints, avgLength)
ADAvgPoints = ADPoints > emaAD ? 1 : ADPoints < emaAD ? -1 : 0
// ~ add varaible for S&P advance delcline here for table
// === MARKET STAGE ===
price = close
length = 10
tmp1 = max(0, change(price))
tmp2 = min(0, change(price))
d2 = sum(tmp1, length)
d4 = sum(tmp2, length)
cond = d2 + d4 == 0
ad3 = cond ? 0 : (d2 - d4) / (d2 + d4) * 100
coeff = 2 / (length + 1) * abs(ad3) / 100
asd = coeff*price+(asd1)*(1-coeff) // not really sure how this line works vs "CompoundValue" in TOS
asd1 := asd[1] // related to above comment
VMA = asd
volumeSPX = security('SP:SPX',"", volume)
vwma8 = sum(volumeSPX * close, 8) / sum(volumeSPX, 8)
vwma21 = sum(volumeSPX * close, 21) / sum(volumeSPX, 21)
vwma34 = sum(volumeSPX * close, 34) / sum(volumeSPX, 34)
bullish = vwma8 > vwma21 and vwma21 > vwma34 ? 1 : 0
bearish = vwma8 < vwma21 and vwma21 < vwma34 ? 1 : 0
distribution = not bullish and not bearish ? 1 : 0
marketStagePoints = bullish ? 2 : bearish? -2 : price >= VMA ? 1 : price < VMA ? -1 : 0
stageTable = bullish ? "Stage: Acceleration" : bearish ? "Stage: Deceleration" : price >= VMA ? "Stage: Accumulation" : "Stage: Distribution"
// === MARKET MOOD ===
// Component weighting
comp1 = SPXPctChangePoints * 1
comp2 = sectorPctChangePoints * 1
comp3 = sectorAvgPoints * 1.5
comp4 = tickspPoints * 1
comp5 = tickspAvgPoints * 1.25
comp6 = UDRatioPoints * 1
comp7 = UDRatioAvgPoints * 1.25
comp8 = ADPoints * 1
comp9 = ADAvgPoints * 1.25
comp10 = marketStagePoints * 1
inSession = time(timeframe.period, "0930-1600")
moodNormalCalc = avg(comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8, comp9, comp10) * 100
moodBase = moodNormalCalc < 0 ? max(moodNormalCalc, -100) : min(moodNormalCalc, 100)
currentMood = ema(moodBase, smoothingLength)
currentMoodTable = currentMood > moodRecommendationPercent ? "Mood: Bullish " + tostring(round(currentMood, 2)) + "%" :
currentMood < moodRecommendationPercent * -1 ? "Mood: Bearish " + tostring(round(currentMood, 2)) + "%" :
"Mood: Neutral " + tostring(round(currentMood, 2)) + "%"
// ~use for table
condition = currentMood > moodRecommendationPercent ? 1 : currentMood < moodRecommendationPercent ? -1 : 0
// === RECOMMENDATIONS ===
zonestep = (100 - moodRecommendationPercent) / 2
recommendation = if (currentMood > moodRecommendationPercent) and (currentMood <= moodRecommendationPercent + zonestep)
1 // Skewed Bullish Iron Condor
else if currentMood > (moodRecommendationPercent + zonestep)
2 // Put Spread
else if currentMood < ((moodRecommendationPercent * -1) + -zonestep)
-2 // Call Spread
else if (currentMood < moodRecommendationPercent * -1) and (currentMood >= (moodRecommendationPercent * -1) - zonestep)
-1 // Skewed Bearish Iron Condor
else
0 // Iron Condor
recommendationTable = recommendation == 1 ? "Potential Trade: Skewed Bullish Iron Condor" :
recommendation == 2 ? "Potential Trade: Put Spread" :
recommendation == -2 ? "Potential Trade: Call Spread" :
recommendation == -1 ? "Potential Trade: Skewed Bearish Iron Condor" :
recommendation == 0 ? "Potential Trade: Iron Condor" : na
// ~ variable for the table about the recommended trades above
// === INTERNAL DIVERGENCE ==
// internalDivergence = (SPXChg > sma(SPXChg, avgLength) and currentMood < currentMood[1] and currentMood[1] < currentMood[2])? +Infinity : 0
// Not sure we can represent "infinity" in Pine.
// === PLOTTING AND TABLES ===
// Plotting
bullline = showMoodRanges ? moodRecommendationPercent : na
bearline = showMoodRanges ? -moodRecommendationPercent : na
zeroline = 0
topline = 100
bottomline = -100
tableline = 150
posColor = color.rgb(38, 166, 154)
negColor = color.rgb(240, 83, 80)
neuColor = color.new(#888888, 0)
moodColor = currentMood >= moodRecommendationPercent ? color.new(posColor, 0) : currentMood <= moodRecommendationPercent * -1 ? color.new(negColor, 0) : color.new(neuColor, 0)
plot(currentMood, color = moodColor)
plot(bullline, color=color.new(posColor, 60), linewidth = 1)
plot(bearline, color=color.new(negColor, 60), linewidth = 1)
plot(zeroline, color=color.new(neuColor, 60), linewidth = 1)
plot(topline, color=color.new(color.gray, 60), linewidth = 1)
plot(bottomline, color=color.new(color.gray, 60), linewidth = 1)
plot(tableline, color=color.new(color.white, 100), linewidth =1)
// Table Dashboard (8 columns)
var table moodTable = table.new(position.top_left, 8, 1, border_width = 3)
f_fillCell(_column, _cellText, _c_color) =>
table.cell(moodTable, _column, 0, _cellText, bgcolor = color.new(_c_color, 70), text_color = _c_color)
if barstate.islast
f_fillCell(0, "SPX Change: " + tostring(SPXchgRnd) +"%", SPXchgRnd > 0 ? posColor : negColor)
f_fillCell(1, "Sector Pull: " + tostring(sectorDifRnd) +"%", sectorPctChangePoints == 1 ? posColor : sectorPctChangePoints == -1 ? negColor: neuColor)
f_fillCell(2, "TICK.US: " + tostring(instantTick), instantTick > tickTrend ? posColor : instantTick < tickTrend ? negColor : neuColor)
f_fillCell(3, tostring(UvolDvolRatioRnd) + ":1 VOL", UvolDvolRatioRnd > volTrend ? posColor : UvolDvolRatioRnd < volTrend ? negColor : neuColor)
f_fillCell(4, "ADSPD: " + tostring(adspd), ADPoints >= 1 ? posColor : ADPoints <= 1 ? negColor : neuColor)
f_fillCell(5, stageTable, bullish ? posColor : bearish ? negColor : neuColor)
f_fillCell(6, currentMoodTable, currentMood > moodRecommendationPercent ? posColor : currentMood < moodRecommendationPercent *-1 ? negColor : neuColor)
f_fillCell(7, recommendationTable, recommendation == 0 ? neuColor : recommendation == 1 or 2 ? posColor : recommendation == -1 or -2 ? negColor : na)