LSMA Z-Score [BackQuant]LSMA Z-Score
Main Features and Use in the Trading Strategy
- The indicator normalizes the LSMA into a detrended Z-Score, creating an oscillator with standard deviation levels to indicate trend strength.
- Adaptive coloring highlights the rate of change and potential reversals, with different colors for positive and negative changes above and below the midline.
- Extreme levels with adaptive coloring indicate the probability of a reversion, providing strategic entry or exit points.
- Alert conditions for crossing the midline or significant shifts in trend direction enhance its utility within a trading strategy.
1. What is an LSMA?
The Least Squares Moving Average (LSMA) is a technical indicator that smoothens price data to help identify trends. It uses the least squares regression method to fit a straight line through the selected price points over a specified period. This approach minimizes the sum of the squares of the distances between the line and the price points, providing a more statistically grounded moving average that can adapt more smoothly to price changes.
2. What is a Z-Score?
A Z-Score is a statistical measurement that describes a value's relationship to the mean of a group of values, measured in terms of standard deviations from the mean. If a Z-Score is 0, it indicates that the data point's score is identical to the mean score. A Z-Score helps in understanding if a data point is typical for a given data set or if it is atypical. In finance, a Z-Score is often used to measure how far a piece of data is from the average of a set, which can be helpful in identifying outliers or unusual data points.
3. Why Turning LSMA into a Z-Score is Innovative and Its Benefits
Converting LSMA into a Z-Score is innovative because it combines the trend identification capabilities of the LSMA with the statistical significance testing of Z-Scores. This transformation normalizes the LSMA, creating a detrended oscillator that oscillates around a mean (zero line), with standard deviation levels to show trend strength. This method offers several benefits:
Enhanced Trend Detection:
- By normalizing the LSMA, traders can more easily identify when the price is deviating significantly from its trend, which can signal potential trading opportunities.
Standardization:
- The Z-Score transformation allows for comparisons across different assets or time frames, as the score is standardized.
Objective Measurement of Trend Strength:
- The use of standard deviation levels provides an objective measure of trend strength and volatility.
4. How It Can Be Used in the Context of a Trading System
This indicator can serve as a versatile tool within a trading system for a range of things:
Trend Confirmation:
- A positive Z-Score can confirm an uptrend, while a negative Z-Score can confirm a downtrend, providing traders with signals to enter or exit trades.
Oversold/Overbought Conditions:
- Extreme Z-Score levels can indicate overbought or oversold conditions, suggesting potential reversals or pullbacks.
Volatility Assessment:
- The standard deviation levels can help traders assess market volatility, with wider bands indicating higher volatility.
5. How It Can Be Used for Trend Following
For trend following strategies, this indicator can be particularly useful:
Trend Strength Indicator:
- By monitoring the Z-Score's distance from zero, traders can gauge the strength of the current trend, with larger absolute values indicating stronger trends.
Directional Bias:
- Positive Z-Scores can be used to establish a bullish bias, while negative Z-Scores can establish a bearish bias, guiding trend following entries and exits.
Color-Coding for Trend Changes :
- The adaptive coloring of the indicator based on the rate of change and extreme levels provides visual cues for potential trend reversals or continuations.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
This is using the Midline Crossover:
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Backtested
DEMA Adjusted Average True Range [BackQuant]The use of the Double Exponential Moving Average (DEMA) within your Adjusted Average True Range (ATR) calculation serves as a cornerstone for enhancing the indicator's responsiveness to market changes. To delve deeper into why DEMA is employed specifically in the context of your ATR calculation, let's explore the inherent qualities of DEMA and its impact on the ATR's performance.
DEMA and Its Advantages
As previously mentioned, DEMA was designed to offer a more responsive alternative to the traditional Exponential Moving Average (EMA). By giving more weight to recent price data, DEMA reduces the lag typically associated with moving averages. This reduction in lag is especially beneficial for short-term traders looking to capitalize on trend reversals and other market movements as swiftly as possible.
The calculation of DEMA involves the following steps:
Calculate EMA1: This is the Exponential Moving Average of the price.
Calculate EMA2: This is the Exponential Moving Average of EMA1, thus it is a smoothing of a smoothing, leading to a greater lag.
Formulate DEMA: The formula
EMA1 = EMA of price
EMA2 = EMA of EMA1
DEMA = (2 x EMA1) - EMA2
effectively doubles the weighting of the most recent data points by subtracting the lagged, double-smoothed EMA2 from twice the single-smoothed EMA1.
This process enhances the moving average's sensitivity to recent price movements, allowing the DEMA to adhere more closely to the price bars than either EMA1 or EMA2 alone.
Integration with ATR
In the context of your ATR calculation, the integration of DEMA plays a crucial role in defining the indicator's core functionality. Here's a detailed explanation of how DEMA affects the ATR calculation:
Initial Determination of DEMA : By applying the DEMA formula to the chosen source data (which can be adjusted to use Heikin Ashi candle close prices for an even smoother analysis), you set a foundation for a more reactive trend-following mechanism within the ATR framework.
Application to ATR Bands : The calculated DEMA serves as the central line from which the ATR bands are derived. The ATR value, multiplied by a user-defined factor, is added to and subtracted from the DEMA to form the upper and lower bands, respectively. This dynamic adjustment not only reflects the volatility based on the ATR but does so in a way that is closely aligned with the most recent price action, thanks to the utilization of DEMA.
Enhanced Signal Quality : The responsiveness of DEMA ensures that the ATR bands adjust more promptly to changes in market conditions. This quality is vital for traders who rely on the ATR bands to identify potential entry and exit points, trend reversals, or to assess market volatility.
By employing DEMA as the core component in calculating the Adjusted Average True Range, your indicator leverages DEMA's reduced lag and increased weight on recent data to provide a more timely and accurate measure of market volatility. This innovative approach enhances the utility of the ATR by making it not only a tool for assessing volatility but also a more reactive indicator for trend analysis and trading signal generation.
The main concept of combining these is to reduce lag, get a more robust signal and still capture clear trends over medium time horizons.
For me, this is best used in confluence with other indicators, it can be made faster in order to get fasters response time, or slower. This is all depending on the needs of you as a trader.
User Inputs:
The script offers several user-configurable inputs, such as the period lengths for DEMA and ATR calculations, the multiplication factor for the ATR, and options to use Heikin Ashi candles or standard price data. Additionally, it allows for the toggling of visual features, like the plotting of the DEMA ATR and its moving average, and the application of color-coded trends on price bars.
Additional Features:
Moving Average Confluence: Traders can opt to display a moving average of the DEMA ATR, choosing from various types (e.g., SMA, EMA, HMA). This feature provides a layer of confluence, aiding in the identification of trend direction and strength.
Trend Identification :
The script employs logical conditions to ascertain the trend direction based on the movement of the DEMA ATR. It assigns colors to represent bullish or bearish trends, which are reflected in the plotted lines and the coloring of price bars.
Alerts :
Customizable alert conditions for trend reversals enhance the utility of the indicator for active trading, notifying users of significant changes in trend direction.
1D Backtests
We include these backtests as a general proxy for how they work.
Please do your own calibrating to suit it to your own needs and backtest.
Past results don't = future results but they can help you understand how it functions.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Session candles & reversals / quantifytools— Overview
Like traditional candles, session based candles are a visualization of open, high, low and close values, but based on session time periods instead of typical timeframes such as daily or weekly. Session candles are formed by fetching price at session start (open), highest price during session (high), lowest price during session (low) and price at session end (close). On top of candles, session based moving average is formed and session reversals detected. Session reversals are also backtested, using win rate and magnitude metrics to better understand what to expect from session reversals and which ones have historically performed the best.
By default, following session time periods are used:
Session #1: London (08:00 - 17:00, UTC)
Session #2: New York (13:00 - 22:00, UTC)
Session #3: Sydney (21:00 - 06:00, UTC)
Session #4: Tokyo (00:00 - 09:00, UTC)
Session time periods can be changed via input menu.
— Reversals
Session reversals are patterns that show a rapid change in direction during session. These formations are more familiarly known as wicks or engulfing candles. Following criteria must be met to qualify as a session reversal:
Wick up:
Lower high, lower low, close >= 65% of session range (0% being the very low, 100% being the very high) and open >= 40% of session range.
Wick down:
Higher high, higher low, close <= 35% of session range and open <= 60% of session range.
Engulfing up:
Higher high, lower low, close >= 65% of session range.
Engulfing down:
Higher high, lower low, close <= 35% of session range.
Session reversals are always based on prior corresponding session , e.g. to qualify as a NY session engulfing up, NY session must have a higher high and lower low relative to prior NY session , not just any session that has taken place in between. Session reversals should be viewed the same way wicks/engulfing formations are viewed on traditional timeframe based candles. Essentially, wick reversals (light green/red labels) tell you most of the motion during session was reversed. Engulfing reversals (dark green/red labels) on the other hand tell you all of the motion was reversed and new direction set.
— Backtesting
Session reversals are backtested using win rate and magnitude metrics. A session reversal is considered successful when next corresponding session closes higher/lower than session reversal close . Win rate is formed by dividing successful session reversal count with total reversal count, e.g. 5 successful reversals up / 10 reversals up total = 50% win rate. Win rate tells us what are the odds (historically) of session reversal producing a clean supporting move that was persistent enough to close that way too.
When a session reversal is successful, its magnitude is measured using percentage increase/decrease from session reversal close to next corresponding session high/low . If NY session closes higher than prior NY session that was a reversal up, the percentage increase from prior session close (reversal close) to current session high is measured. If NY session closes lower than prior NY session that was a reversal down, the percentage decrease from prior session close to current session low is measured.
Average magnitude is formed by dividing all percentage increases/decreases with total reversal count, e.g. 10 total reversals up with 1% increase each -> 10% net increase from all reversals -> 10% total increase / 10 total reversals up = 1% average magnitude. Magnitude metric supports win rate by indicating the depth of successful session reversal moves.
To better understand the backtesting calculations and more importantly to verify their validity, backtesting visuals for each session can be plotted on the chart:
All backtesting results are shown in the backtesting panel on top right corner, with highest win rates and magnitude metrics for both reversals up and down marked separately. Note that past performance is not a guarantee of future performance and session reversals as they are should not be viewed as a complete strategy for long/short plays. Always make sure reversal count is sufficient to draw reliable conclusions of performance.
— Session moving average
Users can form a session based moving average with their preferred smoothing method (SMA , EMA , HMA , WMA , RMA) and length, as well as choose which sessions to include in the moving average. For example, a moving average based on New York and Tokyo sessions can be formed, leaving London and Sydney completely out of the calculation.
— Visuals
By default, script hides your candles/bars, although in the case of candles borders will still be visible. Switching to bars/line will make your regular chart visuals 100% hidden. This setting can be turned off via input menu. As some sessions overlap, each session candle can be separately offsetted forward, clearing the overlaps. Users can also choose which session candles to show/hide.
Session periods can be highlighted on the chart as a background color, applicable to only session candles that are activated. By default, session reversals are referred to as L (London), N (New York), S (Sydney) and T (Tokyo) in both reversal labels and backtesting table. By toggling on "Numerize sessions", these will be replaced with 1, 2, 3 and 4. This will be helpful when using a custom session that isn't any of the above.
Visual settings example:
Session candles are plotted in two formats, using boxes and lines as well as plotcandle() function. Session candles constructed using boxes and lines will be clear and much easier on the eyes, but will apply only to first 500 bars due to Tradingview related limitations. Rest of the session candles go back indefinitely, but won't be as clean:
All colors can be customized via input menu.
— Timeframe & session time period considerations
As a rule of thumb, session candles should be used on timeframes at or below 1H, as higher timeframes might not match with session period start/end, leading to incorrect plots. Using 1 hour timeframe will bring optimal results as greatest amount historical data is available without sacrificing accuracy of OHLC values. If you are using a custom session that is not based on hourly period (e.g. 08:00 - 15:00 vs. 08.00 - 15.15) make sure you are using a timeframe that allows correct plots.
Session time periods applied by default are rough estimates and might be out of bounds on some charts, like NYSE listed equities. This is rarely a problem on assets that have extensive trading hours, like futures or cryptocurrency. If a session is out of bounds (asset isn't traded during the set session time period) the script won't plot given session candle and its backtesting metrics will be NA. This can be fixed by changing the session time periods to match with given asset trading hours, although you will have to consider whether or not this defeats the purpose of having candles based on sessions.
— Practical guide
Whether based on traditional timeframes or sessions, reversals should always be considered as only one piece of evidence of price turning. Never react to them without considering other factors that might support the thesis, such as levels and multi-timeframe analysis. In short, same basic charting principles apply with session candles that apply with normal candles. Use discretion.
Example #1 : Focusing efforts on session reversals at distinct support/resistance levels
A reversal against a level holds more value than a reversal by itself, as you know it's a placement where liquidity can be expected. A reversal serves as a confirming reaction for this expectation.
Example #2 : Focusing efforts on highest performing reversals and avoiding poorly performing ones
As you have data backed evidence of session reversal performance, it makes sense to focus your efforts on the ones that perform best. If some session reversal is clearly performing poorly, you would want to avoid it, since there's nothing backing up its validity.
Example #3 : Reversal clusters
Two is better than one, three is better than two and so on. If there are rapid changes in direction within multiple sessions consecutively, there's heavier evidence of a dynamic shift in price. In such case, it makes sense to hold more confidence in price halting/turning.