Skip to content
This repository has been archived by the owner on Sep 2, 2022. It is now read-only.

linear regression for Squeeze Momentum Indicator #120

Open
tesla-cat opened this issue Jun 28, 2021 · 7 comments
Open

linear regression for Squeeze Momentum Indicator #120

tesla-cat opened this issue Jun 28, 2021 · 7 comments

Comments

@tesla-cat
Copy link

  • your code doesn't contain linreg compared with the one found from trading-view, may I ask why?

  • yours:

    @classmethod
    def SQZMI(cls, ohlc: DataFrame, period: int = 20, MA: Series = None) -> DataFrame:
        """
        Squeeze Momentum Indicator
        The Squeeze indicator attempts to identify periods of consolidation in a market.
        In general the market is either in a period of quiet consolidation or vertical price discovery.
        By identifying these calm periods, we have a better opportunity of getting into trades with the potential for larger moves.
        Once a market enters into a “squeeze”, we watch the overall market momentum to help forecast the market direction and await a release of market energy.
        :param pd.DataFrame ohlc: 'open, high, low, close' pandas DataFrame
        :period: int - number of periods to take into consideration
        :MA pd.Series: override internal calculation which uses SMA with moving average of your choice
        :return pd.Series: indicator calcs as pandas Series
        SQZMI['SQZ'] is bool True/False, if True squeeze is on. If false, squeeeze has fired.
        """

        if not isinstance(MA, pd.core.series.Series):
            ma = pd.Series(cls.SMA(ohlc, period))
        else:
            ma = None

        bb = cls.BBANDS(ohlc, period=period, MA=ma)
        kc = cls.KC(ohlc, period=period, kc_mult=1.5)
        comb = pd.concat([bb, kc], axis=1)

        def sqz_on(row):
            if row["BB_LOWER"] > row["KC_LOWER"] and row["BB_UPPER"] < row["KC_UPPER"]:
                return True
            else:
                return False

        comb["SQZ"] = comb.apply(sqz_on, axis=1)

        return pd.Series(comb["SQZ"], name="{0} period SQZMI".format(period))
  • trading-view:
//
// @author LazyBear 
// List of all my indicators: https://www.tradingview.com/v/4IneGo8h/
//
study(shorttitle = "SQZMOM_LB", title="Squeeze Momentum Indicator [LazyBear]", overlay=false)

length = input(20, title="BB Length")
mult = input(2.0,title="BB MultFactor")
lengthKC=input(20, title="KC Length")
multKC = input(1.5, title="KC MultFactor")

useTrueRange = input(true, title="Use TrueRange (KC)", type=bool)

// Calculate BB
source = close
basis = sma(source, length)
dev = multKC * stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev

// Calculate KC
ma = sma(source, lengthKC)
range = useTrueRange ? tr : (high - low)
rangema = sma(range, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC

sqzOn  = (lowerBB > lowerKC) and (upperBB < upperKC)
sqzOff = (lowerBB < lowerKC) and (upperBB > upperKC)
noSqz  = (sqzOn == false) and (sqzOff == false)

val = linreg(source  -  avg(avg(highest(high, lengthKC), lowest(low, lengthKC)),sma(close,lengthKC)), 
            lengthKC,0)

bcolor = iff( val > 0, 
            iff( val > nz(val[1]), lime, green),
            iff( val < nz(val[1]), red, maroon))
scolor = noSqz ? blue : sqzOn ? black : gray 
plot(val, color=bcolor, style=histogram, linewidth=4)
plot(0, color=scolor, style=cross, linewidth=2)
@AGG2017
Copy link

AGG2017 commented Aug 8, 2021

This type of linear regression will be a bit challenging but recently I found another implementation with numpy polyfit that claimed to produce the same results as linreg in TradingView. I cannot remember where it was but try to search for "python, polyfit, linreg, tradingview" and you will find it. In fact in TradingView this function is a rolling linear regression which is not linear at all.

@arbitrage-technology
Copy link

squizz indicator has nothing to do with a linear regression.. it just tells you, if BB is contained inside KC bands...if this is the case, its a calm moment, ready for the the next squizz....

@AGG2017
Copy link

AGG2017 commented Aug 30, 2021

@arbitrage-technology Just to tell you if BB is inside KC is only one part of the indicator at TV. It also try to show you the level of the current momentum in order to enter on the right side of the trend as well as to exit when the momentum starts to decrease. The momentum can be implemented in many ways but LazyBear decided to use the rolling linear regression function available at TV to calculate the momentum and to show it as a histogram. This is somehow tricky because sometimes the moment of squeeze release is at the wrong side of the shown momentum. The missing part are the Waves A, B and C which are the part of the whole story well described by its creator John F. Carter.

@arbitrage-technology
Copy link

arbitrage-technology commented Aug 30, 2021 via email

@AGG2017
Copy link

AGG2017 commented Aug 30, 2021

The book "Mastering the Trade" by John Carter is a one that must be read in order to understand many important details how to successfuly use this indicator.
All the elements of this indicator are freely available and even done in python. Just need to be assembled. I'm trying to complete the implementation for the Waves A, B and C to have everything together. But there is always something more important to be done before that.

@verdaguer70
Copy link

I have done this :D 💯
image

@p-lorenzo
Copy link

I have done this :D 💯 image

How did you manage to replicate the tradingview sqz? could you provide the code?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants