S&P 500 Sector Performance for ThinkorSwim

tomsk

Well-known member
VIP
I found an S&P 500 Sector Performance chart from the Yahoo ThinkScript newsgroup, written by Jaimie Pinto that folks might find interesting.
It was written sometime ago but still very applicable today. Please enjoy it!

Code:
# PINTO_SectorsOverlay
# Emulation of the PerfChart: S&P Sector ETFs
# http://stockcharts.com/freecharts/perf.php?[SECT]
# Updated on May/22/2012

declare upper;

input ShowOverlay    = yes;
input pivot          = 180;  ### bars
input length         = 4;
input displace       = 3;
input SnP500         = "SPY";
input Cyclicals      = "XLY";
input Technology     = "XLK";
input Industrials    = "XLI";
input Materials      = "XLB";
input Energy         = "XLE";
input Staples        = "XLP";
input HealthCare     = "XLV";
input Utilities      = "XLU";
input Financials     = "XLF";

def BasePrice        = WildersAverage(open             , length)[-length + displace];
def SnP500Price      = WildersAverage(open(SnP500)     , length)[-length + displace];
def CyclicalsPrice   = WildersAverage(open(Cyclicals)  , length)[-length + displace];
def TechnologyPrice  = WildersAverage(open(Technology) , length)[-length + displace];
def IndustrialsPrice = WildersAverage(open(Industrials), length)[-length + displace];
def MaterialsPrice   = WildersAverage(open(Materials)  , length)[-length + displace];
def EnergyPrice      = WildersAverage(open(Energy)     , length)[-length + displace];
def StaplesPrice     = WildersAverage(open(Staples)    , length)[-length + displace];
def HealthCarePrice  = WildersAverage(open(HealthCare) , length)[-length + displace];
def UtilitiesPrice   = WildersAverage(open(Utilities)  , length)[-length + displace];
def FinancialsPrice  = WildersAverage(open(Financials) , length)[-length + displace];

def barNumber        = if barNumber() > pivot then barNumber() else 1;
def BaseOpen         = if barNumber == 1 then basePrice        else BaseOpen[1];
def SnP500Open       = if barNumber == 1 then SnP500Price      else SnP500Open[1];
def CyclicalsOpen    = if barNumber == 1 then CyclicalsPrice   else CyclicalsOpen[1];
def TechnologyOpen   = if barNumber == 1 then TechnologyPrice  else TechnologyOpen[1];
def IndustrialsOpen  = if barNumber == 1 then IndustrialsPrice else IndustrialsOpen[1];
def MaterialsOpen    = if barNumber == 1 then MaterialsPrice   else MaterialsOpen[1];
def EnergyOpen       = if barNumber == 1 then EnergyPrice      else EnergyOpen[1];
def StaplesOpen      = if barNumber == 1 then StaplesPrice     else StaplesOpen[1];
def HealthCareOpen   = if barNumber == 1 then HealthCarePrice  else HealthCareOpen[1];
def UtilitiesOpen    = if barNumber == 1 then UtilitiesPrice   else UtilitiesOpen[1];
def FinancialsOpen   = if barNumber == 1 then FinancialsPrice  else FinancialsOpen[1];

def Multiplier       = BaseOpen;

plot dot =  if barNumber() == pivot then BaseOpen else Double.NaN;
dot.SetDefaultColor(Color.WHITE);
dot.SetStyle(Curve.POINTS);
dot.SetLineWeight(5);

plot basePriceToPlot        = if ShowOverlay then BasePrice        - (BasePrice       - BaseOpen) + Multiplier * (BasePrice        - BaseOpen)        / BaseOpen        else Double.NaN;
basePriceToPlot.SetDefaultColor(Color.WHITE);
AddLabel(ShowOverlay, " " + GetUnderlyingSymbol() + " ", Color.WHITE);
basePriceToPlot.SetLineWeight(2);

plot SnP500PriceToPlot      = if ShowOverlay then SnP500Price      - (SnP500Open      - BaseOpen) + Multiplier * (SnP500Price      - SnP500Open)     / SnP500Open      else Double.NaN;
SnP500PriceToPlot.SetDefaultColor(Color.RED);
AddLabel(ShowOverlay, " SnP500 ", Color.RED);

plot CyclicalsPriceToPlot   = if ShowOverlay then CyclicalsPrice   - (CyclicalsOpen   - BaseOpen) + Multiplier * (CyclicalsPrice   - CyclicalsOpen)  / CyclicalsOpen   else Double.NaN;
CyclicalsPriceToPlot.SetDefaultColor(Color.VIOLET);
AddLabel(ShowOverlay, " Cyclicals ", Color.VIOLET);

plot TechologyPriceToPlot   = if ShowOverlay then TechnologyPrice  - (TechnologyOpen  - BaseOpen) + Multiplier * (TechnologyPrice  - TechnologyOpen) / TechnologyOpen  else Double.NaN;
TechologyPriceToPlot.SetDefaultColor(Color.GREEN);
AddLabel(ShowOverlay, " Techology ", Color.GREEN);

plot IndustrialsPriceToPlot = if ShowOverlay then IndustrialsPrice - (IndustrialsOpen - BaseOpen) + Multiplier * (IndustrialsPrice - IndustrialsOpen) / IndustrialsOpen else Double.NaN;
IndustrialsPriceToPlot.SetDefaultColor(Color.MAGENTA);
AddLabel(ShowOverlay, " Industrials ", Color.MAGENTA);

plot MaterialsPriceToPlot   = if ShowOverlay then MaterialsPrice   - (MaterialsOpen   - BaseOpen) + Multiplier * (MaterialsPrice   - MaterialsOpen)  / MaterialsOpen   else Double.NaN;
MaterialsPriceToPlot.SetDefaultColor(Color.CYAN);
AddLabel(ShowOverlay, " Materials ", Color.CYAN);

plot EnergyPriceToPlot      = if ShowOverlay then EnergyPrice      - (EnergyOpen      - BaseOpen) + Multiplier * (EnergyPrice      - EnergyOpen)     / EnergyOpen      else Double.NaN;
EnergyPriceToPlot.SetDefaultColor(Color.YELLOW);
AddLabel(ShowOverlay, " Energy ", Color.YELLOW);

plot StaplesPriceToPlot     = if ShowOverlay then StaplesPrice     - (StaplesOpen     - BaseOpen) + Multiplier * (StaplesPrice     - StaplesOpen)    / StaplesOpen     else Double.NaN;
StaplesPriceToPlot.SetDefaultColor(Color.DARK_GREEN);
AddLabel(ShowOverlay, " Staples ", Color.DARK_GREEN);

plot HealthCarePriceToPlot  = if ShowOverlay then HealthCarePrice  - (HealthCareOpen  - BaseOpen) + Multiplier * (HealthCarePrice  - HealthCareOpen) / HealthCareOpen  else Double.NaN;
HealthCarePriceToPlot.SetDefaultColor(Color.PLUM);
AddLabel(ShowOverlay, " HealthCare ", Color.PLUM);

plot UtilitiesPriceToPlot   = if ShowOverlay then UtilitiesPrice   - (UtilitiesOpen   - BaseOpen) + Multiplier * (UtilitiesPrice   - UtilitiesOpen)  / UtilitiesOpen   else Double.NaN;
UtilitiesPriceToPlot.SetDefaultColor(Color.ORANGE);
AddLabel(ShowOverlay, " Utilities ", Color.ORANGE);

plot FinancialsPriceToPlot  = if ShowOverlay then FinancialsPrice  - (FinancialsOpen  - BaseOpen) + Multiplier * (FinancialsPrice  - FinancialsOpen) / FinancialsOpen  else Double.NaN;
FinancialsPriceToPlot.SetDefaultColor(Color.PINK);
AddLabel(ShowOverlay, " Financials ", Color.PINK);
 
Is it OK? See SPY performance (343.74) is different from SnP500 (321.14) in the chart (right Panel) ??
PpAPwVf.png
 

tomsk

Well-known member
VIP
@markos I took a look at this study, the code looks pretty clean. What I really like about this is that there are bubbles that depict correlated sectors to the SPX which in turn suggests sectors to concentrate in/avoid. However the display of the plots seems to be rather "haphazard" with the use of different painting styles namely LINE_VS_SQUARE, LONG DASH, SHORT DASH, LINE_vs_POINTS and LINE.

