Indicator · Pine Script v6 · On the chart

Industry Indices Comparison

by etnt· code credited to kruskakli

This indicator displays an on-chart comparison table tracking eleven major industry sector ETFs against a benchmark index, typically SPY.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code302
Settings28inputs
LicenceMPL-2.0
Last update1 year ago3 Aug 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

302 lines of Pine Script v6 from PineScript/industry-indices-comparison.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

industry-indices-comparison.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kruskakli
//@version=6
// @description Industry Sector Performance Analyzer
//
// PURPOSE:
// This indicator provides real-time analysis of major industry sectors' performance relative to the broader market,
// helping traders and investors identify sector rotation, market leadership, and potential trading opportunities.
//
// KEY FEATURES:
// 1. Comprehensive Sector Coverage:
//    - Tracks 11 major S&P 500 sector ETFs: Technology (XLK), Financials (XLF), Energy (XLE), Healthcare (XLV),
//      Industrials (XLI), Basic Materials (XLB), Consumer Staples (XLP), Consumer Discretionary (XLY),
//      Real Estate (XLRE), Utilities (XLU), and Telecommunications (XLC)
//    - Compares each sector against a benchmark index (default: SPY)
//
// 2. Performance Metrics:
//    - Current Price: Real-time price for each sector ETF
//    - Performance %: Price change over selected timeframe (1D/1W/1M/3M)
//    - Relative Strength: Sector performance vs benchmark (outperform/underperform)
//    - Trend Indicator: Visual markers (▲ up, ▼ down, − neutral)
//    - Volume Analysis: Trading volume in millions of shares
//
// 3. Visual Features:
//    - Color-coded performance (Green = outperform, Red = underperform)
//    - Customizable table position (4 corner options)
//    - Adjustable text size (Tiny/Small/Normal)
//    - Clean, organized data presentation
//
// REFERENCES & THEORY:
// 1. Market Trend Analysis:
//    - Dow Theory (Charles Dow): Markets move in trends; primary, secondary, and minor
//    - Reference: "Technical Analysis of Stock Trends" by Robert D. Edwards and John Magee
//    - Link: https://www.investopedia.com/terms/d/dowtheory.asp
//
// 2. Sector Rotation Model:
//    - Sam Stovall's Sector Rotation: Sectors move in predictable patterns through economic cycles
//    - Reference: "Standard & Poor's Guide to Sector Investing" by Sam Stovall
//    - Economic Cycle Stages:
//      * Early Recession: Consumer Staples, Utilities, Healthcare
//      * Full Recession: Consumer Staples, Utilities
//      * Early Recovery: Technology, Basic Materials, Industrials
//      * Full Recovery: Energy, Materials, Industrials
//    - Link: https://www.investopedia.com/articles/trading/05/020305.asp
//
// 3. Relative Strength Theory:
//    - Developed by J. Welles Wilder Jr.
//    - Reference: "New Concepts in Technical Trading Systems"
//    - Principle: Strong sectors tend to stay strong; momentum persists
//    - Link: https://www.investopedia.com/terms/r/relativestrength.asp
//
// 4. Volume Analysis:
//    - Richard Wyckoff's Market Theory
//    - Reference: "Studies in Tape Reading" by Richard D. Wyckoff
//    - Importance of volume confirmation in trend analysis
//    - Link: https://www.investopedia.com/articles/active-trading/070715/making-money-wyckoff-way.asp
//
// 5. Modern Applications:
//    - "Intermarket Analysis" by John J. Murphy
//    - "Trading with Intermarket Analysis" by John J. Murphy
//    - Explains relationships between different market sectors
//    - Link: https://www.investopedia.com/terms/i/intermarket-analysis.asp
//
// HOW IT WORKS:
// 1. Data Collection:
//    - Fetches real-time price and volume data for each sector ETF
//    - Calculates performance over user-selected timeframe
//    - Computes relative performance against benchmark
//
// 2. Analysis:
//    - Determines sector trends based on price movement
//    - Identifies outperforming/underperforming sectors
//    - Monitors volume patterns for confirmation
//
// 3. Display:
//    - Organizes data in an easy-to-read table format
//    - Updates continuously during market hours
//    - Highlights important metrics through color coding
//
// PRACTICAL APPLICATIONS:
// 1. Sector Rotation Strategy:
//    - Identify which sectors are leading/lagging
//    - Spot early signs of sector rotation
//    - Time sector-based trades
//
// 2. Risk Management:
//    - Monitor sector exposure
//    - Identify market trends through sector performance
//    - Validate broader market moves
//
// 3. Portfolio Management:
//    - Guide sector allocation decisions
//    - Identify potential sector opportunities
//    - Track sector momentum
//
// USAGE INSTRUCTIONS:
// 1. Setup:
//    - Add indicator to your chart
//    - Select preferred benchmark (default: SPY)
//    - Choose comparison timeframe (1D/1W/1M/3M)
//    - Adjust table position and text size if needed
//
// 2. Analysis:
//    - Green/Red colors show outperformance/underperformance
//    - Use trend arrows for quick direction reference
//    - Compare volume patterns with price movement
//    - Monitor relative performance vs benchmark
//
// 3. Trading Applications:
//    - Long opportunities: Focus on outperforming sectors
//    - Short opportunities: Consider underperforming sectors
//    - Pair trades: Compare related sectors
//    - Sector rotation: Track performance shifts
//
// CUSTOMIZATION OPTIONS:
// - Benchmark Selection: Choose any market index
// - Timeframe: Select from 1D, 1W, 1M, or 3M comparisons
// - Visual Settings: Adjust table position, text size, and colors
// - Sector Names: Customize display names for each sector
//
// This indicator is ideal for traders and investors who want to:
// - Make informed sector-based trading decisions
// - Understand market dynamics through sector analysis
// - Implement sector rotation strategies
// - Monitor sector-specific opportunities
// - Validate broader market trends

