Least Squares Indicator for ThinkorSwim

ebtrader

ebtrader

New member
Good morning all! Thanks for including me in this group.

Here is one of my favorite studies. It uses the Least Squares Method. I would love your thoughts.

There is nothing out there that can catch the turns as well as this baby can!

Code:
 #LeastSquares created by tradescripter
    #Dec. 24, 2010 Merry Christmas
    #It uses the Least-Squares Method to forecast a new price
    #For an explanation of Least-Squares method see:
    #http://en.wikiversity.org/wiki/Least-Squares_Method


#Hint PriceColorOn: Affect the color of the Price bars according to the signals of this indicator\n<b>Default is Yes
#Hint ArrowsOn: Plot Arrows at signal changes \n<b>Default is Yes
#Hint PredictionLineOn: Plot the indicator \n<b>Default is Yes
#Hint ShowTodayOnly: Plot only the most recent arrows in order not to clutter the Price history\nMakes it easier to see prior prices \n<b>Default is no
#Hint ShowExtraDays: Further adjustment to Show Only Today \n<b>Default is 0
#Hint space: Allows you to move the arrows, and avoid stepping on other arrows when multiple studies are shown \n<b>Default is 0.333
#Hint length: Touch this only if you are an expert! Just kidding. \n<b>Default is 9
#Hint price: For the experimenter \n<b>Default is HL2


#FuturePredictor

input price = close;
input length = 9;
input PredictionLineOn = Yes;
# Input BubblesOn = No;
input ShowTodayOnly = no;
input ShowExtraDays = 0;
input space = 0.333;


def Today = if !ShowTodayOnly then 1 else if GetDay() + ShowExtraDays >= GetLastDay() then 1 else 0;

def AvgPrice = Average(price, length);
def SumTime = fold i = 1 to length + 1 with x = 0 do x + i;
def AvgTime = SumTime / length;
    #sx is the sum of all the deviations from time for the last x bars
def sx = fold j = 1 to length + 1 with y = 0 do y + ((j - AvgTime) * (GetValue(price, length - j, length + 1) - AvgPrice));
        #sy is the sum of all the deviations from price for the last x bars
def sy = fold k = 1 to length + 1 with z = 0 do z + (Power(k - AvgTime, 2));
        #m is the slope of the line, b is the slope intercept of the line in the equation y = mx + b
def m = sx / sy;
def b = AvgPrice - m * AvgTime;
def Prediction = (m * (length + 1)) + b;
plot FuturePrediction = if !PredictionLineOn then Double.NaN else Prediction;
FuturePrediction.AssignValueColor(if FuturePrediction > FuturePrediction[1] then Color.GREEN else Color.RED);
FuturePrediction.SetLineWeight(3);
FuturePrediction.HideBubble();

 
Last edited:
horserider

horserider

Well-known member
VIP
Version with some additions.

Code:
# LeastSquaresMethodForecast_R1V2
    #
    # http://finance.groups.yahoo.com/group/TOS_thinkscript/message/6671
    # R1V0   2010.12.24          TradeScripter
    #
    # R1V1   2010.12.26:06:22    ebtrader
    # R1V2   2010.12.27:08:00    KumoBob
    #        Added Price Color and Arrows
    #        Option to remove any plot
    #        Added Chart Labels
    #         
# R1V3   2010.12.27:16:10    KumoBob
#        Added plot Today Only
#        Added Hints
# R2V1   2010.12.28:15:42 EBTrader
#        Added Regression Channel
#        Added Money Management
#        Added Bubble Option

# R2V2   2010.01.07: 16:06 KumoBob
#         Alternated Arrows

# R2V3   2010.01.11: 18:30 EBTrader
#         Made colors more consistent and added sell bubble


    #This program created by tradescripter
    #Dec. 24, 2010 Merry Christmas
    #It uses the Least-Squares Method to forecast a new price
    #For an explanation of Least-Squares method see:
    #http://en.wikiversity.org/wiki/Least-Squares_Method

#Hint PriceColorOn: Affect the color of the Price bars according to the signals of this indicator\n<b>Default is Yes
#Hint ArrowsOn: Plot Arrows at signal changes \n<b>Default is Yes
#Hint PredictionLineOn: Plot the indicator \n<b>Default is Yes
#Hint ShowTodayOnly: Plot only the most recent arrows in order not to clutter the Price history\nMakes it easier to see prior prices \n<b>Default is no
#Hint ShowExtraDays: Further adjustment to Show Only Today \n<b>Default is 0
#Hint space: Allows you to move the arrows, and avoid stepping on other arrows when multiple studies are shown \n<b>Default is 0.333
#Hint length: Touch this only if you are an expert! Just kidding. \n<b>Default is 9
#Hint price: For the experimenter \n<b>Default is HL2