Based on my observations, I have made some minor modifications on ed_nn's original code that was posted to TSL in April 2019. My mods standardized the plot display for stoch1 through stoch9 to use LINE so that it no longer has that "haphazard" look. In addition, I appended in the bubble the sector percent correlation so that at one glance one can determine the top 2-3 sectors.

The only downside is that some of the sectors are so close together that the bubbles overlap - I see no easy resolution to that, so perhaps the thing to do is to concentrate on the top/bottom 3 sectors.

Here then is version 1,1 of the code which originally was named Beta Rotation, I have retained that name in the same spirit.

Code:
# Beta Rotation V1.1
# ed_nn, with modifications by tomsk
# 1.4.2020

# V1.0 - 04.10.2019 - ed_nn - Initial release of Beta Rotation from TSL
# V1.1 - 01.04.2020 - tomsk - Standardized plots for stoch1-stoch9 and added sector percent correlation

# ed_nn: Maybe it has some interest. It attempts to code a posted idea
# (using Beta + Stochastics to observe rotation) from last week

# Mobius: To find rotation quickly, use primary ETF's in a watchlist with 2 columns
# first column is Correlation to SPX, second column is a stochastic of Beta
# if Beta is 1 or close to 1 that ETF is moving at the fastest momentum in that range
# and if correlation is with SPX .85 or better it's moving with SPX correlation below 0
# and it's moving the opposite of SPX.

declare lower;

input BetaLength = 21;
input StochLength =34;
input showBeta = No;
input showOverlay = Yes;

input Cyclicals      = "XLY";
input Technology     = "XLK";
input Industrials    = "XLI";
input Materials      = "XLB";
input Energy         = "XLE";
input Staples        = "XLP";
input HealthCare     = "XLV";
input Utilities      = "XLU";
input Financials     = "XLF";

defineglobalColor(“PlumMedium“, createColor(221, 160, 221));
defineglobalColor(“Orchid“, createColor(218, 130, 214));
defineglobalColor(“MediumOrchid“, createColor(186, 85, 211));
defineglobalColor(“MediumPurple“, createColor(147, 112, 219));
defineglobalColor(“DarkOrchid“, createColor(153, 50, 204));

addLabel(1,"Rotation Beta/Stochastic (" + betaLength + "," +stochLength + ") ", color.Light_Gray);

script calcBeta {
  input secondSymbol = "XLF";
  input refSymbol = "SPX";
  input betaLength = 21;
  input returnLength = 1;

  def refPrice = close(refSymbol);
  def primary = if refPrice[returnLength] == 0
                then 0
                else (refPrice - refPrice[returnLength]) /
                      refPrice[returnLength] * 100;
  def secondPrice = close(secondSymbol);
  def secondary = if secondPrice[returnLength] == 0
                  then 0
                  else (secondPrice - secondPrice[returnLength]) /
                        secondPrice[returnLength] * 100;
  plot Beta = covariance(secondary, primary, betaLength) /
                         Sqr(stdev(primary, betaLength));
}

script EhlersESSfilter {
    input price = close;
    input length = 8;
    def ESS_coeff_0 = Exp(-Double.Pi * Sqrt(2) / length);
    def ESS_coeff_2 = 2 * ESS_coeff_0 * Cos(Sqrt(2) * Double.Pi / length);
    def ESS_coeff_3 = - Sqr(ESS_coeff_0);
    def ESS_coeff_1 = 1 - ESS_coeff_2 - ESS_coeff_3;
    def ESS_filter = if IsNaN(price + price[1]) then
                      ESS_filter[1]
                 else ESS_coeff_1 * (price + price[1]) / 2 +
                      ESS_coeff_2 * ESS_filter[1] +
                      ESS_coeff_3 * ESS_filter[2];
    plot Smooth_Filter =
         if barnumber() <  length then
              price
         else if !IsNaN(price) then
              ESS_filter
         else Double.NaN;
}

script calcStoch {
  input data = close;
  input StochLength = 21;
  def stochasticValue = ((data - lowest(data, StochLength)) /
                         (highest(data, StochLength) - lowest(data, StochLength)));
  plot stoch = stochasticValue;
}

plot beta1 = if showBeta then calcBeta(Cyclicals) else Double.NaN;
plot beta2 = if showBeta then calcBeta(Technology) else Double.NaN;

plot stoch1 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Cyclicals,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch1.SetDefaultColor(Color.VIOLET);
stoch1.SetLineWeight(2);
stoch1.SetPaintingStrategy(PaintingStrategy.LINE);
stoch1.HideBubble();
AddLabel(ShowOverlay, " Cyclicals ", Color.VIOLET);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch1 < 0.15 then 0 else if stoch1 > 0.85 then 1 else stoch1,
"Cyclicals (" + AsPercent(stoch1) + ")", Color.VIOLET, stoch1 > 0.5);

plot stoch2 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Technology,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch2.SetDefaultColor(CreateColor(90, 160, 120));
stoch2.SetLineWeight(5);
stoch2.SetPaintingStrategy(PaintingStrategy.LINE);
stoch2.HideBubble();
AddLabel(ShowOverlay, " Techology ", CreateColor(90, 160, 120));
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch2 < 0.15 then 0 else if stoch2 > 0.85 then 1 else stoch2, "Technology (" + AsPercent(stoch2) + ")", CreateColor(90, 160, 120), stoch2 > 0.5);

plot stoch3 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Industrials,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch3.SetDefaultColor(Color.MAGENTA);
stoch3.SetLineWeight(5);
stoch3.SetPaintingStrategy(PaintingStrategy.LINE);
stoch3.HideBubble();
AddLabel(ShowOverlay, " Industrials ", Color.MAGENTA);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch3 < 0.15 then 0 else if stoch3 > 0.85 then 1 else stoch3, "Industrials (" + AsPercent(stoch3) + ")", Color.MAGENTA, stoch3 > 0.5);

plot stoch4 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Materials,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch4.SetDefaultColor(Color.CYAN);
stoch4.SetLineWeight(2);
stoch4.SetPaintingStrategy(PaintingStrategy.LINE);
stoch4.HideBubble();
AddLabel(ShowOverlay, " Materials ", Color.CYAN);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch4 < 0.15 then 0 else if stoch4 > 0.85 then 1 else stoch4, "Materials (" + AsPercent(stoch4) + ")", Color.CYAN, stoch4 > 0.5);

plot stoch5 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Energy,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch5.SetDefaultColor(Color.YELLOW);
stoch5.SetLineWeight(1);
stoch5.SetPaintingStrategy(PaintingStrategy.LINE);
stoch5.HideBubble();
AddLabel(ShowOverlay, " Energy ", Color.YELLOW);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch5 < 0.15 then 0 else if stoch5 > 0.85 then 1 else stoch5,
"Energy (" + AsPercent(stoch5) + ")", Color.YELLOW, stoch5 > 0.5);

plot stoch6 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Staples,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch6.SetDefaultColor(CreateColor(80, 180, 70));
stoch6.SetLineWeight(2);
stoch6.SetPaintingStrategy(PaintingStrategy.LINE);
stoch6.HideBubble();
AddLabel(ShowOverlay, " Staples ", CreateColor(80, 180, 70));
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch6 < 0.15 then 0 else if stoch6 > 0.85 then 1 else stoch6,
"Staples (" + AsPercent(stoch6) + ")", CreateColor(80, 180, 70), stoch6 > close);

plot stoch7 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = HealthCare,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch7.SetDefaultColor(CreateColor(180, 80, 180));
stoch7.SetLineWeight(4);
stoch7.SetPaintingStrategy(PaintingStrategy.LINE);
stoch7.HideBubble();
AddLabel(ShowOverlay, " HealthCare ", CreateColor(180, 80, 180));
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch7 < 0.15 then 0 else if stoch7 > 0.85 then 1 else stoch7, "HealthCare (" + AsPercent(stoch7) + ")", CreateColor(180, 80, 180), stoch7 > 0.5);

plot stoch8 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Utilities,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch8.SetDefaultColor(Color.ORANGE);
stoch8.SetLineWeight(2);
stoch8.SetPaintingStrategy(PaintingStrategy.LINE);
stoch8.HideBubble();
AddLabel(ShowOverlay, " Utilities ", Color.ORANGE);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close[0]), if stoch8 < 0.15 then 0 else if stoch8 > 0.85 then 1 else stoch8, "Utilities (" + AsPercent(stoch8) + ")", Color.ORANGE, stoch8 > 0.5);

plot stoch9 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Financials,
                               betaLength = BetaLength)),
                                     stochLength = StochLength);
stoch9.SetDefaultColor(Color.PINK);
stoch9.SetLineWeight(2);
stoch9.SetPaintingStrategy(PaintingStrategy.LINE);
stoch9.HideBubble();
AddLabel(ShowOverlay, " Financials ", Color.PINK);
AddChartBubble(ShowOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch9 < 0.15 then 0 else if stoch9 > 0.85 then 1 else stoch9, "Financials (" + AsPercent(stoch9) + ")", Color.PINK, stoch9 > 0.5);

def barNumber = BarNumber();
def endBar = if !IsNaN(close) and IsNaN(close[-1]) then barNumber else endBar[1];
def lastBar = HighestAll(endBar);

input flowLabelStep = 40;

