Inflation CorrelationHeyo fellas,
In today’s dynamic economic landscape, understanding the relationship of market prices to other economical factors like inflation rate is crucial. The Inflation Correlation Indicator is designed to provide traders with a clear visualization of this relationship. By correlating average inflation rates from selected countries with market closing prices, this indicator offers a unique perspective on potential market movements influenced by inflationary trends.
Features:
Country Selection: Choose from the European Union (EU), Germany (DE), or the United States (US) to tailor the correlation analysis to your specific market interest.
Correlation Length Customization: Adjust the correlation length to refine the sensitivity of the indicator to recent inflation data.
Visual Clarity: The correlation histogram changes color based on the direction of the correlation, providing an intuitive understanding of the inflation correlation.
Whether you’re a fundamental analyst seeking to incorporate macroeconomic indicators into your strategy or a trader looking for an edge in inflation-sensitive markets, the Inflation Correlation Indicator is an indispensable tool in your TradingView arsenal.
Thanks for checking this out!
Best regards,
simwai
Statistical
Statistics • Chi Square • P-value • SignificanceThe Statistics • Chi Square • P-value • Significance publication aims to provide a tool for combining different conditions and checking whether the outcome is significant using the Chi-Square Test and P-value.
🔶 USAGE
The basic principle is to compare two or more groups and check the results of a query test, such as asking men and women whether they want to see a romantic or non-romantic movie.
–––––––––––––––––––––––––––––––––––––––––––––
| | ROMANTIC | NON-ROMANTIC | ⬅︎ MOVIE |
–––––––––––––––––––––––––––––––––––––––––––––
| MEN | 2 | 8 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
| WOMEN | 7 | 3 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
|⬆︎ SEX | 10 | 10 | 20 |
–––––––––––––––––––––––––––––––––––––––––––––
We calculate the Chi-Square Formula, which is:
Χ² = Σ ( (Observed Value − Expected Value)² / Expected Value )
In this publication, this is:
chiSquare = 0.
for i = 0 to rows -1
for j = 0 to colums -1
observedValue = aBin.get(i).aFloat.get(j)
expectedValue = math.max(1e-12, aBin.get(i).aFloat.get(colums) * aBin.get(rows).aFloat.get(j) / sumT) //Division by 0 protection
chiSquare += math.pow(observedValue - expectedValue, 2) / expectedValue
Together with the 'Degree of Freedom', which is (rows − 1) × (columns − 1) , the P-value can be calculated.
In this case it is P-value: 0.02462
A P-value lower than 0.05 is considered to be significant. Statistically, women tend to choose a romantic movie more, while men prefer a non-romantic one.
Users have the option to choose a P-value, calculated from a standard table or through a math.ucla.edu - Javascript-based function (see references below).
Note that the population (10 men + 10 women = 20) is small, something to consider.
Either way, this principle is applied in the script, where conditions can be chosen like rsi, close, high, ...
🔹 CONDITION
Conditions are added to the left column ('CONDITION')
For example, previous rsi values (rsi ) between 0-100, divided in separate groups
🔹 CLOSE
Then, the movement of the last close is evaluated
UP when close is higher then previous close (close )
DOWN when close is lower then previous close
EQUAL when close is equal then previous close
It is also possible to use only 2 columns by adding EQUAL to UP or DOWN
UP
DOWN/EQUAL
or
UP/EQUAL
DOWN
In other words, when previous rsi value was between 80 and 90, this resulted in:
19 times a current close higher than previous close
14 times a current close lower than previous close
0 times a current close equal than previous close
However, the P-value tells us it is not statistical significant.
NOTE: Always keep in mind that past behaviour gives no certainty about future behaviour.
A vertical line is drawn at the beginning of the chosen population (max 4990)
Here, the results seem significant.
🔹 GROUPS
It is important to ensure that the groups are formed correctly. All possibilities should be present, and conditions should only be part of 1 group.
In the example above, the two top situations are acceptable; close against close can only be higher, lower or equal.
The two examples at the bottom, however, are very poorly constructed.
Several conditions can be placed in more than 1 group, and some conditions are not integrated into a group. Even if the results are significant, they are useless because of the group formation.
A population count is added as an aid to spot errors in group formation.
In this example, there is a discrepancy between the population and total count due to the absence of a condition.
The results when rsi was between 5-25 are not included, resulting in unreliable results.
🔹 PRACTICAL EXAMPLES
In this example, we have specific groups where the condition only applies to that group.
For example, the condition rsi > 55 and rsi <= 65 isn't true in another group.
Also, every possible rsi value (0 - 100) is present in 1 of the groups.
rsi > 15 and rsi <= 25 28 times UP, 19 times DOWN and 2 times EQUAL. P-value: 0.01171
When looking in detail and examining the area 15-25 RSI, we see this:
The population is now not representative (only checking for RSI between 15-25; all other RSI values are not included), so we can ignore the P-value in this case. It is merely to check in detail. In this case, the RSI values 23 and 24 seem promising.
NOTE: We should check what the close price did without any condition.
If, for example, the close price had risen 100 times out of 100, this would make things very relative.
In this case (at least two conditions need to be present), we set 1 condition at 'always true' and another at 'always false' so we'll get only the close values without any condition:
Changing the population or the conditions will change the P-value.
In the following example, the outcome is evaluated when:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is lower/equal than the close value from 2 bars back
Or:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is equal than the close value from 2 bars back
close value from 1 bar back is lower than the close value from 2 bars back
In both examples, all possibilities of close against close are included in the calculations. close can only by higher, equal or lower than close
Both examples have the results without a condition included (5 = 5 and 5 < 5) so one can compare the direction of current close.
🔶 NOTES
• Always keep in mind that:
Past behaviour gives no certainty about future behaviour.
Everything depends on time, cycles, events, fundamentals, technicals, ...
• This test only works for categorical data (data in categories), such as Gender {Men, Women} or color {Red, Yellow, Green, Blue} etc., but not numerical data such as height or weight. One might argue that such tests shouldn't use rsi, close, ... values.
• Consider what you're measuring
For example rsi of the current bar will always lead to a close higher than the previous close, since this is inherent to the rsi calculations.
• Be careful; often, there are na -values at the beginning of the series, which are not included in the calculations!
• Always keep in mind considering what the close price did without any condition
• The numbers must be large enough. Each entry must be five or more. In other words, it is vital to make the 'population' large enough.
• The code can be developed further, for example, by splitting UP, DOWN in close UP 1-2%, close UP 2-3%, close UP 3-4%, ...
• rsi can be supplemented with stochRSI, MFI, sma, ema, ...
🔶 SETTINGS
🔹 Population
• Choose the population size; in other words, how many bars you want to go back to. If fewer bars are available than set, this will be automatically adjusted.
🔹 Inputs
At least two conditions need to be chosen.
• Users can add up to 11 conditions, where each condition can contain two different conditions.
🔹 RSI
• Length
🔹 Levels
• Set the used levels as desired.
🔹 Levels
• P-value: P-value retrieved using a standard table method or a function.
• Used function, derived from Chi-Square Distribution Function; JavaScript
LogGamma(Z) =>
S = 1
+ 76.18009173 / Z
- 86.50532033 / (Z+1)
+ 24.01409822 / (Z+2)
- 1.231739516 / (Z+3)
+ 0.00120858003 / (Z+4)
- 0.00000536382 / (Z+5)
(Z-.5) * math.log(Z+4.5) - (Z+4.5) + math.log(S * 2.50662827465)
Gcf(float X, A) => // Good for X > A +1
A0=0., B0=1., A1=1., B1=X, AOLD=0., N=0
while (math.abs((A1-AOLD)/A1) > .00001)
AOLD := A1
N += 1
A0 := A1+(N-A)*A0
B0 := B1+(N-A)*B0
A1 := X*A0+N*A1
B1 := X*B0+N*B1
A0 := A0/B1
B0 := B0/B1
A1 := A1/B1
B1 := 1
Prob = math.exp(A * math.log(X) - X - LogGamma(A)) * A1
1 - Prob
Gser(X, A) => // Good for X < A +1
T9 = 1. / A
G = T9
I = 1
while (T9 > G* 0.00001)
T9 := T9 * X / (A + I)
G := G + T9
I += 1
G *= math.exp(A * math.log(X) - X - LogGamma(A))
Gammacdf(x, a) =>
GI = 0.
if (x<=0)
GI := 0
else if (x
Chisqcdf = Gammacdf(Z/2, DF/2)
Chisqcdf := math.round(Chisqcdf * 100000) / 100000
pValue = 1 - Chisqcdf
🔶 REFERENCES
mathsisfun.com, Chi-Square Test
Chi-Square Distribution Function
Hedge Coin M - Statistical Support and ResistanceHedge Coin M - Statistical Support and Resistance
Introduction
"Hedge Coin M - Statistical Support and Resistance" is a sophisticated, statistically-driven indicator designed specifically for traders in the COIN-M market on Binance. It offers a nuanced approach to identifying key market levels, focusing on the dynamics of support and resistance through advanced volatility analysis.
Foundation and Credits:
This script is an advanced adaptation of TradingView's standard code for the Bollinger Bands indicator. It extends the foundational concept of Bollinger Bands by integrating additional volatility metrics.
Calculation Method
This indicator employs Volume Weighted Moving Averages (VWMA) to create two distinct sets of Bollinger Bands, named BB-a and BB-b.
BB-a is derived from the VWMA of high prices, targeting potential resistance levels.
BB-b is based on the VWMA of low prices, aimed at identifying critical support levels.
Users can independently adjust the standard deviation (SD) multipliers for the upper and lower bands of both BB-a and BB-b, accommodating different market conditions.
Enhanced Volatility Analysis
The indicator calculates additional standard deviation lines for the upper band of BB-a and the lower band of BB-b. These lines provide deeper insights into market volatility.
Plotted Graphs
The primary plots include the upper and lower bands of BB-a and BB-b, marked in distinct colors for clarity.
Additional SD lines are plotted to indicate potential extended levels of support and resistance, offering traders a broader view of possible market movements.
Purpose and Usage
"Hedge Coin M - Statistical Support and Resistance" is designed to provide traders with a consistent, statistical method for identifying significant price levels.
It aids in scaling entry into positions, helping traders to navigate the COIN-M market with more informed decision-making.
This tool is especially useful for traders who combine long-term holding with swing trading strategies, offering a balanced approach to market engagement.
Integration and Adaptation
Easily integrate this indicator into your TradingView chart for the COIN-M market.
Use the insights provided to complement your overall trading strategy, particularly in identifying and reacting to significant market movements.
Disclaimer
Important Note: This indicator is provided for informational purposes only. It does not constitute financial advice, investment advice, trading advice, or any other sort of advice. Trading decisions should be made based on your own analysis, prudence, and judgment. Please be aware of the risks involved in trading and consult a financial advisor if necessary.
Normalized Fisher Transformed VolumeGreetings Traders,
I am thrilled to introduce a game-changing tool that I've passionately developed to enhance your trading precision – the Normalized Fisher Transformed Volume indicator. Let's dive into the specifics and explore how this tool can empower you in the markets.
Unlocking Trading Precision:
Normalization and Transformation:
Normalize raw volume data to ensure a consistent scale for analysis.
The Fisher Transformation converts normalized volume data into a Gaussian distribution, providing enhanced insights into trend dynamics.
Flexible Modes for Tailored Strategies:
Choose from three distinct modes:
Volume T3 (MA) + Heatmap: Identify trends with T3 Moving Average and visualize volume strength with Heatmap.
Volume Percent Rank: Evaluate the position of current volume relative to historical data.
Volume T3 (MA) Percent Rank: Combine T3 Moving Average with percentile ranking for a comprehensive analysis.
Heatmap Visualization for Quick Insights:
Heatmap Zones and Lines visually represent volume strength relative to historical data.
Customize threshold multipliers and color options for precise Heatmap interpretation.
T3 Moving Average Integration:
Smoothed representation of volume trends with the T3 Moving Average enhances trend identification.
Percent Rank Analysis for Context:
Gauge the position of normalized volume within historical context using Percent Rank analysis.
User-Friendly Customization:
Easily adjust parameters such as length, T3 Moving Average length, Heatmap standard deviation length, and threshold multipliers.
Intuitive interface with colored bars and customizable background options for personalized analysis.
How to Use Effectively:
Mode Selection:
Identify your preferred trading strategy and select the mode that aligns with your approach.
Parameter Adjustment:
Fine-tune the indicator by adjusting parameters to match your preferred trading style.
Interpret Heatmap and T3 Analysis:
Leverage Heatmap and T3 Moving Average analysis to spot potential trend reversals, overbought/oversold conditions, and market sentiment shifts.
Conclusion:
The Normalized Fisher Transformed Volume indicator is not just a tool; it's your key to unlocking precision in trading. Crafted by Simwai, this indicator offers unique insights tailored to your specific trading needs. Dive in, explore its features, experiment with parameters, and let it guide you to more informed and precise trading decisions.
Trade wisely and prosper,
simwai
K's Reversal Indicator IIIK's Reversal Indicator III is based on the concept of autocorrelation of returns. The main theory is that extreme autocorrelation (trending) that coincide with a technical signals such as one from the RSI, may result in a powerful short-term signal that can be exploited.
The indicator is calculated as follows:
1. Calculate the price differential (returns) as the current price minus the previous price.
2. the correlation between the current return and the return from 14 periods ago using a lookback of 14 periods.
3. Calculate a 14-period RSI on the close prices.
To generate the signals, use the following rules:
* A bullish signal is generated whenever the correlation is above 0.60 while the RSI is below 40.
* A bearish signal is generated whenever the correlation is above 0.60 while the RSI is above 60.
Returns Model by TenozenHey there! I've been diving into the book "Paul Wilmott on Quantitative Finance," and I stumbled upon this cool model for calculating and modeling returns. Basically, it helps us figure out how much a price has changed over a set number of periods—I like to use 20 periods as a default. Once we get that rate of change value, we crunch some numbers to find the standard deviation and mean using all the historical data we have. That's the foundation of this model.
Now, let's talk about how to use it. This model shows us how returns and price behavior are connected. When returns hang out in the +1 to +2 standard deviation range, it usually means returns are about to drop, and vice versa. Often, this leads to corresponding price moves. But here's the thing: sometimes prices don't do what we expect. Why? It's because there's another hidden factor at play—I like to call it "power."
This "power" isn't something we can see directly, but it's there. Basically, when returns are within that standard deviation range, the market faces resistance when trying to move in its preferred direction, whether bullish or bearish. The strength of this "power" determines if the market will snap back to the average or go for a wild ride. It can show up as small price wiggles, big price jumps, or lightning-fast moves. By understanding this "power," we can get a better handle on what the market might do next and avoid getting blindsided. In the meantime, I couldn't explain "power" yet, but In the future, when I've learned enough, I'd love to share the model with you guys!
So... I'm planning to explore and share more models from this book as I learn, even if those pesky math formulas can be tough to crack. I hope you find this indicator as helpful as I do, and if you've got any suggestions or feedback, please feel free to share! Ciao!
Support & Resistance AI (K means/median) [ThinkLogicAI]█ OVERVIEW
K-means is a clustering algorithm commonly used in machine learning to group data points into distinct clusters based on their similarities. While K-means is not typically used directly for identifying support and resistance levels in financial markets, it can serve as a tool in a broader analysis approach.
Support and resistance levels are price levels in financial markets where the price tends to react or reverse. Support is a level where the price tends to stop falling and might start to rise, while resistance is a level where the price tends to stop rising and might start to fall. Traders and analysts often look for these levels as they can provide insights into potential price movements and trading opportunities.
█ BACKGROUND
The K-means algorithm has been around since the late 1950s, making it more than six decades old. The algorithm was introduced by Stuart Lloyd in his 1957 research paper "Least squares quantization in PCM" for telecommunications applications. However, it wasn't widely known or recognized until James MacQueen's 1967 paper "Some Methods for Classification and Analysis of Multivariate Observations," where he formalized the algorithm and referred to it as the "K-means" clustering method.
So, while K-means has been around for a considerable amount of time, it continues to be a widely used and influential algorithm in the fields of machine learning, data analysis, and pattern recognition due to its simplicity and effectiveness in clustering tasks.
█ COMPARE AND CONTRAST SUPPORT AND RESISTANCE METHODS
1) K-means Approach:
Cluster Formation: After applying the K-means algorithm to historical price change data and visualizing the resulting clusters, traders can identify distinct regions on the price chart where clusters are formed. Each cluster represents a group of similar price change patterns.
Cluster Analysis: Analyze the clusters to identify areas where clusters tend to form. These areas might correspond to regions of price behavior that repeat over time and could be indicative of support and resistance levels.
Potential Support and Resistance Levels: Based on the identified areas of cluster formation, traders can consider these regions as potential support and resistance levels. A cluster forming at a specific price level could suggest that this level has been historically significant, causing similar price behavior in the past.
Cluster Standard Deviation: In addition to looking at the means (centroids) of the clusters, traders can also calculate the standard deviation of price changes within each cluster. Standard deviation is a measure of the dispersion or volatility of data points around the mean. A higher standard deviation indicates greater price volatility within a cluster.
Low Standard Deviation: If a cluster has a low standard deviation, it suggests that prices within that cluster are relatively stable and less likely to exhibit sudden and large price movements. Traders might consider placing tighter stop-loss orders for trades within these clusters.
High Standard Deviation: Conversely, if a cluster has a high standard deviation, it indicates greater price volatility within that cluster. Traders might opt for wider stop-loss orders to allow for potential price fluctuations without getting stopped out prematurely.
Cluster Density: Each data point is assigned to a cluster so a cluster that is more dense will act more like gravity and
2) Traditional Approach:
Trendlines: Draw trendlines connecting significant highs or lows on a price chart to identify potential support and resistance levels.
Chart Patterns: Identify chart patterns like double tops, double bottoms, head and shoulders, and triangles that often indicate potential reversal points.
Moving Averages: Use moving averages to identify levels where the price might find support or resistance based on the average price over a specific period.
Psychological Levels: Identify round numbers or levels that traders often pay attention to, which can act as support and resistance.
Previous Highs and Lows: Identify significant previous price highs and lows that might act as support or resistance.
The key difference lies in the approach and the foundation of these methods. Traditional methods are based on well-established principles of technical analysis and market psychology, while the K-means approach involves clustering price behavior without necessarily incorporating market sentiment or specific price patterns.
It's important to note that while the K-means approach might provide an interesting way to analyze price data, it should be used cautiously and in conjunction with other traditional methods. Financial markets are influenced by a wide range of factors beyond just price behavior, and the effectiveness of any method for identifying support and resistance levels should be thoroughly tested and validated. Additionally, developments in trading strategies and analysis techniques could have occurred since my last update.
█ K MEANS ALGORITHM
The algorithm for K means is as follows:
Initialize cluster centers
assign data to clusters based on minimum distance
calculate cluster center by taking the average or median of the clusters
repeat steps 1-3 until cluster centers stop moving
█ LIMITATIONS OF K MEANS
There are 3 main limitations of this algorithm:
Sensitive to Initializations: K-means is sensitive to the initial placement of centroids. Different initializations can lead to different cluster assignments and final results.
Assumption of Equal Sizes and Variances: K-means assumes that clusters have roughly equal sizes and spherical shapes. This may not hold true for all types of data. It can struggle with identifying clusters with uneven densities, sizes, or shapes.
Impact of Outliers: K-means is sensitive to outliers, as a single outlier can significantly affect the position of cluster centroids. Outliers can lead to the creation of spurious clusters or distortion of the true cluster structure.
█ LIMITATIONS IN APPLICATION OF K MEANS IN TRADING
Trading data often exhibits characteristics that can pose challenges when applying indicators and analysis techniques. Here's how the limitations of outliers, varying scales, and unequal variance can impact the use of indicators in trading:
Outliers are data points that significantly deviate from the rest of the dataset. In trading, outliers can represent extreme price movements caused by rare events, news, or market anomalies. Outliers can have a significant impact on trading indicators and analyses:
Indicator Distortion: Outliers can skew the calculations of indicators, leading to misleading signals. For instance, a single extreme price spike could cause indicators like moving averages or RSI (Relative Strength Index) to give false signals.
Risk Management: Outliers can lead to overly aggressive trading decisions if not properly accounted for. Ignoring outliers might result in unexpected losses or missed opportunities to adjust trading strategies.
Different Scales: Trading data often includes multiple indicators with varying units and scales. For example, prices are typically in dollars, volume in units traded, and oscillators have their own scale. Mixing indicators with different scales can complicate analysis:
Normalization: Indicators on different scales need to be normalized or standardized to ensure they contribute equally to the analysis. Failure to do so can lead to one indicator dominating the analysis due to its larger magnitude.
Comparability: Without normalization, it's challenging to directly compare the significance of indicators. Some indicators might have a larger numerical range and could overshadow others.
Unequal Variance: Unequal variance in trading data refers to the fact that some indicators might exhibit higher volatility than others. This can impact the interpretation of signals and the performance of trading strategies:
Volatility Adjustment: When combining indicators with varying volatility, it's essential to adjust for their relative volatilities. Failure to do so might lead to overemphasizing or underestimating the importance of certain indicators in the trading strategy.
Risk Assessment: Unequal variance can impact risk assessment. Indicators with higher volatility might lead to riskier trading decisions if not properly taken into account.
█ APPLICATION OF THIS INDICATOR
This indicator can be used in 2 ways:
1) Make a directional trade:
If a trader thinks price will go higher or lower and price is within a cluster zone, The trader can take a position and place a stop on the 1 sd band around the cluster. As one can see below, the trader can go long the green arrow and place a stop on the one standard deviation mark for that cluster below it at the red arrow. using this we can calculate a risk to reward ratio.
Calculating risk to reward: targeting a risk reward ratio of 2:1, the trader could clearly make that given that the next resistance area above that in the orange cluster exceeds this risk reward ratio.
2) Take a reversal Trade:
We can use cluster centers (support and resistance levels) to go in the opposite direction that price is currently moving in hopes of price forming a pivot and reversing off this level.
Similar to the directional trade, we can use the standard deviation of the cluster to place a stop just in case we are wrong.
In this example below we can see that shorting on the red arrow and placing a stop at the one standard deviation above this cluster would give us a profitable trade with minimal risk.
Using the cluster density table in the upper right informs the trader just how dense the cluster is. Higher density clusters will give a higher likelihood of a pivot forming at these levels and price being rejected and switching direction with a larger move.
█ FEATURES & SETTINGS
General Settings:
Number of clusters: The user can select from 3 to five clusters. A good rule of thumb is that if you are trading intraday, less is more (Think 3 rather than 5). For daily 4 to 5 clusters is good.
Cluster Method: To get around the outlier limitation of k means clustering, The median was added. This gives the user the ability to choose either k means or k median clustering. K means is the preferred method if the user things there are no large outliers, and if there appears to be large outliers or it is assumed there are then K medians is preferred.
Bars back To train on: This will be the amount of bars to include in the clustering. This number is important so that the user includes bars that are recent but not so far back that they are out of the scope of where price can be. For example the last 2 years we have been in a range on the sp500 so 505 days in this setting would be more relevant than say looking back 5 years ago because price would have to move far to get there.
Show SD Bands: Select this to show the 1 standard deviation bands around the support and resistance level or unselect this to just show the support and resistance level by itself.
Features:
Besides the support and resistance levels and standard deviation bands, this indicator gives a table in the upper right hand corner to show the density of each cluster (support and resistance level) and is color coded to the cluster line on the chart. Higher density clusters mean price has been there previously more than lower density clusters and could mean a higher likelihood of a reversal when price reaches these areas.
█ WORKS CITED
Victor Sim, "Using K-means Clustering to Create Support and Resistance", 2020, towardsdatascience.com
Chris Piech, "K means", stanford.edu
█ ACKNOLWEDGMENTS
@jdehorty- Thanks for the publish template. It made organizing my thoughts and work alot easier.
Normal Distribution CurveThis Normal Distribution Curve is designed to overlay a simple normal distribution curve on top of any TradingView indicator. This curve represents a probability distribution for a given dataset and can be used to gain insights into the likelihood of various data levels occurring within a specified range, providing traders and investors with a clear visualization of the distribution of values within a specific dataset. With the only inputs being the variable source and plot colour, I think this is by far the simplest and most intuitive iteration of any statistical analysis based indicator I've seen here!
Traders can quickly assess how data clusters around the mean in a bell curve and easily see the percentile frequency of the data; or perhaps with both and upper and lower peaks identify likely periods of upcoming volatility or mean reversion. Facilitating the identification of outliers was my main purpose when creating this tool, I believed fixed values for upper/lower bounds within most indicators are too static and do not dynamically fit the vastly different movements of all assets and timeframes - and being able to easily understand the spread of information simplifies the process of identifying key regions to take action.
The curve's tails, representing the extreme percentiles, can help identify outliers and potential areas of price reversal or trend acceleration. For example using the RSI which typically has static levels of 70 and 30, which will be breached considerably more on a less liquid or more volatile asset and therefore reduce the actionable effectiveness of the indicator, likewise for an asset with little to no directional volatility failing to ever reach this overbought/oversold areas. It makes considerably more sense to look for the top/bottom 5% or 10% levels of outlying data which are automatically calculated with this indicator, and may be a noticeable distance from the 70 and 30 values, as regions to be observing for your investing.
This normal distribution curve employs percentile linear interpolation to calculate the distribution. This interpolation technique considers the nearest data points and calculates the price values between them. This process ensures a smooth curve that accurately represents the probability distribution, even for percentiles not directly present in the original dataset; and applicable to any asset regardless of timeframe. The lookback period is set to a value of 5000 which should ensure ample data is taken into calculation and consideration without surpassing any TradingView constraints and limitations, for datasets smaller than this the indicator will adjust the length to just include all data. The labels providing the percentile and average levels can also be removed in the style tab if preferred.
Additionally, as an unplanned benefit is its applicability to the underlying price data as well as any derived indicators. Turning it into something comparable to a volume profile indicator but based on the time an assets price was within a specific range as opposed to the volume. This can therefore be used as a tool for identifying potential support and resistance zones, as well as areas that mark market inefficiencies as price rapidly accelerated through. This may then give a cleaner outlook as it eliminates the potential drawbacks of volume based profiles that maybe don't collate all exchange data or are misrepresented due to large unforeseen increases/decreases underlying capital inflows/outflows.
Thanks to @ALifeToMake, @Bjorgum, vgladkov on stackoverflow (and possibly some chatGPT!) for all the assistance in bringing this indicator to life. I really hope every user can find some use from this and help bring a unique and data driven perspective to their decision making. And make sure to please share any original implementaions of this tool too! If you've managed to apply this to the average price change once you've entered your position to better manage your trade management, or maybe overlaying on an implied volatility indicator to identify potential options arbitrage opportunities; let me know! And of course if anyone has any issues, questions, queries or requests please feel free to reach out! Thanks and enjoy.
Price Legs: Average Heights; 'Smart ATR'Price Legs: Average Heights; 'Smart ATR'. Consol Range Gauge
~~ Indicator to show small and large price legs (based on short and long input pivot lengths), and calculating the average heights of these price legs; counting legs from user-input start time ~~
//Premise: Wanted to use this as something like a 'Smart ATR': where the average/typical range of a distinct & dynamic price leg could be calculated based on a user-input time interval (as opposed to standard ATR, which is simply the average range over a consistent repeating period, with no regard to market structure). My instinct is that this would be most useful for consolidated periods & range trading: giving the trader an idea of what the typical size of a price leg might be in the current market state (hence in the title, Consol Range gauge)
//Features & User inputs:
-Start time: confirm input when loading indicator by clicking on the chart. Then drag the vertical line to change start time easily.
-Large Legs (toggle on/off) and user-input pivot lookback/lookforward length (larger => larger legs)
-Small Legs (toggle on/off) and user-input pivot lookback/lookforward length (smaller => smaller legs)
-Display Stats table: toggle on/off: simple view- shows the averages of large (up & down), small (up & down), and combined (for each).
-Extended stats table: toggle on/off option to show the averages of the last 3 legs of each category (up/down/large/small/combined)
-Toggle on/off Time & Price chart text labels of price legs (time in mins/hours/days; price in $ or pips; auto assigned based on asset)
-Table position: user choice.
//Notes & tips:
-Using custom start time along with replay mode, you can select any arbitrary chunk of price for the purpose of backtesting.
-Play around with the pivot lookback lengths to find price legs most suitable to the current market regime (consolidating/trending; high volatility/ low volatility)
-Single bar price legs will never be counted: they must be at least 2 bars from H>>L or L>>H.
//Credits: Thanks to @crypto_juju for the idea of applying statistics to this simple price leg indicator.
Simple View: showing only the full averages (counting from Start time):
View showing ONLY the large legs, with Time & Price labels toggled ON:
Ratio To Average - The Quant ScienceRatio To Average - The Quant Science is a quantitative indicator that calculates the percentage ratio of the market price in relation to a reference average. The indicator allows the calculation of the ratio using four different types of averages: SMA, EMA, WMA, and HMA. The ratio is represented by a series of histograms that highlight periods when the ratio is positive (in green) and periods when the ratio is negative (in red).
What is the Ratio to Average?
The Ratio to Average is a measure that tracks the price movements with one of its averages, calculating how much the price is above or below its own average, in percentage terms.
USER INTERFACE
Lenght: it adjusts the number of bars to include in the calculation of the average.
Moving Average: it allows you to choose the type of average to use.
Color Up/Color Down : it allows you to choose the color of the indicator for positive and negative ratios.
Source CorrelationIn this small indicator I make it possible for the user to set two different input sources. Then, the indicator displays the correlation of these two input sources. It's a very small script, but I think it could be helpful to somebody to find uncorrelated indicators for his trading strategy. To use uncorrelated indicators is in general recommended.
Enjoy this small, but powerful tool. 🧙♂️
Murder Algo Stats: last portion of Indices closing hour (S&P)Stats regarding the 'murder algo' (last 10mins of the closing hour). Works on all sub-1hr timeframes. Best used on 5min, 10min 15min timeframe. Ideal use on 10min timeframe.
Can be applied to other user input sessions also
What i'm calling the 'Murder Algo' is the tendency of dynamic lower time frame price action in the final 10minutes of the S&P closing hour (or any of the three major US indices: S&P, Nasdaq, Dow).
If there are un-met liquidity targets (i.e. clean highs or lows) as we come into the last portion of the closing hour, price has a tendency to stretch up or down to reach these targets, swiftly.
These statisitics are somewhat experimental/research; trying to quantify this tendency. Please comment below if you think of some additions / modifications that may prove useful.
//Purpose:
-To get statistics of the tendency to 'reach' of the final bar (10minute bar in the above) of the closing hour in Indices (3pm - 4pm NY time).
-Specifically to see how often price reaches for HH or LL in the final bar of the closing hour (most of the time); and to see how far it reaches one way when it does (Mean, median, mode).
//Notes:
-Two sets of historical stats; one is based on the 'solo reach' of the last bar; the other is based on the reach of the last bar from the average price of the preceding bars of the session (purple line in the above)
-Works on any timeframe below hourly. Ideally used on 10min timeframe, but may be interesting to plot on 15min or 5min timeframe also.
-Should also work on custom user-defined session; though this indicator was explicly designed to investigate the 'murder algo': that final rush and/or whipsaw tendency of price in the last few minutes of Regular trading on Indices.
-For S&P, best used on SPX, which gives the longest history of all the S&P variants due to only showing Regular trading hours bars (500 days of history on 10min timeframe, for premium users)
-For most stats, i've rounded to ES1! mintick (i.e. rounded to nearest quarter dollar) =>> This allows more meaningful values for 'mode' statistical measure.
-I trade S&P; but this 'muder algo' phenomenon also obviously presents in Nasdaq and Dow.
//User Inputs:
-Session time input (defaults to closing hour 3pm - 4pm NY time)
-Average method (for the average of all the input session EXCEPT the final bar)
-Toggle on/off Average line.
-other formatting options: text color, table position, line color/style/size.
Example usage with annotations on SPX 500 chart 15m timeframe; using closing hour (3pm-4pm NY time) as our session:
Futures/Spot Ratiowhat is Futures /Spot Ratio?
Although futures and spot markets are separate markets, they are correlated. arbitrage bots allow this gap to be closed. But arbitrage bots also have their limits. so there are always slight differences between futures and spot markets. By analyzing these differences, the movements of the players in the market can be interpreted and important information about the price can be obtained. Futures /Spot Ratio is a tool that facilitates this analysis.
what it does?
it compresses the ratio between two selected spot and futures trading pairs between 0 and 100. its purpose is to facilitate use and interpretation. it also passes a regression (Colorful Regression) through the middle of the data for the same purpose.
about Colorful Regression:
how it does it?
it uses this formula:
how to use it?
use it to understand whether the market is priced with spot trades or leveraged positions. A value of 50 is the breakeven point where the ratio of the spot and leveraged markets are equal. Values above 50 indicate excess of long positions in the market, values below 50 indicate excess of short positions. I have explained how to interpret these ratios with examples below.
Multi-Asset Month/Month % change 10yr Averages10 Year Averages of Month-on-Month % change: Shows current asset, and 3x user input assets
-For comparing seasonal tendencies among different assets.
-Choose from a variety of monthly average measures as source: sma(close, length), sma(ohlc4, length); as well as sma's of vwap, vwma, volume, volatility. (sma = simple moving average).
-Averages based on month cf previous month: i.e. Feb % = Feb compared to Jan; Jan % = Jan compared to prev year's Dec. Average of the last 10yrs of these values is the printed value.
-Plot on current year (2023), or previous year (2022). If Plotting on current year, and a month of year has not yet occured, a 9yr average will be printed.
/// notes ///
-daily bars in month is a global setting; so choose assets which have similar trading days per month. i.e. Crypto: length = 30 (days per month); Stocks/FX/Indices: length = 21 (days per month).
-only plots on Daily timeframe.
10yr Avgs; Plotting with Year = 2022; using sma(close, 21) as source for average M/M change
Time of Day - Volatility Report█ OVERVIEW
The indicator analyses the volatility and reports statistics by the time of day.
█ CONCEPTS
Around the world and at various times, different market participants get involved in the markets. How does this affect the market?
Knowing this gets you better prepared and improves your trading. Here are some ideas to explore:
When is the market busy and quiet?
What time is it the most volatile?
Which pairs in your watchlist are moving while you are actively trading?
Should you adjust your trading time? Should you change your trading pairs?
When does your strategy perform the best?
What entry times do your winners have in common? What about the exit times of your losers?
Is it worth keeping your trade open overnight?
Bitcoin (UTC+0)
Gold (UTC+0)
Tesla, Inc. (UTC+0)
█ FEATURES
Selectable time zones
Display the statistics in your geographical time zone (or other market participants), the exchange time zone, or UTC+0.
Configurable outputs
Output the report statistics as mean or median.
█ HOW TO USE
Plot the indicator and visit the 1H timeframe.
█ NOTES
Gaps
The indicator includes the volatility from gaps.
Calculation
The statistics are not reported from absolute prices (does not favor trending markets) nor percentage prices (does not depict the different periods of volatility that markets can go through). Instead, the script uses the prices relative to the average range of previous days (daily ATR).
Extended trading session
The script analyses extended hours when activated on the chart.
Daylight Saving Time (DST)
The exchange time or geographical time zone selected may observe Daylight Saving Time. For example, NASDAQ:TSLA always opens at 9:30 AM New York time but may see different opening times in another part of the globe (New York time corresponds to UTC-4 and UTC-5 during the year).
Profitable Supertrend v0.1 - AlphaThis a script to try detect the best combination of supertrend parameters in a space of time. Sadly the script is slow. Evaluate all possibilities params is hard for a pinescript and my knowledge too. In some cases, when you want evaluate many time could be the script fails for timeout. Perhaps with time I could enhance. For this problem of speed the calculate of combinatios it's not complete: In factor use a increment of 0.2 in each param (0.1, 0.3, 0.5 ...) in period the increment for each value is 3. The range for factor it's from 3.0 to 12.0. The range of period it's from 10 to 43
My knowledge don't let me go more far. Perhaps with time I can enhance the script.
Compound strategyIn this strategy, I looked at how to manage the crypto I bought. Once we have a little understanding of how cryptocurrency is valued, we can manage the coins we have. For example, the most valuable coin in a coin is to sell when it is overvalued and re-buy when it is undervalued. Furthermore, I realised that buying from the right place and selling at the right time is very important to make a good profit. When it says sell, it's divided into several parts.
1. When the major uptrend is over and we are able to make the desired profit, we will sell our holdings outright.
2. Selling in the middle of a down trend and buying less than that amount again
3. When a small uptrend is over, sell the ones you bought at a lower price and make a small profit.
The other important thing is that the average cost is gradually reduced. Also, those who sell at a loss will reduce their profit (winning rate), so knowing that we will have a chance to calculate our loss and recover it. I used this to write a strategy in Trading View. I have put the link below it. From that we can see how this idea works. What I did was I made the signal by taking some technical indicators as I did in the previous one (all the indicators I got in this case were directional indicators, then I was able to get a good correlation and a standard deviation. I multiplied the correlation and the standard deviation by both and I took the signal as the time when the graph went through zero, and I connected it to the volume so that I could see some of the volume supported by it.)
Now let me tell you a little bit about what I see in this strategy. In this I used the compound effect. That is, the strategy, the profit he takes to reinvest. On the other hand, the strategy itself can put a separate stop loss value on each trade and avoid any major loss from that trade. I also added to this strategy the ability to do swing trading. That means we can take the small profits that come with going on a big up trend or a big down trend. Combined with Compound Effect, Stop Loss and Swing Trading, I was able to make a profit of 894% per annum (1,117.62% for 15 months) with a winning rate of 80%. Winning rate dropped to 80% because I added stop loss and swing trading. The other thing is that I applied DCA to this in both the up trend and the down trend (both). That was another reason for me to make a good profit. The orange line shows how to reduction of costly trade. The yellow line shows the profit and you can see that the profit line does not go down during the loss trades. That's because I want to absorb the loss from that trade.
Combo Backtest 123 Reversal & Statistical Volatility This is combo strategies for get a cumulative signal.
First strategy
This System was created from the Book "How I Tripled My Money In The
Futures Market" by Ulf Jensen, Page 183. This is reverse type of strategies.
The strategy buys at market, if close price is higher than the previous close
during 2 days and the meaning of 9-days Stochastic Slow Oscillator is lower than 50.
The strategy sells at market, if close price is lower than the previous close price
during 2 days and the meaning of 9-days Stochastic Fast Oscillator is higher than 50.
Second strategy
This indicator used to calculate the statistical volatility, sometime
called historical volatility, based on the Extreme Value Method.
Please use this link to get more information about Volatility.
WARNING:
- For purpose educate only
- This script to change bars colors.
Pattern Recognition Probabilities [racer8]Brief 🌟
Pattern Recognition Probabilities (PRP) is a REALLY smart indicator. It uses the correlation coefficient formula to determine if the current set of bars resembles that of past patterns. It counts the number of times the current pattern has occurred in the past and looks at how it performed historically to determine the probability of an up move, down move, or neutral move.
I'd like to say, I'm proud of this indicator 😆🤙 This is the SMARTEST indicator I have ever made 🧠🧠🧠
Note: PRP doesn't give you actual probabilities, but gives you instead the historical occurrences of up, down, and neutral moves that resulted after the pattern. So you can calculate probabilities based on these valuable statistics. So for example, PRP can tell you this pattern has historically resulted in 55 up moves, 20 down moves, and 60 neutral moves.
Parameters 🌟
You can adjust the Pattern length, Minimum correlation, Statistics lookback, Exit after time, and Atr multiplier parameters.
Pattern length - determines how long the pattern is
Minimum correlation - determines the minimum correlation coefficient needed to pass as a similiar enough pattern.
Statistics lookback - lookback period for gathering all the patterns in the past.
Exit after time - determines when exit occurred (number of periods after pattern) ; is the point that represents the pattern's result.
Atr multiplier - determines minimum atr move needed to qualify whether result was an up/down move or a neutral move. If a particular historical pattern resulted in a move that was less than the min atr, then it is recorded as a neutral move in the statistics.
Thanks for reading! 🙏
Good luck 🍀 Stay safe 😷 Drink lots of water💧
Enjoy! 🥳 and Hit the like button! 👍
Daily GAP StatsI did not write the script from scratch but rather started editing code of an existing one. The original code came from a script called GAP DETECTOR by @Asch-
First up: I am a trader, not a programmer and therefore my code most likely is inefficient. If someone with more expertise would like to help and optimize it - feel free to get in touch, I am always happy to learn some new tricks. :)
This script does 2 things:
- It shows daily gaps stats based on user inputs
- It shows color coded labels on gap days with additional information in tooltips ( important: make sure to read 'known issues/limitations' at the end )
User Inputs
==========
Although the input dialog is pretty straight forward, I do a quick rundown:
- Length: max lookback time
- Gap Direction: self explanatory
- Show All Gaps | Cont Only | Reversal Only | Off:
This refers to the way labels are displayed on gap days (again: make sure to read known issues/limitations!)
- Show All Gaps: does what it says
- Cont Only: only shows gaps where price continued in the gap direction. If you filter for gap ups and chose 'Cont only' you will only see labels on gap days where price closed above the open (and vice versa if you scan for gap downs).
- Reversal Only: you will only see labels for closes below the open on gap up days (and the opposite on gap down days)
- Off: self explanatory
- Gap Measure in ATR/PCT: self explanatory, ATR is calculated over a 10d period
- Gap Size (Abs Values): no negative values allowed here. If you filter for gap downs and enter 3 it means it will show gaps where the stock fell more than 3 ATR/PCT on the open.
- RVOL Factor: along with significant gaps should come significant volume. RVOL = volume of the gap day / 20d average volume
- Viewing Options: Placing the stats label in the window is a bit tricky (see knonw issues/limitations) and I was not sure which way I liked better. See for yourself what works best for you.
Known Isusses/Limitations:
=======================
- Positioning of the stats table:
As to my knowledge, Tradingview only allows label positioning relative to price and not relative to the chart window. I tried to always display the gap stats table in the upper right corner, using 52wk high as y-coordinate. This works ok most of the time, but is not pretty. If anybody has some fancy way to tag the label in a fixed position, please get in touch.
- Max number of labels per script:
TradingView has a limitation that allows a maxium of ~50 labels per script. If there are more labels, TradingView will automatically cut the oldest ones, without any notification. I have found this behaviour to be rather inconsistent - sometimes it'll dump labels even if there are a lot fewer than 50. Hopefully TradingView will drop this limitation at one point in the future.
Important: The inconsistent display of the gap day labels has NO INFLUENCE on the calculations in the gap stats table - the count and the calculations are complete and correct!
Alpha Performance of PeriodAlpha Performance of Period (PoP) produces a visualization of returns (gains and losses) over a quarterly, monthly, or annual period. It also displays the total % gain and loss over any length of days, months, and years as defined by the user.
Performance of Period (PoP) can be used to understand the performance of an asset over multiple periods using a single chart layout, and to compare the performance of different assets by using a multi-chart layout.
This can, for example, be used to compare the NASDAQ, S&P, and DJI over the past 20 years to create a dow vs. nasdaq vs. s&p performance chart. This can help you understand a comparison of historical returns by showing which performs the best month-over-month, quarter-to-quarter, year-to-year, throughout any custom period of days/months/years.
The ability to get a visualization of the % gain/loss can help to better understand how markets have performed over time and which markets have historically performed the best.
Check out the up and coming Educational Idea we will be releasing soon after this is live to see an example of how we use this tool.
Current Period Label
-----
Current Period : This label shows the current period's performance only when you hover over it.
(This label is located to the left of the current period's open candle and at the current candles close price)
TICKER "Time Period" Performance Label
-----
Total Period Gain : The total of all % gain periods from the start to end date.
Largest Period Gain : The biggest % gain period from the start to end date.
Total Period Loss : The total of all % loss periods from the start to end date.
Largest Period Loss : The biggest % loss period from the start to end date.
Total period Performance : The total % performance, the difference between the total gain and total loss.
NOTE : The "Current Period" performance is excluded from ALL five of the above-mentioned figures. This was done to avoid giving inaccurate comparison figures due to the period not being finished yet.
Inputs
-----
Current Script Version + Info : A drop-down list of instructions for the user to refer to.
Dark Mode Labels : Toggle on for Dark Mode. This is done since Labels text and background color can not be adjusted separately within the visual inputs so this is the best fit solution.
Time Period of Returns : Pick the period of performance you would like to emulate monthly/quarterly/annual.
Start Date : The day to start tracking performance.
Start Month : The month to start tracking performance.
Start Year : The year to start tracking performance.
End Date : The day to stop tracking performance.
End Month : The month to stop tracking performance.
End Year : The year to stop tracking performance.
As always if you have any feedback let us know in the comments and leave a like if you enjoy this tool :)
Layering PlotsLets say you want to layer into a position and you'd like to see it turn around. The study lets you set a baseline and increments above and below that baseline. A green cross is plotted ever time the price crosses above one of the increments, and red when crossing below that increment.
In the example I set the baseline to $22.1, and Layer increments to $0.50. So it will plot a cross every 50 cents above and below the baseline. This can be used on any chart period (daily, hourly, 5min...), but is limited to 9 layers above and below the baseline.
NOTES...
Lime = when price crosses above a layer that is above the baseline
Green = when price crosses above a layer below the baseline
Pink = when price crosses below a layer that is above the baseline
Red = when price crosses below a layer below the baseline
IMPORTANT...
This does not plot sometimes. I'm using a crossover crossunder function, and if a candle gaps open below and ends above a layer, this will not plot. It is not in error, just the way that function works. I will be looking to improve this study, wanted to share what I have for now.
Multi-Timeframe VWAPShows the Daily, Weekly, Monthly, Quarterly, and Yearly VWAP.
Also shows the previous closing VWAP, which is usually very near the HLC3 standard pivot for the previous time frame. i.e. The previous daily VWAP closing price is usually near the current Daily Pivot. Tickers interact well with the previous Daily and Weekly closing VWAP.
Enabling the STDEV bands shows 3 separate standard deviation levels, defaulted at 1, 2, and 3. The lookback period for the bands is always changing with each new bar, since the standard deviation is calculated from the current bar to the beginning of the period. This is different from bollinger bands, as the lookback is constant (usually 20 periods is the textbook default).
The STDEV bands interval of interest can be changed from Day (D), Week (W), Month (M), Quarter (Q), Year (Y).
Tickers tend to bounce very well on Daily, Weekly, and Yearly VWAP (Yes... Year). Use this code and observe the Year VWAP on several major symbols through the past few years and eyes will be opened.