Relative slopeRelative slope metric
Description:
I was in need to create a simple, naive and elegant metric that was able to tell how strong is the trend in a given rolling window. While abstaining from using more complicated and arguably more precise approaches, I’ve decided to use Linearly Weighted Linear Regression slope for this goal. Outright values are useful, but the problem was that I wasn’t able to use it in comparative analysis, i.e between different assets & different resolutions & different window sizes, because obviously the outputs are scale-variant.
Here is the asset-agnostic, resolution-agnostic and window size agnostic version of the metric.
I made it asset agnostic & resolution agnostic by including spread information to the formula. In our case it's weighted stdev over differenced data (otherwise we contaminate the spread with the trend info). And I made it window size agnostic by adding a non-linear relation of length to the output, so finally it will be aprox in (-1, 1) interval, by taking square root of length, nothing fancy. All these / 2 and * 2 in unexpected places all around the formula help us to return the data to it’s natural scale while keeping the transformations in place.
Peace TV
Slope
StrengthA mathematically elegant, native & modern way how to measure velocity/ strength/ momentum. As you can see it looks like MACD, but !suddenly! has N times shorter code (disregard the functions), and only 1 parameter instead of 3. OMG HOW DID HE DO IT?!?
MACD: "Let's take one filter (1 parameter), than another filter (2 parameters), then let's take dem difference, then let's place another filter over the difference (3rd parameter + introduction of a nested calculation), and let's write a whole book about it, make thousands of multi-hours YouTube videos about it, and let's never mention about the amount of uncertainty being introduced by multiple parameters & introduction of the nested calculation."
Strength: "let's get real, let's drop a weighted linear regression & usual linear regression over the data of the same length, take dem slopes, then make the difference over these slopes, all good. And then share it with people w/o putting an ® sign".
Fyi, regressions were introduced centuries ago, maybe decades idk, the point is long time ago, and computational power enough to calculate what I'm saying is slightly more than required for macd.
Rationale.
Linearly weighted linear regression has steeper slope (W) than the usual linear regression slope (S) due to the fact that the recent datapoints got more weight. This alone is enough of a metric to measure velocity. But still I've recalled macd and decided to make smth like it cuz I knew it'll might make you happy. I realized that S can be used instead of smoothing the W, thus eliminating the nested calculation and keeping entropy & info loss in place. And see, what we get is natural, simple, makes sense and brings flex. I also wanna remind you that by applying regression we maximize the info gain by using all the data in the window, instead of taking difference between the first and the last datapoints.
This script is dedicated to my friend Fabien. Man, you were the light in the darkness in that company. You'll get your alien green Lambo if you'll really want it, no doubts on my side bout that.
Good hunting
4C Moving Avg CloudThis indicator plots 2 moving averages with a cloud filling the area between the two.
It has the unique ability to choose between multiple moving average types, AND also paints the average based on slope direction, all in one indicator.
Most of the available moving average cloud indictors only allow one type of moving average for both averages together (e.g. 21 EMA with 200 EMA; or 21 SMA with 200 SMA)
The 4C Moving Avg Cloud features the ability to choose a different average type for each of the moving averages, and can be mixed and matched (e.g. 21 EMA with 200 SMA; or 21 RMA with 200 EMA; etc...)
Offers a selection for each of the moving averages to choose between: EMA, SMA, RMA, WMA
Credit: Some aspects of this part of the 4C moving avg cloud indicator were adapted from the "Best Cloud All MA" indicator @author=Daveatt
Another unique aspect of this moving avg cloud indicator is that is paints the moving average lines based on slope direction.
If the slope direction of the avg is up, it is painted one color, and if the avg is sloping down, it is painted another color (default: red).
This slope coloring is based on a 1 period lookback, and cant be adjusted.
4C ATR w/ Reference LineThe 4C ATR is a simple indicator that plots a horizontal line on the ATR indicator, which can be used as a minimum or maximum reference value.
Some trading setups have specific criteria that require a minimum ATR on a certain timeframe for the instrument to be playable. The horizontal line is useful as a quick visual reference, and can be adjusted to any specific level for any timeframe. If the ATR dips below the horizontal line, the trader can quickly see that the ATR is below the minimum criteria, and should not trade that instrument (based on their personal trade criteria).
This indicator also features a color change of the ATR line based on trend direction. If the ATR is trending up, it is painted blue, and if it starts to trend down, it is painted red. It uses a hidden simple moving average of the ATR, and the slope direction of the moving average paints the ATR line. The moving average length can be adjusted, and is set at a length of 8 for default. The ATR is set at a default value of 14.
Parts of this script used the default/stock Tradingview ATR indicator to build off of.
The Bounded Slope IndicatorThis indicator uses the concept of slopes and normalizes the values so that they are bounded between 0 and 100. The steps required to calculate the indicator are as follows:
* Calculate the slope of the price using a lookback period (by default, it is either 14 or 21). The slope is calculated by subtracting the current close price from the close price 21 (or 14) periods ago and dividing the result by 21 (or 14).
* Calculate the RSI of the slope calculations to get a normalized slope indicator.
The bounded slope indicator can be used the same way as the RSI:
* Through oversold and overbought levels. A bullish bias is present whenever the indicator is close to its oversold level (by default, it is 30) and a bearish bias is present whenever the indicator is close to its overbought level (by default, it is 70).
* Through the divergence technique. A bullish bias is present whenever the indicator is making higher lows and the market is making lower lows. A bearish bias is present whenever the indicator is making lower highs and the market is making higher highs.
The main advantage of the indicator is its different approach to measuring momentum which can be a good uncorrelated indicator to other classical ones (such as the stochastic oscillator and the MACD).
Honey CypherHoney Cypher Aims to do 4 things
Momentum
Trend Strength
Overbought and oversold zones
Being the most beautiful indicator you ever see
Momentum
The big yellow honey waves primary use is to see the momentum of the market, they can be used in a similar way you would use a MACD or Chaikin Money Flow
On this image you see the honey waves being plotted to the 30 minute timeframe while on the 5 minute chart to have an understanding of longer time momentum in the chart.
Trend Strength
Most tools of the indicator can be used for that but the yellow and purple slope strength lines are made specificaly for this. When you see them curl down you know trend is strengthening towards the downside.
The candle color is based on the amount of Honey waves sloping in one direction. This might be the best tool in the indicator to find Trend Strength. Bright yellow candles mean strong bears while the bright blue candles mean strong bulls.
Overbought and oversold zones
By analysing the waves on a chart you start to learn how big waves can get before a reversal or consolidation period arrives.
You can become profitable with the indicator. But to be honest, my primary focus in making this indicator was find ways to visualise alot of data in a clear and beautiful way.
You should use the indicator with some out of the box ideas instead of just trusting the signals.
examples:
Find a head and shoulders pattern on the top of a huge honey wave.
Find a bottom small wave while the others honey waves are in the opposite direction for entering a pullback.
Use the honey for direction but the yellow and purple slope line crosses for entrys.
Comment your own strategys, I made this open source to be able to get community feedback.
The Honey Cypher waves are calculated in a similar way as the MACD histogram. I've combined MACD formula with some of the lazybear formula. It looks for the distance between 2 moving averages to find trend strength. After that the end results get's smoothed out. It is very satisfying to change that as you can see the honey waves create a melting like motion on each change of smoothing.
Below a preview of the honey cypher moving average lines, all lines have a length that is based on the fibonacci number sequence. Honey cypher measures the distance between for example length 5-8 averages.
I hope this inspires coders to create very beautiful scripts.
Slope of KAMAShows the slope of KAMA by comparing last bar KAMA value to current bar KAMA value. Very simple, yet very effective determining the trend or volatility of market. When slope is very small market can be in range, hence it can be used as volatility filter for trend traders.
LinearRegressionLibraryLibrary "LinearRegressionLibrary" contains functions for fitting a regression line to the time series by means of different models, as well as functions for estimating the accuracy of the fit.
Linear regression algorithms:
RepeatedMedian(y, n, lastBar) applies repeated median regression (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
mSlope :: float, slope of the regression line
mInter :: float, intercept of the regression line
TheilSen(y, n, lastBar) applies the Theil-Sen estimator (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
tsSlope :: float, slope of the regression line
tsInter :: float, intercept of the regression line
OrdinaryLeastSquares(y, n, lastBar) applies the ordinary least squares regression (non-robust) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
olsSlope :: float, slope of the regression line
olsInter :: float, intercept of the regression line
Model performance metrics:
metricRMSE(y, n, lastBar, slope, intercept) returns the Root-Mean-Square Error (RMSE) of the regression. The better the model, the lower the RMSE.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
rmse :: float, RMSE value
metricMAE(y, n, lastBar, slope, intercept) returns the Mean Absolute Error (MAE) of the regression. MAE is is similar to RMSE but is less sensitive to outliers. The better the model, the lower the MAE.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
mae :: float, MAE value
metricR2(y, n, lastBar, slope, intercept) returns the coefficient of determination (R squared) of the regression. The better the linear regression fits the data (compared to the sample mean), the closer the value of the R squared is to 1.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
Rsq :: float, R-sqared score
Usage example:
//@version=5
indicator('ExampleLinReg', overlay=true)
// import the library
import tbiktag/LinearRegressionLibrary/1 as linreg
// define the studied interval: last 100 bars
int Npoints = 100
int lastBar = bar_index
int firstBar = bar_index - Npoints
// apply repeated median regression to the closing price time series within the specified interval
{square bracket}slope, intercept{square bracket} = linreg.RepeatedMedian(close, Npoints, lastBar)
// calculate the root-mean-square error of the obtained linear fit
rmse = linreg.metricRMSE(close, Npoints, lastBar, slope, intercept)
// plot the line and print the RMSE value
float y1 = intercept
float y2 = intercept + slope * (Npoints - 1)
if barstate.islast
{indent} line.new(firstBar,y1, lastBar,y2)
{indent} label.new(lastBar,y2,text='RMSE = '+str.format("{0,number,#.#}", rmse))
Repeated Median Regression with Interactive Range SelectionGreetings to all!
As you probably know, TradingView now supports interactive inputs that can be directly set on a chart. I decided to build a tool that takes advantage of this incredible feature. This tool applies robust linear regression within a time interval on the chart that you can select interactively.
Method
The script uses an algorithm known as Repeated Median Regression . It belongs to the class of so-called robust regression methods. The reason they are called “robust” is that these methods are much less sensitive to outliers in the data than the ordinary least squares.
The calculation procedure is as follows: For each data point, this algorithm collects the slopes of the lines connecting that point to all other points in the sample, calculates the median slope, and then obtains the median value of these median slopes. Subsequently, it calculates the intercepts of the regression line and the mean absolute error (MAE) of the model.
Based on these results, a linear channel is plotted. The upper and lower channel boundaries are set by the MAE value multiplied by a user-defined coefficient.
Further reading
You can read more about robust linear regression on Wikipedia .
For more information on interactive inputs, see the User Manual's page .
Previous publication
I have already posted a script using the repeated median regression method. Although the core algorithm is essentially the same, interactive input provides fundamentally different functionality to the current script.
A word of caution
Currently, the interactive interval selection mode can be triggered only when the script is loaded to the chart. Thus, you might have to reload it when switching between different timeframes.
Mean AnglesThis indicator plots the trend of the angles made by the chosen means. This trend when analysed over multiple timeframes as well as different lengths can give an indication of the trend in short medium and long term.
For example, in any particular timeframe, when the 20 EMA turns a negative arctan, it signifies that on a shorter timeframe (than the current timeframe) is turning downwards in price. When 50, 100 and 200 EMA turn negative, it confirms the trend reversal. Similarly the 20 EMA will be the first one to turn "Up" or positive to indicate a possible trend reversal on the upside.
The angle of the means will oscillate between +pi/2 and -pi/2.
0 means - EMA is flat
+pi/2 means - almost vertical price rise
-pi/2 means - almost vertical price fall
Between -pi/2 and 0 means EMA is sloped downwards. Moving from -pi/2 to 0 means EMA slope is turning up. Moving from 0 to -pi/2 means EMA slope is falling down even lower and faster.
Between 0 and +pi/2 means EMA is slopped upwards. Moving from +pi/2 to 0 means EMA slope is falling down. Moving from 0 to +pi/2 means EMA slope is turning up even higher and faster.
Natural Market Slope [CC]The Natural Market Slope was created by Jim Sloman and this is one of his many Ocean Indicators which I'm publishing thanks to receiving source materials from @altcoinz and @tmac87. I did completely rewrite the formula for this indicator but I commented out the original calculation so you can compare or just for study purposes. I like this version better because it is very smooth and the original formula is a bit faster with response but is very choppy in comparison.
This indicator was the basis for his Natural Market Combo which I will be publishing very soon so stay tuned for that. The idea behind all of his Natural indicators was to use the natural log of the current price in different ways. This indicator obviously focuses on the slope and it essentially becomes another momentum indicator which peaks when the upward momentum is gone and vice versa. Buy when the line turns green and sell when it turns red. I have added strong buy and sell signals in addition to the normal ones and strong signals are darker in color in comparison to the original lighter colors.
Let me know if there are any other indicators you would like to see me publish!
Moving Average Slope AnalysisThis is a simple script which allows to do slope analysis on any kind of Moving Average. Simply change the moving average function that you wish to work with , in the script.
Slope analysis may be required for fine-tuning trade automation software , which uses Moving Average for determining optimum enter/exit point.
Read code comments for instructions!
Crypto momentum strategyThis strategy is based on LazyBear's Squeeze Momentum indicator. It analyzes when the trend in the momentum is shifting, locating the peaks and the valleys, and takes those as sell and buy signals respectively. This is a long strategy, so it also takes into consideration the 50 period Exponential Moving Average to identify upward trends. If the closing price of the candle is above the 50EMA, and the slope of the 50EMA is trending upwards, then the buy signal is executed. If these conditions are not met, the buy signal is ignored.
This strategy works well with crypto trading on the day/week charts.
It has a profit ratio of 4:1 on average, and roughly half of the trades are profitable.
DRSI DMA Scalping Strategy No RepaintThis strategy compares the slope of a Moving Average (of your choosing) to the slope of a Momentum Indicator (of your choosing). Zero is the center line because 0 slope means sideways movement. When both lines cross your buy threshold, it buys. When both lines cross your Sell threshold, it sells. The lines may look choppy, but that is probably because it is referencing a different timeframe than what the chart is set to. I left as many settings adjustable by the user as possible so you can tune this strategy to the relative behavior of whatever you are trading.
This also includes a No Repaint function so the backtest should be as close to live trading as possible.
Return (Percent Change)This Script displays Regular or Log Returns as either a line or histogram and labels the current bar.
If something other than price is selected as the source, the result is percent change with a positive or negative slope.
If a moving average of price is used as the source, the result is analogous to a strength index
Other options include a look-back period adjustment (the default is 1),
smoothing results by converting to an EMA, and
Bollinger Bands with Length and Standard Deviation inputs.
Linear Regression Channel / Curve / Slope by DGTTʜᴇ Lɪɴᴇᴀʀ Rᴇɢʀᴇꜱꜱɪᴏɴ Cʜᴀɴɴᴇʟꜱ
Linear Regression Channels are useful measure for technical and quantitative analysis in financial markets that help identifying trends and trend direction. The use of standard deviation gives traders ideas as to when prices are becoming overbought or oversold relative to the long term trend
The basis of a linear regression channel
Linear Regression Line – is a line drawn according to the least-squares statistical technique which produces a best-fit line that cuts through the middle of price action, a line that best fits all the data points of interest. The resulting fitted model can be used to summarize the data, to predict unobserved values from the same system. Linear Regression Line then present basis for the channel calculations
The linear regression channel
2. Upper Channel Line – A line that runs parallel to the Linear Regression Line and is usually one to two standard deviations above the Linear Regression Line.
3. Lower Channel Line – This line runs parallel to the Linear Regression Line and is usually one to two standard deviations below the Linear Regression Line.
Unlike Fibonacci Channels and Andrew’s Pitchfork, Linear Regression Channels are calculated using statistical methods, both for the regression line (as expressed above) and deviation channels. Upper and Lower channel lines are presenting the idea of bell curve method, also known as a normal distribution and are calculated using standard deviation function.
A standard deviation include 68% of the data points, two standard deviations include approximately 95% of the data points and any data point that appears outside two standard deviations is very rare.
It is often assumed that the data points will move back toward the average, or regress and channels would allow us to see when a security is overbought or oversold and ready to revert to the mean
please note : Over time, the price will move up and down, and the linear regression channel will experience changes as old prices fall off and new prices appear
█ Linear Regression Study Features
Linear Regression Channel
- Linear regression line as basis
- Customizable multiple channels based on Standard Deviation
- ALERTs for the channel levels
Linear Regression Curve
- Linear regression curve as basis
- Optional : Bands based on Standard Deviation or Volatility (ATR). Bands are applied with fixed levels 1, 2 and 3 times StdDev or ATR away from the curve
Linear Regression Slope
- Optional : Up/Down slope arrows for a used defined period
█ Volume / Volatility Add-Ons
High Volatile Bar Indication
Volume Spike Bar Indication
Volume Weighted Colored Bars
Moving Average Slope to determine market directionMoving Average Slope is a straightforward but also a handy indicator.
By inserting this moving average, it is possible to glance at the direction of the trend.
When the moving average has an increasing angle, it will turn green; vice versa, it will be colored red.
It is a trend indicator; I recommend leaving the period at 20 because it includes the last four trading weeks.
If you found this indicator useful, please like it
Repeated Median Regression ChannelThis script uses the Repeated Median (RM) estimator to construct a linear regression channel and thus offers an alternative to the available codes based on ordinary least squares.
The RM estimator is a robust linear regression algorithm. It was proposed by Siegel in 1982 (1) and has since found many applications in science and engineering for linear trend estimation and data filtering.
The key difference between RM and ordinary least squares methods is that the slope of the RM line is significantly less affected by data points that deviate strongly from the established trend. In statistics, these points are usually called outliers, while in the context of price data, they are associated with gaps, reversals, breaks from the trading range. Thus, robustness to outlier means that the nascent deviation from a predetermined trend will be more clearly seen in the RM regression compared to the least-squares estimate. For the same reason, the RM model is expected to better depict gaps and trend changes (2).
Input Description
Length : Determines the length of the regression line.
Channel Multiplier : Determines the channel width in units of root-mean-square deviation.
Show Channel : If switched off , only the (central) regression line is displayed.
Show Historical Broken Channel : If switched on , the channels that were broken in the past are displayed. Note that a certain historical broken channel is shown only when at least Length / 2 bars have passed since the last historical broken channel.
Print Slope : Displays the value of the current RM slope on the graph.
Method
Calculation of the RM regression line is done as follows (1,3):
For each sample point ( t (i), y (i)) with i = 1.. Length , the algorithm calculates the median of all the slopes of the lines connecting this point to the other Length -1 points.
The regression slope is defined as the median of the set of these median slopes.
The regression intercept is defined as the median of the set { y (i) – m * t (i)}.
Computational Time
The present implementation utilizes a brute-force algorithm for computing the RM-slope that takes O ( Length ^2) time. Therefore, the calculation of the historical broken channels might take a relatively long time (depending on the Length parameter). However, when the Show Historical Broken Channel option is off, only the real-time RM channel is calculated, and this is done quite fast.
References
1. A. F. Siegel (1982), Robust regression using repeated medians, Biometrika, 69 , 242–244.
2. P. L. Davies, R. Fried, and U. Gather (2004), Robust signal extraction for on-line monitoring data, Journal of Statistical Planning and Inference 122 , 65-78.
3. en.wikipedia.org
Cosmic VectorThis indicator will copy a moving average's plot and show whether its angle vector is negative or positive. In other words, it will show when the moving average starts to "accelerate" / "decelerate".
To use:
Add any moving average indicator to the chart
Click that indicator's More > Add Indicator on (MA)
Select the Cosmic Angle Gravity indicator
Smooth First Derivative IndicatorIntroducing the Smooth First Derivative indicator. For each time step, the script numerically differentiates the price data using prior datapoints from the look-back window. The resulting time derivative (the rate of price change over time) is presented as a centered oscillator.
A first derivative is a versatile tool used in functional data analysis. When applied to price data, it can be applied to analyze momentum, confirm trend direction, and identify pivot points.
Model Description:
The model assumes that, within the look-back window, price data can be well approximated by a smooth differentiable function. The first derivative can then be computed numerically using a noise-robust one-sided differentiator. The current version of the script employs smooth differentiators developed by P. Holoborodko (www.holoborodko.com). Note that the Indicator should not be confused with Constance Brown's Derivative Oscillator.
Input parameter:
The Bandwidth parameter sets the number of points in the moving look-back window and thus determines the smoothness of the first derivative curve. Note that a smoother Indicator shows a greater lag.
Interpretation:
When using this Indicator, one should recall that the first derivative can simply be interpreted as the slope of the curve:
- The maximum (minimum) in the Indicator corresponds to the point at which the market experiences the maximum upward (downward) slope, i.e., the inflection point. The steeper the slope, the greater the Indicator value.
- The positive-to-negative zero-crossing in the Indicator suggests that the market has formed a local maximum (potential start of a downtrend or a period of consolidation). Likewise, a zero-crossing from negative to positive is a potential bullish signal.
Linear Regression Slope HistogramThis is the slope of linear regression plotted as a histogram. It has a threshold for the slope in case there is a minimum slope amount that the user wants for it to show green or red. The color shows a dim and bright effect depending on the direction of the slope to better show its rise and fall. You can set the length of the slope in the input setting screen.
Some interesting things about linear regression slope that I found out: It kind of looks like the histogram of ADX or the directional movement lines depending on the length used for the slope. According to Tushar Chande, linear regression can be used as an alternative of finding trend direction, although it is hard to say what length to use for it, I haven't been able to figure out a good way to apply it yet. According to Bulkowski, linear regression of the volume can be used with certain chart patterns that he listed to increase their chance of success by taking trades where the linear regression line points towards, so if you use volume as a source on this indicator you can take trades in whatever said direction. Got any other ideas on how to use linear regression? Feel free to let me knows, would gladly appreciate it.
The TMA Slope - TMSlope Oscillator The TMA Slope oscillator is a simple slope of a Triangular Moving Average compared and normalized with the Average True Range of the last 100 periods (default setting).
This specific version add 2 triggers to give trading signals according to the slope:
- Above superior trigger, the trend is bullish, so trading is “Buy”
- Below inferior trigger, the trend is bearish, trading is “Sell”
- If the slope is included between these 2 levels, the market is probably ranging and no new orders should be initiated