DefineGlobalColor("YellowGreen", CreateColor(90, 140, 5));
AddChartBubble(barNumber == (lastBar - flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", globalColor("YellowGreen"), 1);
AddChartBubble(barNumber == (lastBar - 2*flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", globalColor("YellowGreen"), 1);
AddChartBubble(barNumber == (lastBar - 3*flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", globalColor("YellowGreen"), 1);

DefineGlobalColor("Cinamon", CreateColor(200, 10, 40));
AddChartBubble(barNumber == (lastBar - flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", globalColor("Cinamon"), 0);
AddChartBubble(barNumber == (lastBar - 2*flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", globalColor("Cinamon"), 0);
AddChartBubble(barNumber == (lastBar - 3*flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", globalColor("Cinamon"), 0);

plot zero = if barNumber > (lastBar + 7) then double.nan else 0;
zero.SetDefaultColor(createColor(90, 20, 20));
zero.SetStyle(Curve.Long_Dash);
zero.SetLineWeight(5);
zero.HideBubble();

plot one = if barNumber > (lastBar + 7) then double.nan else 1;
one.SetDefaultColor(createColor(20, 70, 20));
one.SetStyle(Curve.Long_Dash);
one.SetLineWeight(5);
one.HideBubble();
# End Beta Rotation V1.1
 
Last edited:

RmS59

Member
Forgive me if I mess up this post - it is my first.

I agree with your concern about difficulty seeing all the bubbles. I added the value of the stoch to the labels.

Here is my revised code:

Code:
# From https://usethinkscript.com/threads/s-p-500-sector-performance.1152/

# Beta Rotation V1.1
# ed_nn, with modifications by tomsk
# 1.4.2020

# V1.0 - 04.10.2019 - ed_nn - Initial release of Beta Rotation from TSL
# V1.1 - 01.04.2020 - tomsk - Standardized plots for stoch1-stoch9 and added sector percent correlation
# V1.2 -01.11.2020 - RmS59 - added Stoch values to the labels

# ed_nn: Maybe it has some interest. It attempts to code a posted idea
# (using Beta + Stochastics to observe rotation) from last week

# Mobius: To find rotation quickly, use primary ETF's in a watchlist with 2 columns
# first column is Correlation to SPX, second column is a stochastic of Beta
# if Beta is 1 or close to 1 that ETF is moving at the fastest momentum in that range
# and if correlation is with SPX .85 or better it's moving with SPX correlation below 0
# and it's moving the opposite of SPX.

# RmS59: To facilitate legibility, the value of the various sector stochs are displayed in the Labels


declare lower;

input BetaLength = 21;
input StochLength = 34;
input showBeta = No;
input showOverlay = Yes;

input Discretionary  = "XLY";
input Technology     = "XLK";
input Industrials    = "XLI";
input Materials      = "XLB";
input Energy         = "XLE";
input Staples        = "XLP";
input HealthCare     = "XLV";
input Utilities      = "XLU";
input Financials     = "XLF";

DefineGlobalColor(“PlumMedium“, CreateColor(221, 160, 221));
DefineGlobalColor(“Orchid“, CreateColor(218, 130, 214));
DefineGlobalColor(“MediumOrchid“, CreateColor(186, 85, 211));
DefineGlobalColor(“MediumPurple“, CreateColor(147, 112, 219));
DefineGlobalColor(“DarkOrchid“, CreateColor(153, 50, 204));

AddLabel(1, "Rotation Beta/Stochastic (" + BetaLength + "," + StochLength + ") ", Color.LIGHT_GRAY);

script calcBeta {
    input secondSymbol = "XLF";
    input refSymbol = "SPX";
    input betaLength = 21;
    input returnLength = 1;

    def refPrice = close(refSymbol);
    def primary = if refPrice[returnLength] == 0
                then 0
                else (refPrice - refPrice[returnLength]) /
                      refPrice[returnLength] * 100;
    def secondPrice = close(secondSymbol);
    def secondary = if secondPrice[returnLength] == 0
                  then 0
                  else (secondPrice - secondPrice[returnLength]) /
                        secondPrice[returnLength] * 100;
    plot Beta = Covariance(secondary, primary, betaLength) /
                         Sqr(StDev(primary, betaLength));
}

script EhlersESSfilter {
    input price = close;
    input length = 8;
    def ESS_coeff_0 = Exp(-Double.Pi * Sqrt(2) / length);
    def ESS_coeff_2 = 2 * ESS_coeff_0 * Cos(Sqrt(2) * Double.Pi / length);
    def ESS_coeff_3 = - Sqr(ESS_coeff_0);
    def ESS_coeff_1 = 1 - ESS_coeff_2 - ESS_coeff_3;
    def ESS_filter = if IsNaN(price + price[1]) then
                      ESS_filter[1]
                 else ESS_coeff_1 * (price + price[1]) / 2 +
                      ESS_coeff_2 * ESS_filter[1] +
                      ESS_coeff_3 * ESS_filter[2];
    plot Smooth_Filter =
         if BarNumber() <  length then
              price
         else if !IsNaN(price) then
              ESS_filter
         else Double.NaN;
}

script calcStoch {
    input data = close;
    input StochLength = 21;
    def stochasticValue = ((data - Lowest(data, StochLength)) /
                         (Highest(data, StochLength) - Lowest(data, StochLength)));
    plot stoch = stochasticValue;
}

plot beta1 = if showBeta then calcBeta(Discretionary) else Double.NaN;
plot beta2 = if showBeta then calcBeta(Technology) else Double.NaN;

plot stoch1 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Discretionary,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch1.SetDefaultColor(Color.VIOLET);
stoch1.SetLineWeight(2);
stoch1.SetPaintingStrategy(PaintingStrategy.LINE);
stoch1.HideBubble();
AddLabel(showOverlay, " Discretionary " + 100 * Round(stoch1, 2), Color.VIOLET);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch1 < 0.15 then 0 else if stoch1 > 0.85 then 1 else stoch1,
"Discretionary (" + AsPercent(stoch1) + ")", Color.VIOLET, stoch1 > 0.5);

plot stoch2 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Technology,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch2.SetDefaultColor(CreateColor(90, 160, 120));
stoch2.SetLineWeight(5);
stoch2.SetPaintingStrategy(PaintingStrategy.LINE);
stoch2.HideBubble();
AddLabel(showOverlay, " Techology " + 100 * Round(stoch2, 2), CreateColor(90, 160, 120));
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch2 < 0.15 then 0 else if stoch2 > 0.85 then 1 else stoch2, "Technology (" + AsPercent(stoch2) + ")", CreateColor(90, 160, 120), stoch2 > 0.5);

plot stoch3 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Industrials,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch3.SetDefaultColor(Color.MAGENTA);
stoch3.SetLineWeight(5);
stoch3.SetPaintingStrategy(PaintingStrategy.LINE);
stoch3.HideBubble();
AddLabel(showOverlay, " Industrials " + 100 * Round(stoch3, 2), Color.MAGENTA);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch3 < 0.15 then 0 else if stoch3 > 0.85 then 1 else stoch3, "Industrials (" + AsPercent(stoch3) + ")", Color.MAGENTA, stoch3 > 0.5);

plot stoch4 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Materials,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch4.SetDefaultColor(Color.CYAN);
stoch4.SetLineWeight(2);
stoch4.SetPaintingStrategy(PaintingStrategy.LINE);
stoch4.HideBubble();
AddLabel(showOverlay, " Materials " + 100 * Round(stoch4, 2), Color.CYAN);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch4 < 0.15 then 0 else if stoch4 > 0.85 then 1 else stoch4, "Materials (" + AsPercent(stoch4) + ")", Color.CYAN, stoch4 > 0.5);

plot stoch5 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Energy,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch5.SetDefaultColor(Color.YELLOW);
stoch5.SetLineWeight(1);
stoch5.SetPaintingStrategy(PaintingStrategy.LINE);
stoch5.HideBubble();
AddLabel(showOverlay, " Energy " + 100 * Round(stoch5, 2), Color.YELLOW);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch5 < 0.15 then 0 else if stoch5 > 0.85 then 1 else stoch5,
"Energy (" + AsPercent(stoch5) + ")", Color.YELLOW, stoch5 > 0.5);

plot stoch6 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Staples,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch6.SetDefaultColor(CreateColor(80, 180, 70));
stoch6.SetLineWeight(2);
stoch6.SetPaintingStrategy(PaintingStrategy.LINE);
stoch6.HideBubble();
AddLabel(showOverlay, " Staples " + 100 * Round(stoch6, 2), CreateColor(80, 180, 70));
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch6 < 0.15 then 0 else if stoch6 > 0.85 then 1 else stoch6,
"Staples (" + AsPercent(stoch6) + ")", CreateColor(80, 180, 70), stoch6 > close);

plot stoch7 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = HealthCare,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch7.SetDefaultColor(CreateColor(180, 80, 180));
stoch7.SetLineWeight(4);
stoch7.SetPaintingStrategy(PaintingStrategy.LINE);
stoch7.HideBubble();
AddLabel(showOverlay, " HealthCare " + 100 * Round(stoch7, 2), CreateColor(180, 80, 180));
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch7 < 0.15 then 0 else if stoch7 > 0.85 then 1 else stoch7, "HealthCare (" + AsPercent(stoch7) + ")", CreateColor(180, 80, 180), stoch7 > 0.5);

plot stoch8 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Utilities,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch8.SetDefaultColor(Color.ORANGE);
stoch8.SetLineWeight(2);
stoch8.SetPaintingStrategy(PaintingStrategy.LINE);
stoch8.HideBubble();
AddLabel(showOverlay, " Utilities " + 100 * Round(stoch8, 2), Color.ORANGE);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close[0]), if stoch8 < 0.15 then 0 else if stoch8 > 0.85 then 1 else stoch8, "Utilities (" + AsPercent(stoch8) + ")", Color.ORANGE, stoch8 > 0.5);

plot stoch9 = calcStoch(
                        data = EhlersESSfilter(
                               calcBeta(secondSymbol = Financials,
                               betaLength = betaLength)),
                                     stochLength = StochLength);
stoch9.SetDefaultColor(Color.PINK);
stoch9.SetLineWeight(2);
stoch9.SetPaintingStrategy(PaintingStrategy.LINE);
stoch9.HideBubble();
AddLabel(showOverlay, " Financials " + 100 * Round(stoch9, 2), Color.PINK);
AddChartBubble(showOverlay and IsNaN(close[-1]) and !IsNaN(close), if stoch9 < 0.15 then 0 else if stoch9 > 0.85 then 1 else stoch9, "Financials (" + AsPercent(stoch9) + ")", Color.PINK, stoch9 > 0.5);

def barNumber = BarNumber();
def endBar = if !IsNaN(close) and IsNaN(close[-1]) then barNumber else endBar[1];
def lastBar = HighestAll(endBar);

input flowLabelStep = 40;

DefineGlobalColor("YellowGreen", CreateColor(90, 140, 5));
AddChartBubble(barNumber == (lastBar - flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", GlobalColor("YellowGreen"), 1);
AddChartBubble(barNumber == (lastBar - 2 * flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", GlobalColor("YellowGreen"), 1);
AddChartBubble(barNumber == (lastBar - 3 * flowLabelStep), 1.01, "M O N E Y   F L O W S   I N", GlobalColor("YellowGreen"), 1);

DefineGlobalColor("Cinamon", CreateColor(200, 10, 40));
AddChartBubble(barNumber == (lastBar - flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", GlobalColor("Cinamon"), 0);
AddChartBubble(barNumber == (lastBar - 2 * flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", GlobalColor("Cinamon"), 0);
AddChartBubble(barNumber == (lastBar - 3 * flowLabelStep), -0.01, "M O N E Y   F L O W S   O U T", GlobalColor("Cinamon"), 0);

plot zero = if barNumber > (lastBar + 7) then Double.NaN else 0;
zero.SetDefaultColor(CreateColor(90, 20, 20));
zero.SetStyle(Curve.LONG_DASH);
zero.SetLineWeight(5);
zero.HideBubble();

plot one = if barNumber > (lastBar + 7) then Double.NaN else 1;
one.SetDefaultColor(CreateColor(20, 70, 20));
one.SetStyle(Curve.LONG_DASH);
one.SetLineWeight(5);
one.HideBubble();
# End Beta Rotation V1.1
 
Last edited by a moderator:

tomsk

Well-known member
VIP
When I was reviewing this for @markos I did think about adding the percentages to the labels but felt that it might be better to focus on the top/bottom 3 sectors rather than the entire range. Another approach might be to ditch all the rather haphazard looking plots and just represent the percentages via labels. However in so doing there is no way to rank/sequence these labels dynamically. Hence I left it as version 1.1.
 

markos

Well-known member
VIP
Hi @Art use what is already there and add the REIT index just below the last entry. Do that for each section of the script. FIRST, save the script in Notepad++, it's a free download. Keep all the scripts you find in there and soon you'll have a pile of each type of code to build from. That way your original script that worked will always be there.
 
Last edited:
  • Like
Reactions: Art

markos

Well-known member
VIP
@Art Notepad++ is one way many pro coders keep their data in properly "formatted" text files. Good luck.
 
  • Like
Reactions: Art

army11b1980

New member
VIP
@RmS59 @tomsk I've copied all three codes and wanted to look at each of them. The very first one, submitted by Tom, isn't working for me. I'm still new to this.. what am I doing wrong?
XPgmbJo.jpg
 
Last edited by a moderator:

drakoniano

New member
Hi how are you guys? I hope fine and healthy. Look I'm looking an indicator that compares the sectors and some stocks like the FAANG. I mean I want the know in percentage how much the sector / stock change from the RTH open.

Markos already sent me something but really is not what I'm looking for.
thanks guys!
 

c0der

Member
looking for something like this, that can be toggled by yesterday's movement or last week's movement. Will be even better if it can show relative strength:

YFgVA72.png
 

Ravenjams

New member
When I was reviewing this for @markos I did think about adding the percentages to the labels but felt that it might be better to focus on the top/bottom 3 sectors rather than the entire range. Another approach might be to ditch all the rather haphazard looking plots and just represent the percentages via labels. However in so doing there is no way to rank/sequence these labels dynamically. Hence I left it as version 1.1.

@tomsk

Hello, I am new to this party and have limited experience with Thinkscript at the moment.

I like this script and I would like to modify it.

How can I get the results in a watchlist or scanner?

I do not want it in a chart there is just to much information, I am only interested in the top 2-3 sectors by percent. Right now just longs. I want to scan only stocks that are in these sectors.

20 years ago I wrote a fairly large program using DTN satellite from scratch. It did a live scan per second. The program would find the highest two or three sectors (longs or shorts) and would give me the top 3-8 symbols within these sectors that where viable. NEVER more.

It would popup new companies all day long within these sectors. If the sectors changed, so did the list of stocks it looked at.

It did this for Longs and shorts. It worked very well, beyond imagination actually, until I had to stop for a Brain Injury I sustained. I was no longer capable of trading until now.

I am back at it again and rewriting this on web protocol from scratch, because I really don't want a none Mobil Satellite dish in my yard and technology has changes by miles. In the mean time I am using Thinkscript.
 

Headhunter20

New member
S&P 500 Sector Performance For ThinkOrSwim
Ruby:
# S&P 500 Sector Performance (Percentage)
# Paris
# 4.12.2018
# After reviewing chubbyboy's S&P sector study, I thought it might
# be a good idea to display labels of relative S&P sector performance
# in percentages. At one glance this will enable us to determine
# which sectors are happening and which are not. Decided to use a
# script() to retrieve the data. Also, I changed the formula slightly.
# The percentage displayed is the current price as a percentage over
# yesterday's closing rather than the open today as was used in chubbyboy's
# study.
#====== Further Modified by Killing Hours ======#
# 5/4/2020 #
# Added Color Mapping #
# to distinguish more suddle movements #
#===============================================#
Modified slightly by Headhunter20.


######################################################################################
script Sector {
input symb = "SPX";
def c = close(symbol = symb, period = AggregationPeriod.day);
def PctChg = (c / c[1]) - 1;
plot pct = PctChg;
}

#Define the color map. Change as you see fit
DefineGlobalColor("VeryGood", CreateColor(4, 216, 22));
DefineGlobalColor("Good", CreateColor(46, 216, 4));
DefineGlobalColor("ModGood", CreateColor(121, 216, 4));
DefineGlobalColor("SlightlyGood", CreateColor(167, 216, 4));
DefineGlobalColor("SluggishGood", CreateColor(210,252,126));
DefineGlobalColor("Neutral", CreateColor(252, 231, 126));
DefineGlobalColor("SluggishBad", CreateColor(252,168,126));
DefineGlobalColor("SlightlyBad", CreateColor(216, 163, 4));
DefineGlobalColor("ModBad", CreateColor(216, 117, 4));
DefineGlobalColor("Bad", CreateColor(216, 43, 4));
DefineGlobalColor("VeryBad", CreateColor(216, 4, 4));

# SPX Overall
def SPX = Sector("SPX");
def spxPer = round(SPX,4) * 100;
AddLabel(
1,
"S&P 500: " +spxPer+"%",
if spxPer > 1.50 then GlobalColor("VeryGood") else
if spxPer > 1 && spxPer <= 1.50 then GlobalColor("Good") else
if spxPer > .5 && spxPer <= 1 then GlobalColor("ModGood") else
if spxPer > .25 && spxPer <= .5 then GlobalColor("SlightlyGood") else
if spxPer > 0 && spxPer <= .25 then GlobalColor("SluggishGood") else
if spxPer == 0 then GlobalColor("Neutral") else
if spxPer < 0 && spxPer >= -.25 then GlobalColor("SluggishBad") else
if spxPer < -.25 && spxPer >= -.5 then GlobalColor("SlightlyBad") else
if spxPer < -.5 && spxPer >= -1 then GlobalColor("ModBad") else
if spxPer < -1 && spxPer >= -1.50 then GlobalColor("Bad") else
if spxPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Energy Sector
def Energy = Sector("$SP500#10");
def engPer = round(Energy,4) * 100;
AddLabel(
1,
"Energy: "+engPer+"% XLE #10",
if engPer > 1.50 then GlobalColor("VeryGood") else
if engPer > 1 && engPer <= 1.50 then GlobalColor("Good") else
if engPer > .5 && engPer <= 1 then GlobalColor("ModGood") else
if engPer > .25 && engPer <= .5 then GlobalColor("SlightlyGood") else
if engPer > 0 && engPer <= .25 then GlobalColor("SluggishGood") else
if engPer == 0 then GlobalColor("Neutral") else
if engPer < 0 && engPer >= -.25 then GlobalColor("SluggishBad") else
if engPer < -.25 && engPer >= -.5 then GlobalColor("SlightlyBad") else
if engPer < -.5 && engPer >= -1 then GlobalColor("ModBad") else
if engPer < -1 && engPer >= -1.50 then GlobalColor("Bad") else
if engPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Consumer Discretionary Spending Sector
def ConDisr = Sector("$SP500#25");
def conDPer = round(ConDisr,4);
AddLabel(
1,
"Con. Discretionary: "+conDPer+"% XLY #25",
if conDPer > 1.50 then GlobalColor("VeryGood") else
if conDPer > 1 && conDPer <= 1.50 then GlobalColor("Good") else
if conDPer > .5 && conDPer <= 1 then GlobalColor("ModGood") else
if conDPer > .25 && conDPer <= .5 then GlobalColor("SlightlyGood") else
if conDPer > 0 && conDPer <= .25 then GlobalColor("SluggishGood") else
if conDPer == 0 then GlobalColor("Neutral") else
if conDPer < 0 && conDPer >= -.25 then GlobalColor("SluggishBad") else
if conDPer < -.25 && conDPer >= -.5 then GlobalColor("SlightlyBad") else
if conDPer < -.5 && conDPer >= -1 then GlobalColor("ModBad") else
if conDPer < -1 && conDPer >= -1.50 then GlobalColor("Bad") else
if conDPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Financial Sector
def Finance = Sector("$SP500#40");
def finPer = round(Finance,4) * 100;
AddLabel(
1,
"Financials: "+finPer+"% XLF #40",
if finPer > 1.50 then GlobalColor("VeryGood") else
if finPer > 1 && finPer <= 1.50 then GlobalColor("Good") else
if finPer > .5 && finPer <= 1 then GlobalColor("ModGood") else
if finPer > .25 && finPer <= .5 then GlobalColor("SlightlyGood") else
if finPer > 0 && finPer <= .25 then GlobalColor("SluggishGood") else
if finPer == 0 then GlobalColor("Neutral") else
if finPer < 0 && finPer >= -.25 then GlobalColor("SluggishBad") else
if finPer < -.25 && finPer >= -.5 then GlobalColor("SlightlyBad") else
if finPer < -.5 && finPer >= -1 then GlobalColor("ModBad") else
if finPer < -1 && finPer >= -1.50 then GlobalColor("Bad") else
if finPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Utilities Sector
def Utilities = Sector("$SP500#55");
def utiPer = round(Utilities,4) * 100;
AddLabel(
1,
"Utilities: "+utiPer+"% XLU #55",
if utiPer > 1.50 then GlobalColor("VeryGood") else
if utiPer > 1 && utiPer <= 1.50 then GlobalColor("Good") else
if utiPer > .5 && utiPer <= 1 then GlobalColor("ModGood") else
if utiPer > .25 && utiPer <= .5 then GlobalColor("SlightlyGood") else
if utiPer > 0 && utiPer <= .25 then GlobalColor("SluggishGood") else
if utiPer == 0 then GlobalColor("Neutral") else
if utiPer < 0 && utiPer >= -.25 then GlobalColor("SluggishBad") else
if utiPer < -.25 && utiPer >= -.5 then GlobalColor("SlightlyBad") else
if utiPer < -.5 && utiPer >= -1 then GlobalColor("ModBad") else
if utiPer < -1 && utiPer >= -1.50 then GlobalColor("Bad") else
if utiPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Materials Sector
def Materials = Sector("$SP500#15");
def matPer = round(Materials,4) * 100;
AddLabel(
1,
"Materials: "+matPer+"% XLB #15",
if matPer > 1.50 then GlobalColor("VeryGood") else
if matPer > 1 && matPer <= 1.50 then GlobalColor("Good") else
if matPer > .5 && matPer <= 1 then GlobalColor("ModGood") else
if matPer > .25 && matPer <= .5 then GlobalColor("SlightlyGood") else
if matPer > 0 && matPer <= .25 then GlobalColor("SluggishGood") else
if matPer == 0 then GlobalColor("Neutral") else
if matPer < 0 && matPer >= -.25 then GlobalColor("SluggishBad") else
if matPer < -.25 && matPer >= -.5 then GlobalColor("SlightlyBad") else
if matPer < -.5 && matPer >= -1 then GlobalColor("ModBad") else
if matPer < -1 && matPer >= -1.50 then GlobalColor("Bad") else
if matPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Consumer Staples Sector
def ConStaple = Sector("$SP500#30");
def conSPer = round(ConStaple,4) * 100;
AddLabel(
1,
"Consumer Staples: "+conSPer+"% XLP #30",
if conSPer > 1.50 then GlobalColor("VeryGood") else
if conSPer > 1 && conSPer <= 1.50 then GlobalColor("Good") else
if conSPer > .5 && conSPer <= 1 then GlobalColor("ModGood") else
if conSPer > .25 && conSPer <= .5 then GlobalColor("SlightlyGood") else
if conSPer > 0 && conSPer <= .25 then GlobalColor("SluggishGood") else
if conSPer == 0 then GlobalColor("Neutral") else
if conSPer < 0 && conSPer >= -.25 then GlobalColor("SluggishBad") else
if conSPer < -.25 && conSPer >= -.5 then GlobalColor("SlightlyBad") else
if conSPer < -.5 && conSPer >= -1 then GlobalColor("ModBad") else
if conSPer < -1 && conSPer >= -1.50 then GlobalColor("Bad") else
if conSPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Information Technology Sector
def InfoTech = Sector("$SP500#45");
def infPer = round(InfoTech,4) * 100;
AddLabel(
1,
"Info Tech: " +infPer+"% XLK #45",
if infPer > 1.50 then GlobalColor("VeryGood") else
if infPer > 1 && infPer <= 1.50 then GlobalColor("Good") else
if infPer > .5 && infPer <= 1 then GlobalColor("ModGood") else
if infPer > .25 && infPer <= .5 then GlobalColor("SlightlyGood") else
if infPer > 0 && infPer <= .25 then GlobalColor("SluggishGood") else
if infPer == 0 then GlobalColor("Neutral") else
if infPer < 0 && infPer >= -.25 then GlobalColor("SluggishBad") else
if infPer < -.25 && infPer >= -.5 then GlobalColor("SlightlyBad") else
if infPer < -.5 && infPer >= -1 then GlobalColor("ModBad") else
if infPer < -1 && infPer >= -1.50 then GlobalColor("Bad") else
if infPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Real Estate Sector
def RealEste = Sector("$SP500#60");
def reaPer = round(RealEste,4) * 100;
AddLabel(
1,
"Real Estate: " +reaPer+"% XLRE #60",
if reaPer > 1.50 then GlobalColor("VeryGood") else
if reaPer > 1 && reaPer <= 1.50 then GlobalColor("Good") else
if reaPer > .5 && reaPer <= 1 then GlobalColor("ModGood") else
if reaPer > .25 && reaPer <= .5 then GlobalColor("SlightlyGood") else
if reaPer > 0 && reaPer <= .25 then GlobalColor("SluggishGood") else
if reaPer == 0 then GlobalColor("Neutral") else
if reaPer < 0 && reaPer >= -.25 then GlobalColor("SluggishBad") else
if reaPer < -.25 && reaPer >= -.5 then GlobalColor("SlightlyBad") else
if reaPer < -.5 && reaPer >= -1 then GlobalColor("ModBad") else
if reaPer < -1 && reaPer >= -1.50 then GlobalColor("Bad") else
if reaPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);


# Industrial Sector
def Industrl = Sector("$SP500#20");
def indPer = round(Industrl,4) * 100;
AddLabel(
1,
"Industrials: " +indPer+"% XLI #20",
if indPer > 1.50 then GlobalColor("VeryGood") else
if indPer > 1 && indPer <= 1.50 then GlobalColor("Good") else
if indPer > .5 && indPer <= 1 then GlobalColor("ModGood") else
if indPer > .25 && indPer <= .5 then GlobalColor("SlightlyGood") else
if indPer > 0 && indPer <= .25 then GlobalColor("SluggishGood") else
if indPer == 0 then GlobalColor("Neutral") else
if indPer < 0 && indPer >= -.25 then GlobalColor("SluggishBad") else
if indPer < -.25 && indPer >= -.5 then GlobalColor("SlightlyBad") else
if indPer < -.5 && indPer >= -1 then GlobalColor("ModBad") else
if indPer < -1 && indPer >= -1.50 then GlobalColor("Bad") else
if indPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Healthcare Sector
def Health = Sector("$SP500#35");
def heaPer = round(Health,4) * 100;
AddLabel(
1,
"Health Care: " +heaPer+"% XLV #35",
if heaPer > 1.50 then GlobalColor("VeryGood") else
if heaPer > 1 && heaPer <= 1.50 then GlobalColor("Good") else
if heaPer > .5 && heaPer <= 1 then GlobalColor("ModGood") else
if heaPer > .25 && heaPer <= .5 then GlobalColor("SlightlyGood") else
if heaPer > 0 && heaPer <= .25 then GlobalColor("SluggishGood") else
if heaPer == 0 then GlobalColor("Neutral") else
if heaPer < 0 && heaPer >= -.25 then GlobalColor("SluggishBad") else
if heaPer < -.25 && heaPer >= -.5 then GlobalColor("SlightlyBad") else
if heaPer < -.5 && heaPer >= -1 then GlobalColor("ModBad") else
if heaPer < -1 && heaPer >= -1.50 then GlobalColor("Bad") else
if heaPer < -1.50 then GlobalColor("VeryBad") else
Color.black
);

# Telecommunication Sector
def Telecoms = Sector("$SP500#50");
def telPef = round(Telecoms,4) * 100;
AddLabel(
1,
"Telecoms: " +telPef+"% XLC #50",
if telPef > 1.50 then GlobalColor("VeryGood") else
if telPef > 1 && telPef <= 1.50 then GlobalColor("Good") else
if telPef > .5 && telPef <= 1 then GlobalColor("ModGood") else
if telPef > .25 && telPef <= .5 then GlobalColor("SlightlyGood") else
if telPef > 0 && telPef <= .25 then GlobalColor("SluggishGood") else
if telPef == 0 then GlobalColor("Neutral") else
if telPef < 0 && telPef >= -.25 then GlobalColor("SluggishBad") else
if telPef < -.25 && telPef >= -.5 then GlobalColor("SlightlyBad") else
if telPef < -.5 && telPef >= -1 then GlobalColor("ModBad") else
if telPef < -1 && telPef >= -1.50 then GlobalColor("Bad") else
if telPef < -1.50 then GlobalColor("VeryBad") else
Color.black
);
# End Study
 
Last edited by a moderator:

Headhunter20

New member
Thank you for finding the header to this. If I had known how to search for it or had it I certainly would have added it. It has been added to the script. I agree whole heartedly that credit should be given. I am certainly grateful for help that I have freely received.
 

8Nick8

Active member
2019 Donor
VIP
#1-20-22 ES Combined ETF_Rotate_Lower by ED_nn ThinkScriptLounge 4-2019 SectorRelativePerformance by RmS59and 7/15/18; added Sector Performance, Shortened Lables, Changed Colors to Preference, Changed all to ETFs (still selectable choices),
#Only interested in labels, left plots possible, note scale of y-axis if use plots

Note I am not a coder, please do check code, settings, and performance for yourself.


Code:
#ETF_SectorRotate_Perf_LabelsSAIMOD_1_20_2022
#Added 12-28-21 sector Rotate to my studies
#Added 1-20-22 sector perform to my studies


#use daily only**********************
#sector rotaton w/added sector performance

# ETF_Rotate_Lower by ED_nn ThinkScriptLounge 4-2019
# from 4/4/2019 chat room:
# 06:37 Mobius: johnny - To find rotation quickly - Use primary ETF's in a watchlist with 2 columns first column is Correlation to SPX second is a stochastic of Beta, if Beta is 1 or close to 1 that ETF is moving at the fastest momentum in that range and if correlation is with SPX .85 or better it's moving with SPX cor# daily start with 13,34 as starting point.
# 4-19-19 Markos took out Beta 1 & 2.
# 6-23-19 Markos put Beta back in
#1-20-22 ES Combined ETF_Rotate_Lower by ED_nn ThinkScriptLounge 4-2019 SectorRelativePerformance by RmS59and 7/15/18; added Sector Performance, Shortened Lables, Changed Colors to Preference, Changed all to ETFs (still selectable choices),
    #Only interested in labels, left plots possible, note scale of y-axis if use plots

#Rotation Colors from Money In to Money Out; changed colors based on preference ES
DefineGlobalColor("TRENDING", Color.DARK_GREEN); #Great
DefineGlobalColor("positive",  CreateColor(0, 175, 0)) ; #good green
DefineGlobalColor("negative",  Color.RED) ; #bad red
DefineGlobalColor("rising",  Color.YELLOW) ; #Light Slate Blue changed to yellow

input BetaLength = 21;
input StochLength = 34;
input showOverlay = yes;

input Cyclicals      = "XLY";
input Technology     = "XLK";
input Industrials    = "XLI";
input Materials      = "XLB";
input Energy         = "XLE";
input Staples        = "XLP";
input HealthCare     = "XLV";
input Utilities      = "XLU";
input Financials     = "XLF";
input Communications = "XTL";
input RealEstate     = "XLRE";
input Retail         = "XRT";
#-----------------------------

#AddLabel(1, "R-Beta/Stoch (" + BetaLength + "," + StochLength + ") ", Color.LIGHT_GRAY);

AddLabel(yes, "ETF Sect Rotate", Color.BLUE); #ES

script calcBeta {
    input secondSymbol = "XLF";
    input refSymbol = "SPX";
    input betaLength = 21;
    input returnLength = 1;

    def refPrice = close(refSymbol);
    def primary = if refPrice[returnLength] == 0
                then 0
                else (refPrice - refPrice[returnLength]) / refPrice[returnLength] * 100;
    def secondPrice = close(secondSymbol);
    def secondary = if secondPrice[returnLength] == 0
                  then 0
                  else (secondPrice - secondPrice[returnLength]) / secondPrice[returnLength] * 100;
    plot Beta = Covariance(secondary, primary, betaLength) / Sqr(StDev(primary, betaLength));
}

script EhlersESSfilter {
    input price = close;
    input length = 8;
    def ESS_coeff_0 = Exp(-Double.Pi * Sqrt(2) / length);
    def ESS_coeff_2 = 2 * ESS_coeff_0 * Cos(Sqrt(2) * Double.Pi / length);
    def ESS_coeff_3 = - Sqr(ESS_coeff_0);
    def ESS_coeff_1 = 1 - ESS_coeff_2 - ESS_coeff_3;
    def ESS_filter = if IsNaN(price + price[1]) then
                      ESS_filter[1]
                 else ESS_coeff_1 * (price + price[1]) / 2 +
                      ESS_coeff_2 * ESS_filter[1] +
                      ESS_coeff_3 * ESS_filter[2];
    plot Smooth_Filter =
         if BarNumber() <  length then
              price
         else if !IsNaN(price) then
              ESS_filter
         else Double.NaN;
}

script calcStoch {
    input data = close;
    input StochLength = 21;
    def stochasticValue = ((data - Lowest(data, StochLength)) / (Highest(data, StochLength) - Lowest(data, StochLength)));
    plot stoch = stochasticValue;
}

####

#Added 1-29-22 ES
#SectorRelativePerformance
################
# Displays relative performance over defined period
# Intended for Sector Analysis
# Created 7/15/18 RmS59

declare lower;

input n1 = "  Analysis Inputs";
input Period = 60;
input price = FundamentalType.CLOSE;
input smoothPeriod = 5;
input DisplayLabel = 1;
input DisplayAltIndex = 1;

input n2 = "  Sector Inputs";
#input Base = "SPX";
input AltIndex1 = "NDX";
input AltIndex2 = "RUT";

#changed to match primary study, some added ES 1-20-22

#input Energy = {default "$SP500#10","XLE"};
#input Materials = {default "$SP500#15", "XLB"};
#input Industrials = {default "$SP500#20", "XLI"};
input ConsDiscr = {default "$SP500#25", "XLY"};
input ConsStpls = {default "$SP500#30", "XLP"};
#input Healthcare = {default "$SP500#35", "XLV"};
#input Financials = {default "$SP500#40", "XLF"};
input InfoTech = {default "$SP500#45", "XLK"};
input Telecom = {default "$SP500#50", "XTL"}; #changed
#input Utilities = {default "$SP500#55", "XLU"};
#input RealEstate = "XLRE";
#input Retail = "XRT";

# For Reference, the S&P500 Sectors are as follows:
# Energy = "$SP500#10";
# Materials = "$SP500#15";
# Industrials = "$SP500#20";
# ConsDiscr = "$SP500#25";
# ConsStpls = "$SP500#30";
# Healthcare = "$SP500#35";
# Financials = "$SP500#40";
# InfoTech = "$SP500#45"
# Telecom = "$SP500#50";
# Utilities = "$SP500#55";


def priceBase = Fundamental(price);
#def priceBase = Fundamental(price, Base);
def priceAltIndex1 = Fundamental(price, AltIndex1);
def priceAltIndex2 = Fundamental(price, AltIndex2);

def priceEnergy = Fundamental(price, Energy);
def priceMaterials = Fundamental(price, Materials);
def priceIndustrials = Fundamental(price, Industrials);
def priceConsDiscr = Fundamental(price, ConsDiscr);
def priceConsStpls = Fundamental(price, ConsStpls);
def priceHealthcare = Fundamental(price, HealthCare);
def priceFinancials = Fundamental(price, Financials);
def priceInfoTech = Fundamental(price, InfoTech);
def priceTelecom = Fundamental(price, Telecom);
def priceUtilities = Fundamental(price, Utilities);
def priceRealEstate = Fundamental(price, RealEstate);
def priceRetail = Fundamental(price, Retail);

def changeBase = (priceBase - priceBase[Period]) / priceBase[Period];
def changeAltIndex1 = (priceAltIndex1 - priceAltIndex1[Period]) / priceBase[Period];
def changeAltIndex2 = (priceAltIndex2 - priceAltIndex2[Period]) / priceBase[Period];

def changeEnergy = (priceEnergy - priceEnergy[Period]) / priceEnergy[Period];
def changeMaterials = (priceMaterials - priceMaterials[Period]) / priceMaterials[Period];
def changeIndustrials = (priceIndustrials - priceIndustrials[Period]) / priceIndustrials[Period];
def changeConsDiscr = (priceConsDiscr - priceConsDiscr[Period]) / priceConsDiscr[Period];
def changeConsStpls = (priceConsStpls - priceConsStpls[Period]) / priceConsStpls[Period];
def changeHealthcare = (priceHealthcare - priceHealthcare[Period]) / priceHealthcare[Period];
def changeFinancials = (priceFinancials - priceFinancials[Period]) / priceFinancials[Period];
def changeInfoTech = (priceInfoTech - priceInfoTech[Period]) / priceInfoTech[Period];
def changeTelecom = (priceTelecom - priceTelecom[Period]) / priceTelecom[Period];
def changeUtilities = (priceUtilities - priceUtilities[Period]) / priceUtilities[Period];
def changeRealEstate = (priceRealEstate - priceRealEstate[Period]) / priceRealEstate[Period];
def changeRetail = (priceRetail - priceRetail[Period]) / priceRetail[Period];

plot BasePerf = if priceBase == 0 then Double.NaN else Round(MovAvgExponential(changeBase - changeBase, 2), smoothPeriod);
plot AltIndex1Perf = if priceAltIndex1 == 0 then Double.NaN else Round(100 * (changeAltIndex1 - changeBase), 1);
plot AltIndex2Perf = if priceAltIndex2 == 0 then Double.NaN else Round(100 * (changeAltIndex2 - changeBase), 1);

plot EnergyPerf = if priceEnergy == 0 then Double.NaN else Round(ExpAverage(100 * (changeEnergy - changeBase), smoothPeriod), 1);
plot MaterialsPerf = if priceMaterials == 0 then Double.NaN else Round(ExpAverage(100 * (changeMaterials - changeBase), smoothPeriod), 1);
plot IndustrialsPerf = if priceIndustrials == 0 then Double.NaN else Round(ExpAverage(100 * (changeIndustrials - changeBase), smoothPeriod), 1);
plot ConsDiscrPerf = if priceConsDiscr == 0 then Double.NaN else Round(ExpAverage(100 * (changeConsDiscr - changeBase), smoothPeriod) , 1);
plot ConsStplsPerf = if priceConsStpls == 0 then Double.NaN else Round(ExpAverage(100 * (changeConsStpls - changeBase), smoothPeriod), 1);
plot HealthcarePerf = if priceHealthcare == 0 then Double.NaN else Round(ExpAverage(100 * (changeHealthcare - changeBase), smoothPeriod), 1);
plot FinancialsPerf = if priceFinancials == 0 then Double.NaN else Round(ExpAverage(100 * (changeFinancials - changeBase), smoothPeriod), 1);
plot InfoTechPerf = if priceInfoTech == 0 then Double.NaN else Round(ExpAverage(100 * (changeInfoTech - changeBase), smoothPeriod), 1);
plot TelecomPerf = if priceTelecom == 0 then Double.NaN else Round(ExpAverage(100 * (changeTelecom - changeBase), smoothPeriod), 1);
plot UtilitiesPerf = if priceUtilities == 0 then Double.NaN else Round(ExpAverage(100 * (changeUtilities - changeBase), smoothPeriod), 1);
plot RealEstatePerf = if priceRealEstate == 0 then Double.NaN else Round(ExpAverage(100 * (changeRealEstate - changeBase), smoothPeriod), 1);
plot RetailPerf = if priceRetail == 0 then Double.NaN else Round(ExpAverage(100 * (changeRetail - changeBase), smoothPeriod), 1);

plot Zero = if !IsNaN(close) then 0 else Double.NaN;

AltIndex1Perf.SetDefaultColor(Color.LIGHT_RED);
AltIndex2Perf.SetDefaultColor(Color.LIME);

#EnergyPerf.SetDefaultColor(Color.LIGHT_GRAY);
MaterialsPerf.SetDefaultColor(Color.CYAN);
IndustrialsPerf.SetDefaultColor(Color.MAGENTA);
ConsDiscrPerf.SetDefaultColor(Color.VIOLET);
ConsStplsPerf.SetDefaultColor(Color.DARK_GREEN);
HealthcarePerf.SetDefaultColor(Color.PLUM);
FinancialsPerf.SetDefaultColor(Color.DARK_RED);
InfoTechPerf.SetDefaultColor(Color.GREEN);
TelecomPerf.SetDefaultColor(Color.LIGHT_GREEN);
UtilitiesPerf.SetDefaultColor(Color.ORANGE);
RealEstatePerf.SetDefaultColor(Color.WHITE);

#AddLabel(DisplayLabel, period +" Period RS/"+ GetUnderlyingSymbol() + " " + smoothPeriod + " Sm",  Color.WHITE);
#AddLabel(DisplayLabel, "  ",Color.DARK_GRAY);
#AddLabel(DisplayLabel && DisplayAltIndex, " "+ AltIndex1 + " " + AltIndex1Perf + "%",AltIndex1Perf.TakeValueColor());
#AddLabel(DisplayLabel && DisplayAltIndex, " "+ AltIndex2 + " " + AltIndex2Perf + "%",AltIndex2Perf.TakeValueColor());

#AddLabel(DisplayLabel, " Energy "+ Energy + " " + EnergyPerf + "%",EnergyPerf.TakeValueColor());
#AddLabel(DisplayLabel, " Materials "+ Materials + " " + MaterialsPerf + "%",MaterialsPerf.TakeValueColor());
#AddLabel(DisplayLabel, " Industrials "+ Industrials + " " + IndustrialsPerf + "%",IndustrialsPerf.TakeValueColor());
#AddLabel(DisplayLabel, " ConsDiscr "+ ConsDiscr + " " + ConsDiscrPerf + "%",ConsDiscrPerf.TakeValueColor());
#AddLabel(DisplayLabel, " ConsStpls "+ ConsStpls + " " + ConsStplsPerf + "%",ConsStplsPerf.TakeValueColor());
#AddLabel(DisplayLabel, " Healthcare "+ Healthcare + " " + HealthcarePerf + "%",HealthcarePerf.TakeValueColor());
#AddLabel(DisplayLabel, " Financials "+ Financials + " " + FinancialsPerf + "%",FinancialsPerf.TakeValueColor());
#AddLabel(DisplayLabel, " InfoTech "+ InfoTech + " " + InfoTechPerf + "%",InfoTechPerf.TakeValueColor());
#AddLabel(DisplayLabel, " CommSvc "+ Telecom + " " + TelecomPerf + "%",TelecomPerf.TakeValueColor());
#AddLabel(DisplayLabel, " Utilities "+ Utilities + " " + UtilitiesPerf + "%",UtilitiesPerf.TakeValueColor());
#AddLabel(DisplayLabel, " RealEstate "+ RealEstate + " " + RealEstatePerf + "%",RealEstatePerf.TakeValueColor());
#AddLabel(DisplayLabel, " Retail "+ Retail + " " + RetailPerf + "%",RetailPerf.TakeValueColor());
#### End



####
#labels shortened and changed names, added sectors from SectorRelativePerformance ES 1-20-22

def upStochLimit = 0.95;
def lowStockLimit = 0.05;

def stoch1 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Cyclicals, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "ConsDiscr " + ConsDiscrPerf + "%",
if stoch1 <= lowStockLimit then GlobalColor("negative") else
if stoch1 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch1 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch2 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Technology, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Tech " + InfoTechPerf + "%",
if stoch2 <= lowStockLimit then GlobalColor("negative") else
if stoch2 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch2 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch3 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Industrials, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Industr " + IndustrialsPerf + "%",
if stoch3 <= lowStockLimit then GlobalColor("negative") else
if stoch3 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch3 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch4 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Materials, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Mtls " + MaterialsPerf + "%",
if stoch4 <= lowStockLimit then GlobalColor("negative") else
if stoch4 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch4 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch5 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Energy, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Energy " + EnergyPerf + "%",
if stoch5 <= lowStockLimit then GlobalColor("negative") else
if stoch5 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch5 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch6 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Staples, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "ConsStpls " + ConsStplsPerf + "%",
if stoch6 <= lowStockLimit then GlobalColor("negative") else
if stoch6 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch6 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch7 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = HealthCare, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Health " + HealthcarePerf + "%",
if stoch7 <= lowStockLimit then GlobalColor("negative") else
if stoch7 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch7 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch8 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Utilities, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Util " + UtilitiesPerf + "%",
if stoch8 <= lowStockLimit then GlobalColor("negative") else
if stoch8 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch8 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch9 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Financials, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Finance " + FinancialsPerf + "%",
if stoch9 <= lowStockLimit then GlobalColor("negative") else
if stoch9 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch9 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch10 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Communications, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Comms " + TelecomPerf  + "%",
if stoch10 <= lowStockLimit then GlobalColor("negative") else
if stoch10 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch10 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch11 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = RealEstate, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "RealEst " + RealEstatePerf  + "%",
if stoch11 <= lowStockLimit then GlobalColor("negative") else
if stoch11 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch11 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

def stoch12 = calcStoch( data = EhlersESSfilter( calcBeta(secondSymbol = Retail, betaLength = betaLength) ), stochLength = StochLength);
AddLabel(showOverlay, "Retail " + RetailPerf + "%",
if stoch11 <= lowStockLimit then GlobalColor("negative") else
if stoch11 >= upStochLimit  then GlobalColor("TRENDING") else
if stoch11 >= stoch1[1] then GlobalColor("positive") else GlobalColor("rising"));

AddLabel(yes, " ", Color.BLACK);
@evilsurgeon Thank you for the script, pls correct me if my interpretation of the sector rotation is wrong.

#Rotation Colors from Money In to Money Out; changed colors based on preference ES
DefineGlobalColor("TRENDING", Color.DARK_GREEN); #Great
DefineGlobalColor("positive", CreateColor(0, 175, 0)) ; #good green
DefineGlobalColor("negative", Color.RED) ; #bad red
DefineGlobalColor("rising", Color.YELLOW) ; #Light Slate Blue changed to yellow


To check fund flow of the stock, we just need to look at the sector where our stocks are categorised to determine whether the funds are flowing in or out, based on the color codes above. In your attached pic, INTC is showing that the funds are flowing out from Tech Sector abt -2.3% on the day of trading. Is that correct ?

In the same pic, consumer discretionary has a value is -5.2% (but GREEN), may I know what does that mean when it is shown together with INTC chart. What does negative 5.2 with green color mean?



My confusion arises when I open NKE chart, XLY sector has a positive, which may explain why it was painted GREEN previous, but the XLK is also positive (BUT yellow), may I know what does that mean?

Thank you
 

Similar threads

Top