Regression Candle Conversion IndicatorHey everyone!
I got a pseudo-request a while ago for something like this, essentially the ability to track where another ticker would fall based on an alternative ticker.
I did create my ticker correlation reference indicator which directly looks at the correlation between 2 tickers. However, this is an indicator that operates on the same principle but is more pragmatic for trading.
What does it do?
Well, in keeping with the theme of what I call my indicators, this has a title that explains exactly what it does, "Regression Candle Conversion Indicator" or "RCCI" for short. It uses simple regression to convert one ticker to another. So while you are tracking one indicator, you can see where the expected value should fall on the other.
Applications?
The big application of this for me is being able to track where SPY/QQQ or IWM is falling during overnight trading sessions. Extended trading hours close at 8 pm NYSE time. After that, you have to guess where futures prices will put the ETF version of it. This indicator will allow you to track where, theoretically, the underlying ETF ticker will fall based on the current trading behaviour.
Some other applications are just the ability to track how similar or dissimilar one stock is to the other. For example, if we wanted to trade, say, Boeing using shares of DFEN or ITA (a defence specific ETF), here is what we get:
In the chart above we can see BA as the primary chart and ITA as the RCCI converted chart. We will see 2 major things that should cause us concern.
First, there is a really poor correlation between the two tickers. This indicates that ITA may not produce the best exposure if I am directly looking for Boeing exposure.
Second, there is a wide standard error. this means that the results that the RCCI is providing may be skewed up to +/- 2 points (as indicated by the standard error chart).
Let's take a look at BA and DFEN:
In the above, we can see that the correlation is not great, but the standard error is quite low.
This means that, while this may not be the best ticker for Boeing exposure, the RCCI is able to confidently calculate the ticker within +/- 0.50 cents based on BA's underlying data.
However, its important to note that it is not advisable to really rely on these results if the correlation is less than + 0.5 or greater than -0.5.
Let's take a look at a few more examples:
Above we have BA (NYSE) vs BA (NEO TSX CAD Hedged). We can see the strong relationship and high confidence calculations.
And some others:
SPX (primary) and ES1! (secondary):
RTY and IWM:
ES1! and SPY:
Customizations:
As you can see above, it is pretty straight forward. There are 3 options:
Lookback Length: Determines the length of assessment for correlation and the regression assessment.
Manual Ticker Input: The indicator will pull the data from your current chart and compare it against a manually selected indicator. You must tell the indicator which ticker you are comparing against.
Data Table: This will show you the data table which contains the standard error assessment and the correlation assessment. These are determined by your lookback length. The lookback length is defaulted to 500.
And that's the indicator! It's pretty straight forward. Hopefully you find it helpful, especially if you track futures during overnight sessions.
Leave your comments/questions and feedback below.
Thanks for checking it out!
Statistics
Risk ManagementLibrary "RiskManagement"
This library keeps your money in check, and is used for testing and later on webhook-applications too. It has four volatility functions and two of them can be used to calculate a Stop-Loss, like Average True Range. It also can calculate Position Size, and the Risk Reward Ratio. But those calculations don't take leverage into account.
position_size(portfolio, risk, entry, stop_loss, use_leverage, qty_as_integer)
This function calculates the definite amount of contracts/shares/units you should use to buy or sell. This value can used by `strategy.entry(qty)` for example.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. Possible values are between 0.1 and 100%. Same usecase with strategy(default_qty_type=strategy.percent_of_equity,default_qty_value=100), except its calculation the risk only.
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
use_leverage (bool) : This value is optional. When not used or when set to false then this function will let you invest your portfolio at max.
qty_as_integer (bool) : This value is optional. When set to true this function will return a value used with integers. The largest integer less than or equal to the given number. Because some Broker/Exchanges let you trade hole contracts/shares/units only.
Returns: float
position_size_currency(portfolio, risk, entry, stop_loss)
This function calculates the definite amount of currency you should use when going long or short.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. For example: 1 is 100% and 0,01 is 1%. Default amount is 0.02 (2%).
entry (float) : This is the limit-/market-price for the current investment. In other words: The price per contract/share/units you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
Returns: float
rrr(entry, stop_loss, take_profit)
This function calculates the Risk Reward Ratio. Common values are between 1.5 and 2.0 and you should not go lower except for very few special cases.
Parameters:
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
take_profit (float) : This is the limit-/market-price when to take profits.
Returns: float
change_in_price(length)
This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
maximum_price_fluctuation(length)
This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
absolute_price_changes(length)
This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
annualized_volatility(length)
This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
Total ReturnThis script calculates a Total Return index for stocks that shows the total performance of a stock, incorporating returns from both the share price and dividends.
To understand this, consider the situation where you invest in a 5% div stock and hold the position for 10 years. Assume at the end of 10 years, the price has gone up by 50%. A price chart will then show a 50% return, but in reality the investor has also received 50% of the initial investment in dividends, making his total return substantially more. Exactly how much more depends on whether the investor reinvested the dividends in the stock, or just held them as cash. If the former, his total return will be well over 100%; in the latter, his total return will be 100% exactly.
There are 2 input options:
- Dividend type: allows the user to choose "gross" or "net". Note that most stocks will have a "gross" data series whereas many will not have a "net" series.
- Reinvestment: allows the user to choose whether dividends should be reinvested in the stock ("Yes") or held in cash ("No").
Total return formula:
- With reinvestment: log((today's closing price + dividends paid today) / (yesterday's closing price))
- Without reinvestment: log(today's closing price / yesterday's closing price) + log (dividends paid thus far / first closing price)
Linear Correlation Coefficient W/ MAs and Significance TestsThis Linear CC takes into account the log-normal distribution of stock prices and performs Pearson correlation on that data set. It also smoothens the results into an easy to read oscillator, and performs a two-tail t-test on the correlation coefficient data (with a = 0.05) to determine the significance of the coefficients. Significant results are shown in a solid yellow color while insignificant results are shown in a dark yellow color (you can eyeball this with a normal LCC by looking at results around -0.5 to +0.5).
Two MAs are provided as well for a quick trend analysis. You can reduce the lookback period, but it defaults to 31 for the sake of statistical standards.
ASG Delta %This utility script provides a convenient way to calculate the percentage gain or drop of a token's price within a user-defined date range. It eliminates the need for manual measurement on individual charts, saving time and effort.
The script is particularly valuable when integrated into a daily token scanning routine for watchlists. By comparing the significant gains or drops among different tokens, traders can identify potential trading opportunities.
Simply select the desired date range, and the script will identify the highest and lowest price points achieved during that period. It then shows a visual representation in the form of a bullish or bearish box, displaying the percentage change (delta %). If the current price falls within the box's upper and lower bounds, additional percentage information can be shown in either the 'normal' or 'reverse' mode.
For instance, if a token experiences a -52.35% drop, enabling the 'Reverse' setting will reveal a potential 109.86% gain (from the low), or a 76.02% gain (from current price) or a potential drop of -16.5% (from current price) etc.. Having these basic statistics available, without having to manually chart them, especially during prolonged bear or bull markets, enables traders to make informed decisions and position themselves for more profitable trades.
I hope you find this script valuable. Your comments and recommendations are welcome as they will help improve the script's functionality further.
The Z-score The Z-score, also known as the standard score, is a statistical measurement that describes a value's relationship to the mean of a group of values. It's 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. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
The concept of Z-score was introduced by statistician Carl Friedrich Gauss as part of his "method of the least squares," which was an important step in the development of the normal distribution and Z-score tables. It's a key concept in statistics and is used in various statistical tests.
In financial analysis, Z-scores are used to determine whether a data point is usual or unusual. You can think of it as a measure of how many standard deviations an element is from the mean. For instance, a Z-score of 1.0 would denote a value that is one standard deviation from the mean. Z-scores are also used to predict probabilities, with Z-scores having a distribution that is expected to be normal.
In trading, a Z-score is used to determine how often a trading system may produce a string of winners or losers. It can help a trader to understand whether the losses or profits they see are something that the system would most likely produce, or if it's a once in a blue moon situation. This helps traders make decisions about when to start or stop a system.
I just wanted to play a bit with the Z-score I guess.
Feel free to share your findings if you discover additional applications for this strategy or identify timeframes where it appears to perform more optimally.
How it works:
This strategy is based on a statistical concept called Z-score, which measures the number of standard deviations a data point is from the mean. In other words, it helps determine how unusual or usual a data point is.
In the context of this strategy, Z-score is applied to a 10-period EMA (Exponential Moving Average) of Heikin-Ashi candlestick close prices. The Z-score is calculated over a look-back period of 25 bars.
The EMA of the Z-score is then calculated over a 20-bar period, and the upper and lower thresholds (bounds for buy and sell signals) are defined using the 90th and 10th percentiles of this EMA score.
Long positions are taken when the Z-score crosses above the lower threshold or crosses above the mid-line (50th percentile). An additional long entry is made when the Z-score crosses above the highest value the EMA has been in the past 100 periods.
Short positions are initiated when the EMA crosses below the upper threshold, lower threshold or the highest value the EMA has been in the past 100 periods.
Positions are closed when opposing entry conditions are met, for example, a long position is closed when the short entry condition is true, and vice versa.
Set your desired start date for the strategy. This can be modified in the timestamp("YYYY MM DD") function at the top of the script.
Machine Learning : Torben's Moving Median KNN BandsWhat is Median Filtering ?
Median filtering is a non-linear digital filtering technique, often used to remove noise from an image or signal. Such noise reduction is a typical pre-processing step to improve the results of later processing (for example, edge detection on an image). Median filtering is very widely used in digital image processing because, under certain conditions, it preserves edges while removing noise (but see the discussion below), also having applications in signal processing.
The main idea of the median filter is to run through the signal entry by entry, replacing each entry with the median of neighboring entries. The pattern of neighbors is called the "window", which slides, entry by entry, over the entire signal. For one-dimensional signals, the most obvious window is just the first few preceding and following entries, whereas for two-dimensional (or higher-dimensional) data the window must include all entries within a given radius or ellipsoidal region (i.e. the median filter is not a separable filter).
The median filter works by taking the median of all the pixels in a neighborhood around the current pixel. The median is the middle value in a sorted list of numbers. This means that the median filter is not sensitive to the order of the pixels in the neighborhood, and it is not affected by outliers (very high or very low values).
The median filter is a very effective way to remove noise from images. It can remove both salt and pepper noise (random white and black pixels) and Gaussian noise (randomly distributed pixels with a Gaussian distribution). The median filter is also very good at preserving edges, which is why it is often used as a pre-processing step for edge detection.
However, the median filter can also blur images. This is because the median filter replaces each pixel with the value of the median of its neighbors. This can cause the edges of objects in the image to be smoothed out. The amount of blurring depends on the size of the window used by the median filter. A larger window will blur more than a smaller window.
The median filter is a very versatile tool that can be used for a variety of tasks in image processing. It is a good choice for removing noise and preserving edges, but it can also blur images. The best way to use the median filter is to experiment with different window sizes to find the setting that produces the desired results.
What is this Indicator ?
K-nearest neighbors (KNN) is a simple, non-parametric machine learning algorithm that can be used for both classification and regression tasks. The basic idea behind KNN is to find the K most similar data points to a new data point and then use the labels of those K data points to predict the label of the new data point.
Torben's moving median is a variation of the median filter that is used to remove noise from images. The median filter works by replacing each pixel in an image with the median of its neighbors. Torben's moving median works in a similar way, but it also averages the values of the neighbors. This helps to reduce the amount of blurring that can occur with the median filter.
KNN over Torben's moving median is a hybrid algorithm that combines the strengths of both KNN and Torben's moving median. KNN is able to learn the underlying distribution of the data, while Torben's moving median is able to remove noise from the data. This combination can lead to better performance than either algorithm on its own.
To implement KNN over Torben's moving median, we first need to choose a value for K. The value of K controls how many neighbors are used to predict the label of a new data point. A larger value of K will make the algorithm more robust to noise, but it will also make the algorithm less sensitive to local variations in the data.
Once we have chosen a value for K, we need to train the algorithm on a dataset of labeled data points. The training dataset will be used to learn the underlying distribution of the data.
Once the algorithm is trained, we can use it to predict the labels of new data points. To do this, we first need to find the K most similar data points to the new data point. We can then use the labels of those K data points to predict the label of the new data point.
KNN over Torben's moving median is a simple, yet powerful algorithm that can be used for a variety of tasks. It is particularly well-suited for tasks where the data is noisy or where the underlying distribution of the data is unknown.
Here are some of the advantages of using KNN over Torben's moving median:
KNN is able to learn the underlying distribution of the data.
KNN is robust to noise.
KNN is not sensitive to local variations in the data.
Here are some of the disadvantages of using KNN over Torben's moving median:
KNN can be computationally expensive for large datasets.
KNN can be sensitive to the choice of K.
KNN can be slow to train.
Multi Timeframe Control (Enomai)This indicator is called "Multi Timeframe Control" and has the following features:
1. Table settings:
- selection of different timeframes (1m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, D, W, M) for displaying closing prices;
- choice of table orientation (horizontal or vertical);
- selection of the position for the table on the chart (top right, middle right, bottom right, top center, middle center, bottom center, top left, middle left, bottom left);
- table size selection (automatic, large, medium, normal, small, tiny);
- text color customization (positive closing value color and negative closing value color);
- display or hide closing prices in the table.
2. Line settings:
- selection of different timeframes for displaying lines (similar to table settings);
- for each time frame (1m, 5m, 15m, etc.) you can choose whether to place a line on the chart;
- individual color selection for each line.
- choice of line display type on the chart (circle, cross, step line, diamond);
- show or hide lines on the chart.
3. Other settings:
- offset the length of price lines to the left by a certain number of bars (default is 0, maximum is 300 bars);
- offset of bars for displaying the closing price from previous periods (default is 1, maximum is 500 bars).
The indicator allows you to display closing prices for different timeframes simultaneously both in the table and on the chart with the corresponding colors for each timeframe. You can also set up which previous bar and, accordingly, its closing price to display in the table and on the chart. For example, if you set 3 in the bar offset setting for displaying the closing price of previous periods, then for the D timeframe will be displayed the closing price of the bar 3 days ago.
-----
Данный индикатор называется "Multi Timeframe Control" и имеет следующие возможности:
1. Настройка таблицы:
- выбор различных временных рамок (1m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, D, W, M) для отображения цен закрытия;
- выбор ориентации таблицы (горизонтальная или вертикальная);
- выбор положения таблицы на графике (верхний правый, средний правый, нижний правый, верхний центр, средний центр, нижний центр, верхний левый, средний левый, нижний левый);
- выбор размера таблицы (автоматический, большой, средний, нормальный, малый, мелкий);
- настройка цвета текста, цвета положительных значений закрытия цены и цвета отрицательных значений закрытия цены;
- отображение или сокрытие цен закрытия в таблице.
2. Настройка линий:
- выбор различных временных рамок для отображения линий (аналогичны настройкам таблицы);
- для каждой временной рамки (1m, 5m, 15m и т.д.) вы можете выбрать, нужно ли размещать линию на графике;
- вы можете выбрать цвет для каждой линии в отдельности.
- выбор типа отображения линий на графике (круг, крестик, ступенчатая линия, ромб);
- отображение или сокрытие линий на графике.
3. Другие настройки:
- смещение длины линий цены влево на определенное количество баров (по умолчанию 0, максимум 300 баров);
- смещение баров для отображения цены закрытия предыдущих периодов (по умолчанию 1, максимум 500 баров).
Индикатор позволяет отображать цены закрытия для разных таймфреймов одновременно как в таблице, так и на графике с соответствующими цветами для каждого таймфрейма. Также Вы можете настроить какой именно предыдущий бар и, соответственно, его цену закрытия отображать в таблице и на графике. Например, если в настройке смещения баров для отображения цены закрытия предыдущих периодов установить 3, то для таймфрейма D будет отображаться цена закрытия бара 3 дня назад.
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.
Currency ConverterWhat it is?
It's a Currency converter/Exchange rate Viewer.
How it works?
You put the main currency and the other currency in setting then it will show the converted rate in chart.
Daily data infoThis indicator can:
- Indicate on which day of the week created the High or Low
- Based on the bars you set, sum the times in which (The day of the week you want to test makes the Weekly High or Low)
- Has the option to Sum or calculate the %
Position Size Calculator (EzAlgo)Upon adding the indicator to the chart, you will be prompted to place entry price lines, stop loss price line, and multiple take profit price lines by clicking at the desired price level on the chart.
Section Summaries
Table Settings: Allows users to select position and font size from drop-down menus. Displays current settings and potential profit/loss values.
Price Points: Users can set their Entry and select whether they want to include a DCA entry, Stop Loss price, Liquidation Buffer %, Take Profit levels and the amount of position to close at each level.
Risk Management: Users fill out their Account Size, set their Risk % (or fixed $ amount) for each Entry, set Manual Leverage, or allow the indicator to automatically choose the leverage based on the Stop Loss price distance from Entry and the Risk % per Entry.
User-Input Descriptions
DCA Price: The price at which users initiate their second, equally sized and leveraged position when using a Dollar-Cost Averaging (DCA) strategy. Upon reaching the DCA Price, the Entry Price adjusts to the Avg Price, calculated as the midpoint between initial and DCA entries.
Liquidation Buffer: A pre-set percentage that determines how close to the Stop Loss a position can get before it's liquidated. This assists the Auto Leverage feature in optimizing the leverage amount according to risk tolerance.
Risk per Entry: The proportion of the account, in % or a fixed dollar amount, that users are willing to risk for each trading position. If DCA is checked, this will assume users are entering with half of the total position size per entry.
Automatic Leverage: Auto Leverage automatically determines the optimal leverage level for a trade based on the user's Stop Loss price distance from the Entry point and the user-defined risk percentage per Entry. It also considers a user-defined Liquidation Buffer, which is a preset percentage determining how close to the Stop Loss a position can get before it's liquidated. This tool allows traders to optimize their leverage amount according to their risk tolerance.
Max Leverage: The highest leverage level users are willing to use, even if the exchange permits higher. This limit applies when the Auto Leverage feature is enabled.
Seasonal Performance for Stocks & CryptoThe Seasonal Performance indicator quickly allows you to see if you are in a bullish or bearish time of year for an underlying security and where the current performance stacks up compared to the same time of year historically. Table is fully customizable from colors to what data to see.
Table Displays
Average Performance
Best Performance
Worst Performance
Last Performance
Current Performance
Note this indicator will only work with Stocks, ETF's, Index's or Crypto.
Central Bank Balance SheetsDisplay FED, China, Europe and Japan Central Bank Assets over time in USD.
Display FED, China, Europe and Japan Central Bank Assets as % of their country's GDP over time.
Display the sum of all of the central bank assets over time.
Autocorrelation - The Quant ScienceAutocorrelation - The Quant Science it is an indicator developed to quickly calculate the autocorrelation of a historical series. The objective of this indicator is to plot the autocorrelation values and highlight market moments where the value is positive and exceeds the attention threshold.
This indicator can be used for manual analysis when a trader needs to search for new price patterns within the historical series or to create complex formulas in estimating future prices.
What is autocorrelation?
Autocorrelation in trading is a statistical measure used to determine the presence of a relationship or pattern of dependence between values in a financial time series over time. It represents the correlation of past values in a series with its future values. In other words, autocorrelation in trading aims to identify if there are systematic relationships between the past prices or returns of a security or market and its future prices or returns. This analysis can be helpful in identifying patterns or trends that can be leveraged for informed trading decisions. The presence of autocorrelation may suggest that market prices or returns follow a certain pattern or trend over time.
Limitations of the model
It is important to note that autocorrelation does not necessarily imply a causal relationship between past and future values. Other variables or market factors may influence the dynamics of prices or returns, and therefore autocorrelation could be merely a random coincidence. Therefore, it is essential to carefully evaluate the results of autocorrelation analysis along with other information and trading strategies to make informed decisions.
How to use
The usage is very simple, you just need to add it to the current chart to activate the indicator.
From the user interface, you can manage two important features:
1. Lenght: the delay period applied to the historical series during the autocorrelation calculation can be managed from the user interface. By default, it is set to 20, which means that the autocorrelation ratio within the historical series is calculated with a delay of 20 bars.
2. Threshold: the threshold value that the autocorrelation level must meet can be managed from the user interface. By default, it is set to 0.50, which means that the autocorrelation value must be higher than this threshold to be considered valid and displayed on the chart.
3. Bar color: the color used to display the autocorrelation data and highlight the bars when autocorrelation is valid can be managed from the user interface.
To set up the chart
We recommend disabling the 'wick' and 'border' of the candlesticks from the chart settings for a high-quality user experience.
Z-Score Retracement Indicator Releasing the Z-Score Retracement Indicator
What it does:
The Z-Score retracement indicator operates similarly to Fibonacci retracements. It calculates the average, standard deviation and Z-Scores of a user defined period and will plot out the various Standard Deviation levels and price targets based on the period under analysis.
It will visually display the distance from the mean and which price targets correspond to which standard deviation. It is intended to aid traders in determining where the mean is and to calculate the probability of price targets and the probability of a regression to the mean.
How do you use it?
When you launch the indicator, it will ask you to identify the start period. I always try to identify periods where the most recent uptrend or downtrend has started, and then start the analysis from that point. When you plot it, the indicator will display the current strength of the trend in the same way that a regression or log-linear regression indicator would, by displaying the Pearson Correlation Coefficient:
Unlike with linear regression or log-linear regression, you don't necessarily need to have a strong up or downtrend to use the indicator, however it is ideal to find an area with a clear trend.
From there, you can clearly see the standard deviation zones:
The indicator will also display the current Standard Deviation of the last close price.
The centre line (a Z-Score of 0) corresponds to absolute neutrality and would be a regression to the mean. The price target for this area is also listed.
If you want to calculate the price of a specific Standard Deviation, you can! Launch the settings and select the input you would like:
Simply select whether you want to convert a Standard Deviation Z-Score to price or price to Z-Score. Then input the variable into the appropriate field. The indicator will then display the results in a table at the top right of the chart:
In the above image, you can see that a Z-Score of 0 (indicating absolute neutrality) on QQQ is equivalent to a price of 299.
Calculating Probability:
You can calculate probability by reference a Z-Score Table. I have discussed this in my previous Z-Score based indicators, but essentially, the rule of thumb is this:
Anything over + 2 standard deviations corresponds with roughly less than a 5 to 10% chance of continuation higher. I encourage you to check out the writeup on my Z-Score Probability Indicator for more information on the price use of Z-Score for probability determinations.
Concluding remarks:
And that is the indicator! Its pretty straight forward and its intended to be an added tool for regression and log-linear regression based traders to help visualize the actual distance from the mean a ticker is currently trading at.
Another thing to keep in mind is you can use this on the very small time frames as well. I have used this for day trading on the 5 and 1 minute timeframe to determine "regressions to the mean" on a much smaller level. Like here:
That's the indicator!
Hope you enjoy, leave your questions, comments and suggestions below, safe trades everyone!
Annualized Spot-Future DifferenceThe "Annualized Spot-Future Difference" indicator (ASFD) compares the closing prices of a futures contract and its underlying spot asset. It calculates the price difference between the two instruments and annualizes this difference to provide a standardized measure for comparison.
The indicator takes inputs for the futures ticker symbol and the spot ticker symbol, allowing flexibility in selecting the specific assets for analysis. Additionally, it allows the user to input the contract date, which represents the expiration date of the futures contract.
The ASFD indicator plots the annualized difference between the futures and spot prices. It calculates the price difference by subtracting the spot price from the futures price. To annualize this difference, it considers the remaining days to the contract expiration and scales the difference accordingly.
The annualized difference can provide insights into market expectations, as it reflects the market's perception of the future price movement of the underlying asset. A positive value indicates that the futures price is higher than the spot price, potentially suggesting bullish sentiment. Conversely, a negative value suggests bearish sentiment, with the futures price lower than the spot price.
Traders and analysts can utilize the ASFD indicator to identify potential opportunities for arbitrage or evaluate market sentiment regarding the underlying asset. By monitoring changes in the annualized difference over time, they can gain insights into market dynamics and make informed trading decisions.
It's important to note that the ASFD indicator relies on accurate and up-to-date pricing data for both the futures and spot assets. Traders should verify that the selected ticker symbols correspond to the desired instruments and ensure that the contract date aligns with the relevant futures contract expiration.
Overall, the ASFD indicator provides a quantitative measure of the annualized price difference between futures and spot assets, enabling traders and analysts to assess market expectations and identify potential trading opportunities.
Z-Score Candles with ReversalsIn the process of releasing some of my Z-Score based indicators. This is the Z-Score Candle indicator.
What it does:
This converts the current candles into a z-score based candle over a 14 period lookback (adjustable but recommended to leave at 14).
It plots out the overbought/oversold areas using colours and will lookback over a user defined period of time to identify previous areas of bullish and bearish reversals.
Why Z-Score Candles?
Before we get into how to use it, I think its important to discuss why converting candles to a Z-Score is advantageous.
When we convert candlesticks to Z-Score, we have the ability to view areas of natural mathematical support and resistance (I want to clarify, when I saw mathematical support and resistance, it is kind of a misnomer, it is not the same as technical support and resistance. Its a measure of the natural tendency of things to revert to their mean and not deviate to extreme poles of their mean for prolonged period of time, I use the term mathematical support and resistance as it is something most traders are familiar with and operates similarly).
This is particularly helpful during trends. For example, if we take a look at the following BA chart:
In the chart above, you can see that despite BA not being on technical support (that red line), the indicator identified math support (the support was identified by the indicator looking at BA's natural deviations from its mean and seeing that, at that particular point in time, BA had deviated to an area that traditionally leads to reversals to the upside).
If we look at another example:
We can see in the chart above that, despite BA making a new high on the day and "breaking out" of previous resistance, BA was at math resistance being 3.0 Standard Deviations from its trading mean at the time. Thus, necessitating the pullback you see in the chart.
How to use it:
The indicator can be used similar to RSI and Stochastics or any other oscillator based indicator. The difference is, you can actually see the price action in terms of its relationship to its mean. What the means, is the indicator displays the current price action in terms of the ticker's relationship to its current mean and average. This permits us to see areas of rejection and support in relation to its current distance from neutrality. We can also see the various positions of each of the ticker's values from the mean. For example, we can see where the open is in relation to the average, the high and the low vs simply looking at a single variable (usually the close price).
The indicator will also highlight areas where the ticker has deviated to extreme ends of its mean (defined at a Z-Score of +/- 3.0). The picture below is an example of a bearish extreme:
And a bullish extreme:
You can see in both cases a reversal resulted almost immediately.
Inputs:
In the chart above, you can see the 3 main input sections.
Z-Score Lookback: This determines the lookback length for the Z-Score. The recommendation is to leave at 14, especially if you are a day trader.
SMA Inputs: The SMA (The white line) can be toggled off and on. You can also change the source to the High, Low, Close and Open Z-Score. You can adjust the lookback length of the SMA to your liking to assess trends. It does not need to be the same input as the Z-Score.
Reversal Inputs: The reversal inputs determines the length of lookback for the indicator to determine the most extreme bearish and bullish deviation from its mean. It is defaulted at 75 but can be adjusted based on preference. For more frequent signals, you can reduce the lookback length but be prepared for false signals in that case. You can also toggle off the reversal labels if you do not want them.
Concluding remarks:
And that is the Z-Score Candle indicator in a nutshell. Pretty self explanatory otherwise. It is more tailored to day traders. It is not a tool I would necessarily use for longer-term outlooks. I would use a simple Z-Score based indicator for that. But for active day trading, this is very helpful. That said, it can be used to look at longer term outlooks as well, but there are more powerful Z-Score based indicators for that (you can check out my own Z-Score indicator or my recently released Z-Score Probability Indicator which is more tailored for bigger picture outlooks).
Hope you enjoy, as always leave your comments, suggestions and questions below!
Safe trades to all!
Z-Score Probability IndicatorThis is the Z-Score Probability indicator. As many people like my original Z-Score indicator and have expressed more interest in the powers of the Z, I decided to make this indicator which shows additional powers of the Z-Score.
Z-Score is not only useful for measuring a ticker or any other variable’s distance from the mean, it is also useful to calculate general probability in a normal distribution set. Not only can it calculate probability in a dataset, but it can also calculate the variables within said dataset by using the Standard Deviation and the Mean of the dataset.
Using these 2 aspects of the Z-Score, you can, In principle, have an indicator that operates similar to Fibonacci retracement levels with the added bonus of being able to actually ascertain the realistic probability of said retracement.
Let’s take a look at an example:
This is a chart showing SPY on the daily timeframe. If we look at the current Z-Score level, we can see that SPY is pushing into the 2 to 3 Z-Score range. We can see two things from this:
1. We can see that a retracement to a Z-Score of 2 would correspond to a price of 425.26 based on the current dataset. And
2. We can see that the probability that SPY retraces to a Z-Score of 2 is around 0.9800 or 98%.
To take it one step further, we can look at the various other variables in the distribution. If we were to bet on SPY retracing back to -1 SDs, that would correspond to a price of around 397.15, with a probability of around 0.1600 or 16% (see image below):
Let’s say, we thought SPY would go to $440. Well, we can see that the probability SPY goes to 434.64 currently is pretty low. How do we know? Because the Z-Score table shows us the probability of values falling BELOW that Z-score level in the current distribution. So if we look at this example below:
We can see that 0.9998 or roughly 99% of values in the current SPY distribution will fall below 434.64. Thus, it may be unrealistic, at this point in time, to target said value.
So what is a Z-Score Table?
Well, I need to disclose/clarify that the Z-Score Table being displayed in this indicator does Z-Score probability a HUGE injustice. However, with the constraints what is realistic to fit into an indicator, I had to make it far more succinct. Let’s take a look at an actual Z-Score Table below:
Above is a look an the actual Z-Score table. How it works is you first identify you’re Z-Score and then find the corresponding value that relates to your score. The number displayed in the dataset represents the number of variables in the dataset/density distribution that fall BELOW that particular Z-score.
So, for example, if we have a Z-Score of -2.31, we can consult that table, go to the -2.3 then scroll across to the 0.01 to represent -2.31. We would see that this Z-Score corresponds to a 0.0104 probability zone (or essentially 1%) indicating that the majority of the variables in the distribution fall below that mean Z-score. In terms of tickers and stocks, that would mean it would theoretically be “overbought”.
So what does the indicator Z-Table tell us?
I have averaged out the data for the purposes of this indicator. However, you can also reference a manual Z-Table to get the exact probability for the current precise Z-Score. However, the reality is it doesn’t necessarily matter to be exact when it comes to tickers. The reason being, ticker’s are in constant flux, and by the time you identify that probability, the ticker will already be at a different level. So generalizations are okay in these circumstances, you just need to get the “gist” of where the distribution lies.
So how do I use the indicator?
Using the indicator is pretty straightforward. Once launched, you will see the current Z-Score of the ticker, the current levels based on the distribution and the summarized Z-Table.
The Z-Table will turn gray to indicate the zone the ticker is currently in. In this case, we can see that SPY currently is in the 2 SD Zone, meaning that 0.98 or 98% of the current dataset being shown falls below the price we are at:
When we launch the settings, we can see a few inputs.
Lookback Length: This determines the number of candles back we want to calculate the distribution for. It is defaulted to 75, but you can adjust it to whichever length you want.
SMA Length: The SMA is optional but defaults to on. If you want to see the smoothed trend of the Z-Score, this will do the trick. It does not need to be set to the same
length as the Z-Score lookback. Thus, if you want a more or less responsive SMA with, say, a larger dataset, then you can reduce the SMA length yourself.
Distribution Probability Fills: This simply colour codes the distribution zones / probability zones on the indicator.
Show Z-Table: This will display the summarized Z-Table.
Show SMA: As I indicated, the SMA is optional, you can toggle it on or off to see the overall Z-Score trend.
Concluding Remarks:
And that my friends is the Z-Score Probability Indicator.
I hope you all enjoy it and find it helpful. As always leave your comments, questions and suggestions below.
Safe trades to all and take care!
Risk-Adjusted Return OscillatorThe Risk-Adjusted Return Oscillator (RAR) is designed to aid traders in predicting future price action by analysing the risk-adjusted performance of an asset. This oscillator is displayed directly on the price chart, unlike other oscillators.
By considering the risk-return relationship, the indicator helps identify periods of overvaluation or undervaluation, allowing traders to anticipate potential price reversals or trend accelerations.
HOW TO USE
The Risk-Adjusted Return Oscillator analyses the risk-adjusted performance of an asset to detect price reversals and accelerations. Here's how to interpret its signals:
Ranging Market:
Overbought Signal: When the RAR curve reaches the overbought level (upper red line), it suggests a potential reversal signal. It indicates that the asset may be overvalued, and a price correction or trend reversal could occur.
Oversold Signal: When the RAR curve reaches the oversold level (lower red line), it indicates a potential reversal signal. It suggests that the asset may be undervalued, and a price correction or trend reversal could take place.
Trending Market:
Overbought Signal: In a trending market, an overbought signal (RAR curve reaching upper red line) suggests trend acceleration. It indicates that the existing trend is gaining strength, and buying pressure is increasing.
Oversold Signal: In a trending market, an oversold signal (RAR curve reaching lower red line) also signifies trend acceleration. It suggests that the prevailing trend is intensifying, and selling pressure is increasing.
Thus, it's important to consider the market context when interpreting overbought and oversold signals. In ranging markets, these signals act as potential reversal points. However, in trending markets, they indicate trend acceleration, reinforcing the current price direction.
SETTINGS
Period Length: Adjust the number of bars used to calculate returns and standard deviation.
Smoothing: Define the smoothing period for the RAR curve.
Show Overbought/Oversold Signals: Choose whether to display triangular shapes for overbought and oversold conditions.
Correlation TrackerCorrelation Tracker Indicator
The Correlation Tracker indicator calculates and visualizes the correlation between two symbols on a chart. It helps traders and investors understand the relationship and strength of correlation between the selected symbol and another symbol of their choice.
Indicator Features:
- Correlation Calculation: The indicator calculates the correlation between two symbols based on the provided lookback period.
- Correlation Scale: The correlation value is normalized to a scale ranging from 0 to 1 for easy interpretation.
- Table Display: A table is displayed on the chart showing the correlation value and a descriptive label indicating the strength of the correlation.
- Customization Options: Users can customize the text color, table background color, and choose whether to display the Pearson correlation value.
- The Correlation Tracker indicator utilizes a logarithmic scale calculation, making it particularly suitable for longer timeframes such as weekly charts, thereby providing a more accurate and balanced measure of correlations across a wide range of values.
How to Use:
1. Select the symbol for which you want to track the correlation (default symbol is "SPX").
2. Adjust the lookback period to define the historical data range for correlation calculation.
3. Customize the text color and table background color according to your preference.
4. Choose whether to display the Pearson correlation value or a descriptive label for correlation strength.
5. Observe the correlation line on the chart, which changes color based on the strength of the correlation.
6. Refer to the correlation table for the exact correlation value or the descriptive label indicating the correlation strength.
Note: The indicator can be applied to any time frame chart and is not limited to logarithmic scale.
Script TimerWanna know how long your script takes to execute.
Just put this function at the end of your code and it will tell you how much time it takes to run your algo from start to end.
Data will show in the data window panel measured in seconds
AlgebraLibLibrary "AlgebraLib"
f_signaldraw(_side, _date)
: Draw a simple label with Buy or Sell signal
Parameters:
_side (string)
_date (int)
Returns: : VOID, it draws a new label