indicator("Industry Indices Comparison", overlay=true)

// Color constants
GREEN = color.new(#26a69a, 0)
RED = color.new(#ef5350, 0)
GRAY = color.new(#787B86, 0)
TEXT_COLOR = color.new(#FFFFFF, 0)

// Input parameters
// Benchmark selection
benchmarkSymbol = input.symbol("SPY", "Benchmark Index", group="Index Selection")

// Industry indices selection
index1Symbol = input.symbol("XLK", "Technology Index", group="Index Selection")
index2Symbol = input.symbol("XLF", "Financials Index", group="Index Selection")
index3Symbol = input.symbol("XLE", "Energy Index", group="Index Selection")
index4Symbol = input.symbol("XLV", "Healthcare Index", group="Index Selection")
index5Symbol = input.symbol("XLI", "Industrials Index", group="Index Selection")
index6Symbol = input.symbol("XLB", "Materials Index", group="Index Selection")
index7Symbol = input.symbol("XLP", "Consumer Staples Index", group="Index Selection")
index8Symbol = input.symbol("XLY", "Consumer Discretionary Index", group="Index Selection")
index9Symbol = input.symbol("XLRE", "Real Estate Index", group="Index Selection")
index10Symbol = input.symbol("XLU", "Utilities Index", group="Index Selection")
index11Symbol = input.symbol("XLC", "Telecommunications Index", group="Index Selection")

// Industry names
index1Name = input.string("Technology", "Technology Name", group="Industry Names")
index2Name = input.string("Financials", "Financials Name", group="Industry Names")
index3Name = input.string("Energy", "Energy Name", group="Industry Names")
index4Name = input.string("Healthcare", "Healthcare Name", group="Industry Names")
index5Name = input.string("Industrials", "Industrials Name", group="Industry Names")
index6Name = input.string("Materials", "Materials Name", group="Industry Names")
index7Name = input.string("Consumer Staples", "Consumer Staples Name", group="Industry Names")
index8Name = input.string("Consumer Discretionary", "Consumer Discretionary Name", group="Industry Names")
index9Name = input.string("Real Estate", "Real Estate Name", group="Industry Names")
index10Name = input.string("Utilities", "Utilities Name", group="Industry Names")
index11Name = input.string("Telecommunications", "Telecommunications Name", group="Industry Names")

// Timeframe selection
timeframeInput = input.string("1M", "Comparison Timeframe", options=["1D", "1W", "1M", "3M"], group="Settings")

// Visual settings
tablePosition = input.string("Top Right", "Table Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group="Appearance")
textSize = input.string("Small", "Text Size", options=["Tiny", "Small", "Normal"], group="Appearance")
outperformColor = input.color(GREEN, "Outperform Color", group="Appearance")
underperformColor = input.color(RED, "Underperform Color", group="Appearance")

// Helper functions
getTimeframeOffset() =>
    offset = switch timeframeInput
        "1D" => 1
        "1W" => 7
        "1M" => 30
        "3M" => 90
        => 30  // Default to 1M

getPerformance(sym) =>
    float performance = 0.0
    offset = getTimeframeOffset()
    [currentClose, prevClose] = request.security(sym, timeframe.period, [close, close[offset]])
    if prevClose != 0
        performance := ((currentClose - prevClose) / prevClose) * 100
    performance

// Calculate performances
var benchmarkPerf = 0.0
var index1Perf = 0.0
var index2Perf = 0.0
var index3Perf = 0.0
var index4Perf = 0.0
var index5Perf = 0.0
var index6Perf = 0.0
var index7Perf = 0.0
var index8Perf = 0.0
var index9Perf = 0.0
var index10Perf = 0.0
var index11Perf = 0.0

if barstate.islast
    benchmarkPerf := getPerformance(benchmarkSymbol)
    index1Perf := getPerformance(index1Symbol)
    index2Perf := getPerformance(index2Symbol)
    index3Perf := getPerformance(index3Symbol)
    index4Perf := getPerformance(index4Symbol)
    index5Perf := getPerformance(index5Symbol)
    index6Perf := getPerformance(index6Symbol)
    index7Perf := getPerformance(index7Symbol)
    index8Perf := getPerformance(index8Symbol)
    index9Perf := getPerformance(index9Symbol)
    index10Perf := getPerformance(index10Symbol)
    index11Perf := getPerformance(index11Symbol)

// Calculate relative performances
relativePerf1 = index1Perf - benchmarkPerf
relativePerf2 = index2Perf - benchmarkPerf
relativePerf3 = index3Perf - benchmarkPerf
relativePerf4 = index4Perf - benchmarkPerf
relativePerf5 = index5Perf - benchmarkPerf
relativePerf6 = index6Perf - benchmarkPerf
relativePerf7 = index7Perf - benchmarkPerf
relativePerf8 = index8Perf - benchmarkPerf
relativePerf9 = index9Perf - benchmarkPerf
relativePerf10 = index10Perf - benchmarkPerf
relativePerf11 = index11Perf - benchmarkPerf

// Format numbers
formatPerf(value) =>
    str.tostring(math.round(value, 2)) + "%"

// Table position
var tablePos = switch tablePosition
    "Top Right" => position.top_right
    "Top Left" => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left" => position.bottom_left
    => position.top_right

// Text size
var txtSize = switch textSize
    "Tiny" => size.tiny
    "Small" => size.small
    "Normal" => size.normal
    => size.small

// Create and populate table
var table perfTable = table.new(tablePos, 6, 13, border_width=1)

// Function to determine trend
getTrendSymbol(perf) =>
    perf > 0 ? "▲" : perf < 0 ? "▼" : "−"

// Function to get cell color based on performance
getCellColor(perf) =>
    perf > 0 ? outperformColor : perf < 0 ? underperformColor : GRAY

// Function to add index row
addIndexRow(sym, name, perf, relPerf, rowNum) =>
    [price, vol] = request.security(sym, timeframe.period, [close, volume])
    table.cell(perfTable, 0, rowNum, name, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 1, rowNum, str.tostring(math.round(price, 2)), text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 2, rowNum, formatPerf(perf), text_color=TEXT_COLOR, bgcolor=getCellColor(perf), text_size=txtSize)
    table.cell(perfTable, 3, rowNum, formatPerf(relPerf), text_color=TEXT_COLOR, bgcolor=getCellColor(relPerf), text_size=txtSize)
    table.cell(perfTable, 4, rowNum, getTrendSymbol(perf), text_color=getCellColor(perf), text_size=txtSize)
    table.cell(perfTable, 5, rowNum, str.tostring(math.round(vol/1000000, 1)) + "M", text_color=TEXT_COLOR, text_size=txtSize)

if barstate.islast
    // Headers
    table.cell(perfTable, 0, 0, "Industry", bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 1, 0, "Price", bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 2, 0, timeframeInput + " %", bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 3, 0, "vs " + benchmarkSymbol, bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 4, 0, "Trend", bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 5, 0, "Volume", bgcolor=GRAY, text_color=TEXT_COLOR, text_size=txtSize)

    // Benchmark row
    [benchPrice, benchVol] = request.security(benchmarkSymbol, timeframe.period, [close, volume])
    table.cell(perfTable, 0, 1, benchmarkSymbol, text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 1, 1, str.tostring(math.round(benchPrice, 2)), text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 2, 1, formatPerf(benchmarkPerf), text_color=TEXT_COLOR, bgcolor=getCellColor(benchmarkPerf), text_size=txtSize)
    table.cell(perfTable, 3, 1, "Benchmark", text_color=TEXT_COLOR, text_size=txtSize)
    table.cell(perfTable, 4, 1, getTrendSymbol(benchmarkPerf), text_color=getCellColor(benchmarkPerf), text_size=txtSize)
    table.cell(perfTable, 5, 1, str.tostring(math.round(benchVol/1000000, 1)) + "M", text_color=TEXT_COLOR, text_size=txtSize)

    // Add industry index rows
    addIndexRow(index1Symbol, index1Name, index1Perf, relativePerf1, 2)
    addIndexRow(index2Symbol, index2Name, index2Perf, relativePerf2, 3)
    addIndexRow(index3Symbol, index3Name, index3Perf, relativePerf3, 4)
    addIndexRow(index4Symbol, index4Name, index4Perf, relativePerf4, 5)
    addIndexRow(index5Symbol, index5Name, index5Perf, relativePerf5, 6)
    addIndexRow(index6Symbol, index6Name, index6Perf, relativePerf6, 7)
    addIndexRow(index7Symbol, index7Name, index7Perf, relativePerf7, 8)
    addIndexRow(index8Symbol, index8Name, index8Perf, relativePerf8, 9)
    addIndexRow(index9Symbol, index9Name, index9Perf, relativePerf9, 10)
    addIndexRow(index10Symbol, index10Name, index10Perf, relativePerf10, 11)
    addIndexRow(index11Symbol, index11Name, index11Perf, relativePerf11, 12)

Overview

Industry Indices Comparison calculates percentage price changes over a selectable timeframe, evaluates relative strength versus the benchmark, provides trend direction markers, and displays trading volume for each sector. Users can customize the sector symbols, benchmark index, evaluation timeframe, table placement, text size, and performance highlight colors. The indicator renders exclusively as a dashboard table on the price chart without plotting price overlays or generating direct trade signals.

Details

Published by

etnt on GitHub

Code credit

kruskakli, as written in the script's header

Draws

On the price chart

Markets

Stocks, Indices

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Benchmark IndexsymbolSPYbenchmarkSymbol
Technology IndexsymbolXLKindex1Symbol
Financials IndexsymbolXLFindex2Symbol
Energy IndexsymbolXLEindex3Symbol
Healthcare IndexsymbolXLVindex4Symbol
Industrials IndexsymbolXLIindex5Symbol
Materials IndexsymbolXLBindex6Symbol
Consumer Staples IndexsymbolXLPindex7Symbol
Consumer Discretionary IndexsymbolXLYindex8Symbol
Real Estate IndexsymbolXLREindex9Symbol
Utilities IndexsymbolXLUindex10Symbol
Telecommunications IndexsymbolXLCindex11Symbol
Show all 28 settings
SettingTypeDefaultVariable
Technology NamestringTechnologyindex1Name
Financials NamestringFinancialsindex2Name
Energy NamestringEnergyindex3Name
Healthcare NamestringHealthcareindex4Name
Industrials NamestringIndustrialsindex5Name
Materials NamestringMaterialsindex6Name
Consumer Staples NamestringConsumer Staplesindex7Name
Consumer Discretionary NamestringConsumer Discretionaryindex8Name
Real Estate NamestringReal Estateindex9Name
Utilities NamestringUtilitiesindex10Name
Telecommunications NamestringTelecommunicationsindex11Name
Comparison Timeframestring1MtimeframeInput
Table PositionstringTop RighttablePosition
Text SizestringSmalltextSize
Outperform ColorcolorGREENoutperformColor
Underperform ColorcolorREDunderperformColor
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This indicator overlays an intraday SPX and ES chart with a midnight session range, regular-trading-hours opening levels, and a VWAP projection box. It draws the midnight high, mid, and low, flags edge rejections within an absolute tolerance, and plots optiona

Indicator v6 TrendSupport & resistance
Updated 7 weeks ago · None stated GitHub repository of SPX Midnight Box + Snag Logic
228 stars

TradersPost Trading Checklist is an overlay indicator that evaluates a suite of popular technical conditions for long and short trade setups. It checks session-anchored VWAP, fast and slow EMA alignments and crosses, 200 SMA, RSI overbought or oversold conditi

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of TradersPost Trading Checklist
92 stars

This indicator classifies the market into gamma regime types (negative gamma trend, positive gamma mean-reversion, or transition) by calculating a composite score based on daily ATR ratios, session VWAP crossover frequencies, and opening range displacement. It

Indicator v5 Volatility & bandsTrend
Updated 2 months ago · Custom licence GitHub repository of Moon Dev GEX Regime & Trap

EMA Ribbon Overlay

by iamrichardD
57 stars

Calculates exponential moving averages for fast, pivot, and slow lengths along with optional 50, 100, and 200 simple moving average context lines. It visualizes bullish and bearish ribbon fills on the main price chart alongside MACD calculations to generate ea

Indicator v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon Overlay
53 stars

Apex Trend & Liquidity Master calculates a trend cloud using customizable moving averages expanded by a volatility multiplier directly on the main price chart. It identifies dynamic support and resistance liquidity zones from swing high and low pivots, extendi

Indicator v6 TrendSupport & resistance
Updated 2 months ago · MPL-2.0 GitHub repository of Apex Trend & Liquidity Master

More Screeners & dashboards scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers