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.
Statistics
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
Rolling Risk-Adjusted Performance RatiosThis simple indicator calculates and provides insights into different performance metrics of an asset - Sharpe, Sortino and Omega Ratios in particular. It allows users to customize the lookback period and select their preferred data source for evaluation of an asset.
Sharpe Ratio:
The Sharpe Ratio measures the risk-adjusted return of an asset by considering both the average return and the volatility or riskiness of the investment. A higher Sharpe Ratio indicates better risk-adjusted performance. It allows investors to compare different assets or portfolios and assess whether the returns adequately compensate for the associated risks. A higher Sharpe Ratio implies that the asset generates more return per unit of risk taken.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that focuses specifically on the downside risk or volatility of an asset. It takes into account only the negative deviations from the average return (downside deviation). By considering downside risk, the Sortino Ratio provides a more refined measure of risk-adjusted performance, particularly for investors who are more concerned with minimizing losses. A higher Sortino Ratio suggests that the asset has superior risk-adjusted returns when considering downside volatility.
Omega Ratio:
The Omega Ratio measures the probability-weighted ratio of gains to losses beyond a certain threshold or target return. It assesses the skewed nature of an asset's returns by differentiating between positive and negative returns and assigning more weight to extreme gains or losses. The Omega Ratio provides insights into the potential asymmetry of returns, highlighting the potential for significant positive or negative outliers. A higher Omega Ratio indicates a higher probability of achieving large positive returns compared to large negative returns.
Utility:
Performance Evaluation: Provides assessment of an asset's performance, considering both returns and risk factors.
Risk Comparison: Allows for comparing the risk-adjusted returns of different assets or portfolios. Helps identify investments with better risk-reward trade-offs.
Risk Management: Assists in managing risk exposure by evaluating downside risks and volatility.
Monthly Gain in percentageThis scripts calculates the percentage gain in a month (previous 22 trade days).
Firstly, it calculates number of sample days
-> minimum no. of sampling duration = 22
-> maximum no. of sampling duration = increased from 22 until 0day_low > 22_day_high
Example if sampling_duration = 100
Monthly percentage gain = ((Current_Day_High_Price - 0_Day_Low_Price) * 100 / 0_Day_Low_Price) * 22 / sampling_duration
Monthly Strategy Performance TableWhat Is This?
This script code adds a Monthly Strategy Performance Table to your Pine Script strategy scripts so you can see a month-by-month and year-by-year breakdown of your P&L as a percentage of your account balance.
The table is based on realized equity rather than open equity, so it only updates the metrics when a trade is closed.
That's why some numbers will not match the Strategy Tester metrics (such as max drawdown), as the Strategy Tester bases metrics like max drawdown on open trade equity and not realized equity (closed trades).
The script is still a work-in-progress, so make sure to read the disclaimer below. But I think it's ready to release the code for others to play around with.
How To Use It
The script code includes one of my strategies as an example strategy. You need to replace my strategy code with your own. To do that just copy the source code below into a blank script, delete lines 11 -> 60 and paste your strategy code in there instead of mine. The script should work with most systems, but make sure to read the disclaimer below.
It works best with a significant amount of historical data, so it may not work very effectively on intraday timeframes as there is a severe limitation of available bars on TradingView. I recommend using it on 4HR timeframes and above, as anything less will produce very little usable data. Having a premium TradingView plan will also help boost the number of available bars.
You can hover your mouse over a table cell to get more information in the form of tooltips (such as the Long and Short win rate if you hover over your total return cell).
Credit
The code in this script is based on open-source code originally written by QuantNomad, I've made significant changes and additions to the original script but all credit for the idea and especially the display table code goes to them - I just built on top of it:
Why Did I Make This?
None of this is trading or investment advice, just my personal opinion based on my experience as a trader and systems developer these past 6+ years:
The TradingView Strategy Tester is severely limited in some important ways. And unless you use complex Excel formulas on exported test data, you can't see a granular perspective of your system's historical performance.
There is much more to creating profitable and tradeable systems than developing a strategy with a good win rate and a good return with a reasonable drawdown.
Some additional questions we need to ask ourselves are:
What did the system's worst drawdown look like?
How long did it last?
How often do drawdowns occur, and how quickly are they typically recovered?
How often do we have a break-even or losing month or year?
What is our expected compounded annual growth rate, and how does that growth rate compare to our max drawdown?
And many more questions that are too long to list and take a lifetime of trading experience to answer.
Without answering these kinds of questions, we run the risk of developing systems that look good on paper, but when it comes to live trading, we are uncomfortable or incapable of enduring the system's granular characteristics.
This Monthly Performance Table script code is intended to help bridge some of that gap with the Strategy Tester's limited default performance data.
Disclaimer
I've done my best to ensure the numbers this code outputs are accurate, and according to my testing with my personal strategy scripts it appears to work fine. But there is always a good chance I've missed something, or that this code will not work with your particular system.
The majority of my TradingView systems are extremely simple single-target systems that operate on a closed-candle basis to minimize many of the data reliability issues with the Strategy Tester, so I was unable to do much testing with multiple targets and pyramiding etc.
I've included a Debug option in the script that will display important data and information on a label each time a trade is closed. I recommend using the Debug option to confirm that the numbers you see in the table are accurate and match what your strategy is actually doing.
Always do your own due diligence, verify all claims as best you can, and never take anyone's word for anything.
Take care, and best of luck with your trading :)
Kind regards,
Matt.
PS. If you're interested in learning how this script works, I have a free hour-long video lesson breaking down the source code - just check out the links below this script or in my profile.
[Mad] Liquidation LevelsThe Liquidation Lines Technical Indicator is a trading tool designed to assist traders in identifying potential liquidation levels. This indicator generates virtual positions, known as "liquidation lines", which mark the points at which these positions would be liquidated under specified conditions.
Key Features:
Quantity of Lines: The indicator can create up to 125 liquidation lines, evenly distributed between long and short positions. This limit is derived from a maximum of 500 lines, divided by four to account for two types of leverage (long and short).
Customizable Liquidation Levels: Users are given the ability to set liquidation levels according to their individual trading strategies and the current market conditions.
Customizable Visuals: The color and thickness of the liquidation lines can be adjusted to suit personal preferences, providing a clear visual representation on the trading chart for ease of analysis.
Selectable Signal Sources: The indicator provides the flexibility to choose the signal source for creating the liquidation lines. Users can select from a range of popular technical analysis tools such as Bollinger Bands, MACD crosses, EMA crosses, or SMA crosses. This feature allows traders to customize the formation of liquidation lines based on their preferred technical indicators, adding to the comprehensiveness and versatility of the tool.
Two selectable Leverages: The indicator accommodates both long and short leverages, offering a comprehensive understanding of potential liquidation points for various trading scenarios.
Selectable Exchange Maintenance: The indicator allows users to select their specific cryptocurrency exchange. This feature ensures that the liquidation lines are accurately calculated according to the maintenance margin requirements of the chosen exchange, adding precision and customization to the trading analysis.
Ultimate Correlation CoefficientIt contains the Correlations for SP:SPX , TVC:DXY , CURRENCYCOM:GOLD , TVC:US10Y and TVC:VIX and is intended for INDEX:BTCUSD , but works fine for most other charts as well.
Don't worry about the colored mess, what you want is to export your chart ->
TradingView: How can I export chart data?
and then use the last line in the csv file to copy your values into a correlation table.
Order is:
SPX
DXY
GOLD
US10Y
VIX
Your last exported line should look like this:
2023-05-25T02:00:00+02:00 26329.56 26389.12 25873.34 26184.07 0 0.255895534 -0.177543633 0.011944815 0.613678565 0.387705043 0.696003298 0.566425278 0.877838156 0.721872645 0 -0.593674719 -0.839538073 -0.662553817 -0.873684242 -0.695764534 -0.682759656 -0.54393749 -0.858188808 -0.498548691 0 0.416552489 0.424444345 0.387084882 0.887054782 0.869918437 0.88455388 0.694720993 0.192263269 -0.138439783 0 -0.39773255 -0.679121698 -0.429927048 -0.780313396 -0.661460134 -0.346525721 -0.270364046 -0.877208139 -0.367313687 0 -0.615415111 -0.226501775 -0.094827955 -0.475553396 -0.408924242 -0.521943234 -0.426649404 -0.266035908 -0.424316191
The zeros are thought as a demarcation for ease of application :
2023-05-25T02:00:00+02:00 26329.56 26389.12 25873.34 26184.07 0 -> unused
// 15D 30D 60D 90D 120D 180D 360D 600D 1000D
0.255895534 -0.177543633 0.011944815 0.613678565 0.387705043 0.696003298 0.566425278 0.877838156 0.721872645 -> SPX
0
-0.593674719 -0.839538073 -0.662553817 -0.873684242 -0.695764534 -0.682759656 -0.54393749 -0.858188808 -0.498548691 -> DXY
0
0.416552489 0.424444345 0.387084882 0.887054782 0.869918437 0.88455388 0.694720993 0.192263269 -0.138439783 -> GOLD
0
-0.39773255 -0.679121698 -0.429927048 -0.780313396 -0.661460134 -0.346525721 -0.270364046 -0.877208139 -0.367313687 -> US10Y
0
-0.615415111 -0.226501775 -0.094827955 -0.475553396 -0.408924242 -0.521943234 -0.426649404 -0.266035908 -0.424316191 -> VIX
KernelFunctionsFiltersLibrary "KernelFunctionsFilters"
This library provides filters for non-repainting kernel functions for Nadaraya-Watson estimator implementations made by @jdehorty. Filters include a smoothing formula and zero lag formula. You can find examples in the code. For more information check out the original library KernelFunctions.
rationalQuadratic(_src, _lookback, _relativeWeight, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_relativeWeight (simple float)
startAtBar (simple int)
_filter (simple string)
gaussian(_src, _lookback, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
startAtBar (simple int)
_filter (simple string)
periodic(_src, _lookback, _period, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_period (simple int)
startAtBar (simple int)
_filter (simple string)
locallyPeriodic(_src, _lookback, _period, startAtBar, _filter)
Parameters:
_src (float)
_lookback (simple int)
_period (simple int)
startAtBar (simple int)
_filter (simple string)
j(line1, line2)
Parameters:
line1 (float)
line2 (float)
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. 🧙♂️
ATR Daily BandThis indicator draws an upper and lower band for each day. It uses the Average True Range calculation (with configurable lookback) and places the band at 1ATR above and 1ATR below the daily open.
I use this indicator as a simple gauge to tell how significant price movement is, and get a feel for the daily volatility. Due to the fractal nature of price action, it can be difficult to determine if a price movement is significant while zoomed in on a single intraday chart. Using this indicator, I can tell if the price action is approaching the ATR or if it's just staying within the band.
Strategies: Useful for both mean reversion and momentum strategies. It's up to you to decide how this metric will fit into your trading strategy. I currently use this indicator to look for mean reversion setups, but that is due to the current market conditions and my personal trading style.
Initial Balance Panel Strategy for BitcoinInitial Balance Strategy
Initial Balance Strategy uses a source code of "Initial Balance Monitoring Panel" that build from "Initial Balance Markets Time Zones - Overall Highest and Lowest".
Initial Balance is based on the highest and lowest price action within the first 60 minutes of trading. Reading online this can depict which way the market can trend for the session. More information about Initial Balance Panel you can read at the end of the article.
Strategy idea
The main idea is to catch the trend move when most of the 16 Crypto pairs break the Low or High levels together. I found good results when 15 of 16 pairs is break that levels and after we manage the trade within some trail stop indicator, I choose Volatility Stop for this strategy.
Additional Strategy idea
The second one idea that was not made is to catch the pullback after fully green/red zones in Initial Balance Panel become white. That mean the main trend can be finished and we can try to catch good pullback in opposite direction.
Binance Crypto pairs
The strategy use the 16 default Crypto currencies pairs from the Binance. As additional variations of the strategy can be changing the currencies pairs and their number.
List of default pairs:
BINANCE:BTCUSDT, BINANCE:ETHUSDT, BINANCE:EOSUSDT, BINANCE:LTCUSDT, BINANCE:XRPUSDT, BINANCE:DASHUSDT, BINANCE:IOTAUSDT, BINANCE:NEOUSDT, BINANCE:QTUMUSDT, BINANCE:XMRUSDT, BINANCE:ZECUSDT, BINANCE:ETCUSDT, BINANCE:ADAUSDT, BINANCE:XTZUSDT, BINANCE:LINKUSDT, BINANCE:DOTUSDT
Summary
The strategy works very well for a buy trades with settings 15 crypto pairs of 16 that follow the trend with breaking the long initial balance level.
Initial Balance Monitoring Panel
Allows you to have an instant view of 16 Crypto pairs within a monitoring panel, monitoring Initial Balance (Asia, London, New York Stock Exchanges).
The code can easily be changed to suit the crypto pairs you are trading.
The setup of my chart would also include this indicator and the "Initial Balance Markets Time Zones - Overall Highest and Lowest" (with all IBs enabled) as shown above.
Initial Balance is based on the highest and lowest price action within the first 60 minutes of trading. Reading online this can depict which way the market can trend for the session.
The indicator has been coded for Crypto (so other symbols may not work as expected).
Though Initial Balance is based off the first 60 minutes of the trading markets opening, but Crypto is 24/7, this indicator looks at how Asia, London and New York Stock Exchanges opening trading can affect Crypto price action.
Source: Initial Balance Monitoring Panel
Position and Profit/LossHelps users track their position and profit/loss in real-time.
Instructions :
Open the indicator settings
Input your Quantity, Buy Price, Fee, and Target Price
This indicator is designed to provide users with simple real-time tracking of their positions and profit/loss within a trading session. It offers clear and concise information that enables users to understand their current position's profitability, making it easier for them to manage their trades effectively.
Input parameters
qty : Quantity of the position (default value: 100.0). The target label is represented by a green cross
buy_price : Buy price of the position (default value: 1.0).
fee : Fee percentage for the transaction (default value: 0.0016). note that this is not a percentage, but rather a decimal. So 0.0016 is 0.16%
target : Target price for the position (default value: 1.0). This is an extra label to show you where your target is on the chart. The target label is represented by a green cross
In addition to the main profit/loss label, the script also displays two auxiliary labels. The "BuyPrice" label presents the buy price of the position as a red cross symbol on the chart, allowing users to easily identify their entry point. The "targetSell" label displays the target sell price as green cross symbol, indicating the desired exit point for the position. These visual markers help users visualize their trading strategy.
The script takes into account that users may only need this information displayed on the last bar, as continuous updates might not be necessary. By checking if the current bar is the last one, the script ensures that the labels are only displayed when relevant.
Limitations
The script assumes that trading is done using the same quantity; which is not always the case. This will change with subsequent updates.
Statistics TableThis script display some useful Statistics data that can be useful in making trading decision.
Here the list of information this script is display in table format.
You can change each and every single ema and rs length as per your need from setting.
1) close difference from first ema
2) close difference from second ema
3) close difference from third ema
4) close difference from fourth ema
5) difference between first and second ema
6) difference between second and third ema
7) difference between first and third ema
8) volume up down ratio
9) ATR/ADR %
10) volume pocket pivot count
11) daily closing range
12) weekly closing range
13) close difference from 52week high
14) close difference from 52week low
15) close difference from All time high
16) close difference from All time low
17) rs line above or below first rs ema
18) rs line above or below second rs ema
19) rs line above or below third rs ema
20) rs line above or below fourth rs ema
21) first rs value
22) second rs value
23) third rs value
24) fourth rs value
25) difference between previous first rs length days change % and current first rs length days change %
26) difference between previous second rs length days change % and current second rs length days change %
27) difference between previous third rs length days change % and current third rs length days change %
Time Series Model IndicatorHello,
I am releasing this time series modelling indicator.
Brief overview of the indicator's functionality:
The Time Series Model indicator is a technical analysis tool that calculates and visualizes a linear regression line based on historical price data. It assesses the trend direction and provides an outer band around the regression line to indicate potential support and resistance levels. The indicator also detects outliers in the price data and calculates correlations between the time variable and the closing price. It offers various customization options such as input length, user-defined hours in advance, display settings for tables and fills, and the ability to show variable correlations. Overall, this indicator aims to help traders identify trends, potential reversals, and price extremes in a given time series.
Specific Functions:
Slope Calculations: The indicator calculates the slope and intercept of the regression line using the specified length of assessment (user defined). It also computes the residuals, standard error of the regression, and the upper and lower bounds of the standard error region. Additionally, it calculates multiple standard deviation bands around the regression line. The slope will change to green if the stock is in an uptrend and to red if the stock is in a downtrend.
Outliers: This feature detects extreme positive and negative outliers based on the z-score calculated from the price data. It highlights the outliers with a red background color to red if this option is selected.
Correlation to Time Assessments: This feature performs trend assessments based on the correlation between time and price data. It identifies uptrends, downtrends, falling trends, rising trends, etc.
Outerband Plots: This feature plots the regression line, standard error bands, and multiple standard deviation bands around the regression line. It also fills the areas between these lines.
Trend Assessment: This feature further assesses the trend based on the strength of the correlation. It identifies strong up or down trends, moderate trends, weak trends, no trend, etc.
Linear Regression Time Data: This section retrieves price data (close, high, low, open) for the specified timeframe and stores them in arrays for a linear regression analysis.
Define LinReg Variables: This section calculates linear regression lines and their upper and lower control limits for the close, low and high prices. It also calculates the correlation between close price and time.
Manual assessments: This feature allows for the manual assessment of time series data. The user can input a look forward for hours in the future and get the predicted price range based on the current time relationship. See image below:
Calculating model "fit": The indicator will display the amount of time the stock closes within and outside its respective bands to ascertain the degree of "fit" (see image below):
Explanations:
The outer cloud: The outer, tealish green cloud represents the regression line + 1.5 standard deviations from the regression line.
The inner cloud: The inner, white coloured cloud represents the immediate time series range calculated through regression of the open, high and low price of the ticker.
Correlations:
The ability of the indicator to calculate correlations on both the smaller and larger timeframes are its strongest feature. You can see the formation of trends by tracking the correlation over the length of the time series model's assessment. You can also track the degree of change. The image below shows the correlation table:
In this image, we can see that the stock is in a moderate downtrend manifested by a correlation of -0.73 (purple arrow).
This downtrend is weakening as manifested by a positive change of 0.05 on the shorter timeframe.
If we scroll down on the table and see the Close, High and Low, we can see that the larger trend over time is a downtrend and that this downtrend is actually strengthening. We know this by the negative change (negative change = significant inverse relationship to time is increasing. i.e. as time increases, the stock price decreases proportionately).
So what does negative correlation to time mean?
If a stock's price exhibits a negative correlation to time, it implies that there is a systematic relationship between the passage of time and the stock's price movement in the opposite direction. This finding could have several potential implications for traders and investors. Firstly, it suggests that the stock's price tends to decrease as time progresses, indicating a downward trend or bearish sentiment. This information might be useful for traders looking to capitalize on short-selling or hedging strategies. Secondly, it could indicate a potential opportunity to predict future price movements based on the timing of negative correlations. By understanding the relationship between time and price, investors may be able to make more informed decisions about when to buy or sell the stock. Lastly, a negative correlation to time may also suggest the influence of external factors or market conditions that systematically impact the stock's performance over time. Therefore, monitoring this correlation can provide insights into broader market dynamics and help investors better understand the stock's behavior.
What about a positive correlation to time?
If a stock's price demonstrates a positive correlation to time, it means that there is a consistent relationship between the passage of time and the stock's price movement in the same direction. This positive correlation to time can have significant implications for traders and investors. Firstly, it indicates a potential upward trend or bullish sentiment, suggesting that the stock's price tends to increase as time progresses. This information can be valuable for investors seeking long-term growth opportunities or looking to capitalize on upward price movements. Secondly, a positive correlation to time may provide insights into the stock's historical performance patterns and help identify potential buying or selling opportunities based on the timing of positive correlations. Additionally, understanding this correlation can aid in assessing the stock's overall trajectory and identifying potential market trends. It's important to note that positive correlation to time does not guarantee future performance, but it can offer valuable information to inform investment decisions.
Because this indicator is pretty big, I have done an overview and tutorial video which I will link below:
As always, please leave your comments and suggestions below.
I thank you for taking the time to read and check out this indicator.
Safe trades everyone and enjoy your weekend!
Cobra's CryptoMarket VisualizerCobra's Crypto Market Screener is designed to provide a comprehensive overview of the top 40 marketcap cryptocurrencies in a table\heatmap format. This indicator incorporates essential metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, Omega Ratio, Z-Score, and Average Daily Range (ADR). The table utilizes cell coloring resembling a heatmap, allowing for quick visual analysis and comparison of multiple cryptocurrencies.
The indicator also includes a shortened explanation tooltip of each metric when hovering over it's respected cell. I shall elaborate on each here for anyone interested.
Metric Descriptions:
1. Beta: measures the sensitivity of an asset's returns to the overall market returns. It indicates how much the asset's price is likely to move in relation to a benchmark index. A beta of 1 suggests the asset moves in line with the market, while a beta greater than 1 implies the asset is more volatile, and a beta less than 1 suggests lower volatility.
2. Alpha: is a measure of the excess return generated by an investment compared to its expected return, given its risk (as indicated by its beta). It assesses the performance of an investment after adjusting for market risk. Positive alpha indicates outperformance, while negative alpha suggests underperformance.
3. Sharpe Ratio: measures the risk-adjusted return of an investment or portfolio. It evaluates the excess return earned per unit of risk taken. A higher Sharpe ratio indicates better risk-adjusted performance, as it reflects a higher return for each unit of volatility or risk.
4. Sortino Ratio: is a risk-adjusted measure similar to the Sharpe ratio but focuses only on downside risk. It considers the excess return per unit of downside volatility. The Sortino ratio emphasizes the risk associated with below-target returns and is particularly useful for assessing investments with asymmetric risk profiles.
5. Omega Ratio: measures the ratio of the cumulative average positive returns to the cumulative average negative returns. It assesses the reward-to-risk ratio by considering both upside and downside performance. A higher Omega ratio indicates a higher reward relative to the risk taken.
6. Z-Score: is a statistical measure that represents the number of standard deviations a data point is from the mean of a dataset. In finance, the Z-score is commonly used to assess the financial health or risk of a company. It quantifies the distance of a company's financial ratios from the average and provides insight into its relative position.
7. Average Daily Range: ADR represents the average range of price movement of an asset during a trading day. It measures the average difference between the high and low prices over a specific period. Traders use ADR to gauge the potential price range within which an asset might fluctuate during a typical trading session.
Utility:
Comprehensive Overview: The indicator allows for monitoring up to 40 cryptocurrencies simultaneously, providing a consolidated view of essential metrics in a single table.
Efficient Comparison: The heatmap-like coloring of the cells enables easy visual comparison of different cryptocurrencies, helping identify relative strengths and weaknesses.
Risk Assessment: Metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, and Omega Ratio offer insights into the risk associated with each cryptocurrency, aiding risk assessment and portfolio management decisions.
Performance Evaluation: The Alpha, Sharpe Ratio, and Sortino Ratio provide measures of a cryptocurrency's performance adjusted for risk. This helps assess investment performance over time and across different assets.
Market Analysis: By considering the Z-Score and Average Daily Range (ADR), traders can evaluate the financial health and potential price volatility of cryptocurrencies, aiding in trade selection and risk management.
Features:
Reference period optimization, alpha and ADR in particular
Source calculation
Table sizing and positioning options to fit the user's screen size.
Tooltips
Important Notes -
1. The Sharpe, Sortino and Omega ratios cell coloring threshold might be subjective, I did the best I can to gauge the median value of each to provide more accurate coloring sentiment, it may change in the future.
The median values are : Sharpe -1, Sortino - 1.5, Omega - 20.
2. Limitations - Some cryptos have a Z-Score value of NaN due to their short lifetime, I tried to overcome this issue as with the rest of the metrics as best I can. Moreover, it limits the time horizon for replay mode to somewhere around Q3 of 2021 and that's with using the split option of the top half, to remain with the older cryptos.
3. For the beginner Pine enthusiasts, I recommend scimming through the script as it serves as a prime example of using key features, to name a few : Arrays, User Defined Functions, User Defined Types, For loops, Switches and Tables.
4. Beta and Alpha's benchmark instrument is BTC, due to cryptos volatility I saw no reason to use SPY or any other asset for that matter.
Autoregressive CloudHello,
I am releasing this indicator called the Autoregressive Cloud Indicator.
What it does:
The indicator performs an autoregression analysis on 3 price variables of a ticker, those being the High, the Low and the Close. It uses a 1-lag system and looks back at the previous close, high and low’s effect on the proceeding high, low and close. It then plots out the anticipated range for the ticker based on the autoregression analysis, as well as displays the lag-correlation (autocorrelation) in a table.
What is Autoregression analysis?
Autoregression is a modelling technique used to describe a time series based on its own past values. It assumes that the current value of a variable is a linear combination of its previous values and a random error term.
And what is autocorrelation?
Autocorrelation measures the correlation between a time series and its lagged values. It quantifies the degree to which the current value of a series is related to its past values at different lags, indicating any patterns or dependencies in the data over time. Autoregression and autocorrelation are closely related concepts used to analyze and model time series data.
So how does it work?
The indicator calculates autoregressive values for the close, high, and low prices of a security based on the specified lookback length (which is defaulted to 50). It then plots three sets of clouds representing the smoothed autoregressive values for each price component (done using the SMA function). The transparency of the clouds can be adjusted using the "Transparency" input. Additionally, the code includes a correlation table that displays the correlation coefficients between the lagged values of the close, high, and low prices. The table's position can be customized using the "Position" input.
The indicator defaults to the chart timeframe; however, you can manually adjust the indicator to display the range for whatever timeframe you would like. You can view the 30 minute, 15 or even hourly range on the 1 minute or 5 minute chart if you want.
The indicator will show the anticipated “true trading range” of the stock based on the autoregression and autocorrelation of all 3 variables:
Above is SPY on the 5 minute timeframe with 15 minute levels overlayed. Here, you can see the anticipated trading range for that 15 minute time period.
Using the Correlation Table:
The correlation table displays the Pearson Coefficient for all 3 autoregressions.
A positive correlation: A positive autocorrelation indicates a positive relationship between past and current values of a time series variable. It suggests that when the variable has a high value at a certain time, it is more likely to have a high value in the future, and when it has a low value, it is more likely to have a low value in the future. This positive autocorrelation can imply persistence or trend in the data, indicating that past values can provide useful information for predicting future values. The rule of thumb is anything over 0.5 is considered significant.
A positive correlation among all 3 variables also indicates an uptrend. If you see a strong positive (i.e. the values are all greater than 0.8), it indicates an incredibly decisive and strong uptrend.
A negative correlation: A negative autocorrelation indicates an inverse relationship between past and current values of a time series variable. It suggests that when the variable has a high value at a certain time, it is more likely to have a low value in the future, and vice versa. This negative autocorrelation can imply mean reversion or oscillatory behavior in the data, where extreme values tend to be followed by values closer to the average. It indicates that past values can provide useful information for predicting future values by anticipating a reversal in the direction of the variable. The rule of thumb is anything below or equal to -0.5 is considered significant.
A negative correlation among all 3 variables also indicates a downtrend. If you see a strong negative (i.e. the values are all less than or equal to -0.8), it indicates an incredibly decisive and strong downtrend.
Uses of the Indicator:
The indicator can be used for the following functions:
1. Day trading and scalping within an expected range;
2. Determining the strength or weakness of an uptrend or downtrend on various timeframes;
3. Determining the relationship between previous values and past performance and its effect on future performance;
4. Can alert to changes in trend direction in advance (you may see high, low or close turn negative before others, signifying that weakness is beginning to materialize in an uptrend, or inverse in a downtrend (value changes positive)).
Customizability:
SMA: The autoregression data is smoothed by a 3 period lookback. You can change this if you want, but in order for the indicator to present the true trading range, it is recommended to leave it at <= 3.
Lookback Length: This is the length of the lookback period for the autoregression and autocorrelation functions.
Transparency settings: You can adjust the transparency of the clouds manually.
Timeframe: You can adjust the timeframe, as explained above, to display the timeframe of interest. When you adjust the timeframe, the data will all reflect that timeframe and not necessarily the current TF you have open (i.e. you select 30 minutes while viewing it on the 5 minute, it will show the data for the 30 minute TF period).
Video Tutorial:
I have prepared a video outlining the indicator and also explaining the theory of autoregression/correlation. You can find it below:
Let me know any comments, questions or suggestions below.
Thank you for taking the time to read/watch and check out this indicator.
Safe trades everyone!