AssignBackgroundColor(CreateColor(8, 0, 15));
input length = 9;
input price = HL2;
input PriceColorOn = Yes;
input ArrowsOn = Yes;
input PredictionLineOn = Yes;
input BubblesOn = No;
input ShowTodayOnly = no;
input ShowExtraDays = 0;
input space = 0.333;
def Today = if !ShowTodayOnly then 1 else if GetDay() + ShowExtraDays >= GetLastDay() then 1 else 0;

def AvgPrice = Average(price, length);
def SumTime = fold i = 1 to length + 1 with x = 0 do x + i;
def AvgTime = SumTime / length;
    #sx is the sum of all the deviations from time for the last x bars
def sx = fold j = 1 to length + 1 with y = 0 do y + ((j - AvgTime) * (GetValue(price, length - j, length + 1) - AvgPrice));
        #sy is the sum of all the deviations from price for the last x bars
def sy = fold k = 1 to length + 1 with z = 0 do z + (Power(k - AvgTime, 2));
        #m is the slope of the line, b is the slope intercept of the line in the equation y = mx + b
def m = sx / sy;
def b = AvgPrice - m * AvgTime;
def Prediction = (m * (length + 1)) + b;
plot FuturePrediction = if !PredictionLineOn then Double.NaN else Prediction;
FuturePrediction.AssignValueColor(if FuturePrediction > FuturePrediction[1] then Color.GREEN else Color.RED);
FuturePrediction.SetLineWeight(3);
FuturePrediction.HideBubble();


AssignPriceColor(if !PriceColorOn then Color.CURRENT else if Prediction > Prediction[1] then (CreateColor(000, 255, 255)) else if Prediction < Prediction[1] then (CreateColor(255, 160, 000)) else Color.GRAY);
AddLabel(PriceColorOn , "Price Color On", if Prediction > Prediction[1] then Color.GREEN else if Prediction < Prediction[1] then Color.RED else Color.GRAY);

AddLabel(ArrowsOn, "MagentaArrows=LeastSquares",  if Prediction > Prediction[1] then Color.GREEN else if Prediction < Prediction[1] then Color.RED else Color.GRAY);

def spaceman = Average(high - low) * space;
def xover = Crosses(Prediction, Prediction[1], CrossingDirection.ANY);
plot UpArrow = if Today && xover && Prediction > Prediction[1] then low - spaceman else Double.NaN;
UpArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
UpArrow.SetDefaultColor(Color.MAGENTA);
plot DnArrow = if Today && xover && Prediction < Prediction[1] then high + spaceman else Double.NaN;
DnArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
DnArrow.SetDefaultColor(Color.MAGENTA);

    #    plot firstup = crosses((Prediction > low), yes) && Prediction < Prediction[1];
    #    firstup.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

    #    plot firstdown = crosses((Prediction < high), yes) && Prediction > Prediction[1];
    #    firstdown.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

rec LastArrow = if low > Prediction && LastArrow[1] <> 1 && Prediction < Prediction[1] then 1 else
    if high < Prediction && LastArrow[1] <> -1 && Prediction > Prediction[1] then -1 else LastArrow[1];

plot firstup = if Today && LastArrow > 0 && LastArrow <> LastArrow[1]  then low else Double.NaN;
firstup.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
firstup.SetLineWeight(5);
firstup.SetDefaultColor(Color.YELLOW);
plot firstdown = if Today && LastArrow < 0 && LastArrow <> LastArrow[1]  then high else Double.NaN;
firstdown.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
firstdown.SetLineWeight(5);
firstdown.SetDefaultColor(Color.YELLOW);






#
# Linear Regression with Standard Deviation Channels
#
#  Written by Robert Hall
#   Released 10 April 2009
#
#
#  Standard Deviation can be input to 2 decimal places
#

input standardDeviation = 1.5;
input startDateYyyyMmDd = 20110105;
input startTime = 0030;



plot MiddleLR = InertiaAll(price, length, startDateYyyyMmDd, startTime, extendtoright = 1);

def dist = HighestAll(AbsValue(MiddleLR - price)) * standardDeviation / 2;

plot UpperLR = MiddleLR + dist;
plot LowerLR = MiddleLR - dist;

MiddleLR.SetDefaultColor(Color.WHITE);
MiddleLR.SetLineWeight(1);
MiddleLR.SetStyle(Curve.FIRM);

UpperLR.SetDefaultColor(Color.CYAN);
UpperLR.SetLineWeight(1);
UpperLR.SetStyle(Curve.FIRM);

LowerLR.SetDefaultColor(Color.CYAN);
LowerLR.SetLineWeight(1);
LowerLR.SetStyle(Curve.FIRM);

#    Money Management

# Longs

def exposure20pct = LastArrow < 0 && LastArrow <> LastArrow[1];

def exposure40pct = Prediction[3] > Prediction[4] && Prediction[2] > Prediction[3] && Prediction[1] > Prediction[2] && Prediction > Prediction[1] ;

def exposure60pct = Prediction[2] > Prediction[3] && Prediction[1] > Prediction[2] && Prediction > Prediction[1];

def exposure80pct = Prediction[1] > Prediction[2] && Prediction > Prediction[1];

def exposure100pct = xover && Prediction > Prediction[1];

# Shorts

def exposureneg20pct = LastArrow > 0 && LastArrow <> LastArrow[1];

def exposureneg40pct = Prediction[3] < Prediction[4] && Prediction[2] < Prediction[3] && Prediction[1] < Prediction[2] && Prediction < Prediction[1];

def exposureneg60pct = Prediction[2] < Prediction[3] && Prediction[1] < Prediction[2] && Prediction < Prediction[1];

def exposureneg80pct = Prediction[1] < Prediction[2] && Prediction < Prediction[1];

def exposureneg100pct = xover && Prediction < Prediction[1];



AddLabel(yes, Concat( "", Concat(" ", 
if exposure20pct then "Long 20% " else 
if exposure40pct then "Long 40% " else
if exposure60pct then "Long 60%" else
if exposure80pct then "Long 60%" else
if exposure100pct then "Long 100%" else

if exposureneg20pct then "Short 20% " else 
if exposureneg40pct then "Short 40% " else
if exposureneg60pct then "Short 60%" else
if exposureneg80pct then "Short 60%" else
if exposureneg100pct then "Short 100%" else
"Go Flat")), 

if exposure20pct then Color.CYAN else 
if exposure40pct then  Color.CYAN else 
if exposure60pct then  Color.CYAN else
if exposure80pct then Color.CYAN else 
if exposure100pct then  Color.CYAN else
if exposureneg20pct then Color.ORANGE else 
if exposureneg40pct then Color.ORANGE else
if exposureneg60pct then Color.ORANGE else
if exposureneg80pct then Color.ORANGE else
if exposureneg100pct then Color.ORANGE else
Color.WHITE);

AddChartBubble(BubblesOn && xover && Prediction > Prediction[1] , low, Concat("Buy Baby", HL2), Color.CYAN, yes);

AddChartBubble(BubblesOn && xover && Prediction < Prediction[1] , high, Concat("Sell That Bad Boy", HL2), Color.ORANGE, yes);

# ************************************************************
 
ebtrader

ebtrader

New member
i love those additions as well. feel free to ask me about any of the stuff in the code. If anyone is interested, there is a way to extend those regression channels into the future as well.

has anyone used this indicator at all in the past or currently?
 
horserider

horserider

Well-known member
VIP
Double LS lower study I did a while back. Different lengths to look for color agreement.

 
D

diazlaz

Well-known member
2019 Donor
VIP
LR and Least Square methods work best for inter and longer time frames, my experience and in discussions with other CMTs, they were never designed for short term/intraday trading. This indicator will work for longer holdings and timeframes.

if anyone has experience using this successfully for short term time frames or have a pairing that works let us know.
 
H

Hguru

Member
someone please explain the LS Lower study when you get a chance and what the settings mean too thanks
 
horserider

horserider

Well-known member
VIP
Hguru Just 2 LS studis with different length inputs. The idea saw both turning red or green was a safer signal. Sometimes th short length will change color while the longer length does not. So then you could look at whether that was a false or true change. If the short then bounces good chance it is not a change in direction.
 
horserider

horserider

Well-known member
VIP
It is a linear regression slope using least squares method. It is curve fitting as far as I understand. Can an explaination be given why it is not suitable for any time frame. Just curious , I do not use it.
 
A

asianboy

New member
Can any one convector this tradeview scrip to thinkorswim script

//SMA(25)≒FLSMA(25,7,13)
//SMA(50)≒FLSMA(50,13,26)
//SMA(75)≒FLSMA(75,20,26)


study(title = "Future Least Squares Moving Average", shorttitle="FLSMA", overlay=true)


length = input(title="Length", type=integer, defval=75)
offset = input(title="Offset", type=integer, defval=20)
displacement = input(26, minval=1)

src = input(close, title="Source")

lsma = linreg(src, length, offset)
plot(lsma, offset = displacement-1, color=blue, title="FLSMA" )
 
M

Mindlessmentor

New member
What are the differences between the yellow and the purple arrows? I also see the magneta arrows label going green and red, and the short and long % changing. I really like this indicator and i'd like to test it out. Any assistance will be greatly appreciated. thanks
 
Last edited:
horserider

horserider

Well-known member
VIP
@Mindlessmentor My suggestion, turn off the arrows and make sure you know how it works. There is a hint above.
 
T

TK_44

New member
VIP
i love those additions as well. feel free to ask me about any of the stuff in the code. If anyone is interested, there is a way to extend those regression channels into the future as well.

has anyone used this indicator at all in the past or currently?
@ebtrader I love this version of this indicator, thanks for posting. How can I extend the regression channel?
 

Similar threads

Top