Spearman Rank Correlation CoefficientI'm pleased to introduce this script in honor of the new array functions introduced to PineScript version 4.0. This update is a long time coming and opens the door to amazing scripting possibilities!
Definition
Named after Charles Spearman and denoted by the Greek letter ‘ ρ ’ (rho), the Spearman rank correlation coefficient is the nonparametric version of the Pearson correlation coefficient . Use the Spearman rank correlation when you have two ranked variables, and you want to see whether the two variables covary. That is, as one variable increases/decreases, the other variable tends to increase/decrease respectively.
It is best used to discover if two variables (and in this first version of the indicator, two ticker symbols) increase and decrease together. There are advantages to using this version of correlation vs. the Pearson R.
Interpretation
The value oscillates between +1 and -1.
A value of +1 means the two variables are perfectly correlated, that is they are increasing and decreasing together in perfect harmony.
A value of -1 means the two variables exhibit a perfect negative correlation, that is they increase and decrease oppositely.
A value of zero means the two variables are not correlated at all (noise).
상관계수 (CC)
Optimal Weighted Moving AverageThe Optimal Weighted Moving Average was created by Thomas Hutchinson and Peter G. Zhang, Ph.D. (Stocks & Commodities V. 11:12 (500-505)) and it is very similar to a classic weighted moving average but it uses the correlation between the input and the optimal weighted moving average output to use as the weights. Buy when the line turns green and sell when it turns red.
Let me know if you would like to see me publish any other scripts or if you want something custom done!
Correlation MatrixIn financial terms, 'correlation' is the numerical measure of the relationship between two variables (in this case, the variables are Forex pairs).
The range of the correlation coefficient is between -1 and +1. A correlation of +1 indicates that two currency pairs will flow in the same direction.
A correlation of -1 indicates that two currency pairs will move in the opposite direction.
Here, I multiplied correlation coefficient by 100 so that it is easier to read. Range between 100 and -100.
Color Coding:-
The darker the color, the higher the correlation positively or negatively.
Extra Light Blue (up to +29) : Weak correlation. Positions on these symbols will tend to move independently.
Light Blue (up to +49) : There may be similarity between positions on these symbols.
Medium Blue (up to +75) : Medium positive correlation.
Navy Blue (up to +100) : Strong positive correlation.
Extra Light Red (up to -30) : Weak correlation. Positions on these symbols will tend to move independently
Light Red (up to -49) : There may be similarity between positions on these symbols.
Dark Red: (up to -75) : Medium negative correlation.
Maroon: (up to -100) : Strong negative correlation.
BTC Correlation CoefficientAn indicator that only calculates and displays the correlation coefficient with bitfinex:BTCUSD close.
By changing the settings, you can calculate any chart and correlation coefficient
0.7 to 1.0 There is a fairly strong positive correlation
0.4 to 0.7 Positive correlation
0.2 to 0.4 with a weak positive correlation
-0.2 ~ 0 ~ 0.2 Little correlation
-0.4 to -0.2 Weak negative correlation
-0.7 to -0.4 Negative correlation
-1 to -0.7 Significantly negative correlation
bitfinex:BTCUSDのcloseとの相関係数を計算して表示するだけのインジケーターです。
設定を変更すれば任意のチャートと相関係数の計算ができます
0.7 ~ 1.0 かなり強い正の相関がある
0.4 ~ 0.7 正の相関がある
0.2 ~ 0.4 弱い正の相関がある
-0.2 ~ 0 ~ 0.2 ほとんど相関がない
-0.4 ~ -0.2 弱い負の相関がある
-0.7 ~ -0.4 負の相関がある
-1 ~ -0.7 かなり強い負の相関がある
Dual Purpose Pine Based CorrelationThis is my "Pine-based" correlation() function written in raw Pine Script. Other names applied to it are "Pearson Correlation", "Pearson's r", and one I can never remember being "Pearson Product-Moment Correlation Coefficient(PPMCC)". There is two basic ways to utilize this script. One is checking correlation with another asset such as the S&P 500 (provided as a default). The second is using it as a handy independent indicator correlated to time using Pine's bar_index variable. Also, this is in fact two separate correlation indicators with independent period adjustments, so I guess you could say this indicator has a dual purpose split personality. My intention was to take standard old correlation and apply a novel approach to it, and see what happens. Either way you use it, I hope you may find it most helpful enough to add to your daily TV tool belt.
You will notice I used the Pine built-in correlation() in combination with my custom function, so it shows they are precisely equal, even when the first two correlation() parameters are reversed on purpose or by accident. Additionally, there's an interesting technique to provide a visually appealing line with two overlapping plot()s combined together. I'm sure many members may find that plotting tactic useful when a bird's nest of plotting is occurring on the overlay pane in some scenarios. One more thing about correlation is it's always confined to +/-1.0 irregardless of time intervals or the asset(s) it is applied to, making it a unique oscillator.
As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette". For those of you who are newcomers to Pine Script, this code release may also help you comprehend the "Power of Pine" by employing advanced programming techniques in Pine exhibiting code utilization in a most effective manner. One of the many tricks I applied here was providing floating point number safeties for _correlation(). While it cannot effectively use a floating point number, it won't error out in the event this should occur especially when applying "dominant cycle periods" to it, IF you might attempt this.
NOTICE: You may have observed there is a sqrt() custom function and you may be thinking... "Did he just sick and twistedly overwrite the Pine built-in sqrt() function?" The answer is... YES, I am and yes I did! One thing I noticed, is that it does provide slightly higher accuracy precision decimal places compared to the Pine built-in sqrt(). Be forewarned, "MY" sqrt() is technically speaking slower than snail snot compared to the native Pine sqrt(), so I wouldn't advise actually using it religiously in other scripts as a daily habit. It is seemingly doing quite well in combination with these simple calculations without being "sluggish". Lastly, of course you may always just delete the custom sqrt() function, via Pine Editor, and then the script will still operate flawlessly, yet more efficiently.
Features List Includes:
Dark Background - Easily disabled in indicator Settings->Style for "Light" charts or with Pine commenting
AND much, much more... You have the source!
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
Hashem Correlation CoefficientCorrelation Coefficient
Core Code from: www.tradingview.com
This indicator Show Correlation between the Current Ticker & timeframe and a Customizable Ticker. After adding the indicator you can change the second ticker in the settings.
The Correlation Coeff is between -1 to 1 which 1 means 100% correlation and -1 means -100% correlation ( Inverse Correlation ).
The color of the area changes when:
Blue : CC > 0.5
Aqua : CC > 0.75
Purple : CC < -0.5
Red : CC < -0.75
Function : Multiple Correlation
This script was written to calculate the correlation coefficient (Adjusted R-Squared) for one dependent and two independent variables.(3-way)
Pearson correlation method was used with exponential moving averages as the correlation calculation method.
Use your source ( i use "close" generally ) as the dependent variable.
Inspired by this article : www.real-statistics.com
The Adjusted R-Squared coefficient is used as output, but the R-Squared coefficient is also available in the code.
Adjusted R-Squared is often used for multiple correlations.
It also gives better results in large samples.
Here is the article about the difference of the two coefficients : www.investopedia.com
I wrote this function to increase the efficiency of my Dow Factor I used before.
When my research is over, I will apply the 3-factor correlation to my scripts.
I hope that I will achieve more efficient indicators and oscillators and even strategies.
In this command, I gave a few variable values and plotted them as an example.
I hope this function is useful in your work.
Finally, you can use periods as mutable variables.
The function is recovered from integer loads.
Best regards. Noldo
Kaufman Adaptive Correlation OscillatorIntroduction
The correlation oscillator is a technical indicator that measure the linear relationship between the market closing price and a simple increasing line, the indicator is in a (-1,1) range and rise when price is up-trending and fall when price is down-trending. Another characteristic of the indicator is its inherent smoothing which provide a noise free (to some extent) oscillator.
Such indicator use simple moving averages as well as estimates of the standard deviation for its calculation, but we can easily make it adaptive, this is why i propose this new technical indicator that create an adaptive correlation oscillator based on the Kaufman adaptive moving average.
The Indicator
The length parameter control the period window of the moving average, larger periods return smoother results while having a low kurtosis, which mean that values will remain around 1 or -1 a longer period of time. Pre-filtering apply a Kaufman adaptive moving average to the input, which allow for a smoother output.
No pre-filtering in orange, pre-filtering in yellow, period = 100 for both oscillators.
If you are not aware of the Kaufman adaptive moving average, such moving average return more reactive results when price is trending and smoother results when price is ranging, this also apply for the proposed indicator.
Conclusion
Classical correlation coefficients could use this approach, therefore the linear relationships between any variables could be measured. The fact that the indicator is adaptive add a certain potential, however such combination make the indicator have the drawback of kama + the correlation oscillator, which might appear at certain points.
Thanks for reading !
Correlation MATRIX (Flexible version)Hey folks
A quick unrelated but interesting foreword
Hope you're all good and well and tanned
Me? I'm preparing the opening of my website where we're going to offer the Algorithm Builder Single Trend, Multiple Trends, Multi-Timeframe and plenty of others across many platforms (TradingView, FXCM, MT4, PRT). While others are at the beach and tanning (Yes I'm jealous, so what !?!), we're working our a** off to deliver an amazing looking website and great indicators and strategies for you guys.
Today I worked in including the Trade Manager Pro version and the Risk/Reward Pro version into all our Algorithm Builders. Here's a teaser
We're going to have a few indicators/strategies packages and subscriptions will open very soon.
The website should open in a few weeks and we still have loads to do ... (#no #summer #holidays #for #dave)
I see every message asking me to allow access to my Algorithm Builders but with the website opening shortly, it will be better for me to manage the trials from there - otherwise, it's duplicated and I can't follow all those requests
As you can probably all understand, it becomes very challenging to publish once a day with all that workload so I'll probably slow down (just a bit) and maybe posting once every 2/3 days until the website will be over (please forgive me for failing you). But once it will open, the daily publishing will resume again :) (here's when you're supposed to be clapping guys....)
While I'm so honored by all the likes, private messages and comments encouraging me, you have to realize that a script always takes me about 2/3 hours of work (with research, coding, debugging) but I'm doing it because I like it. Only pushing the brake a bit because of other constraints
INDICATOR OF THE DAY
I made a more flexible version of my Correlation Matrix .
You can now select the symbols you want and the matrix will update automatically !!! Let me repeat it once more because this is very cool... You can now select the symbols you want and the matrix will update automatically :)
Actually, I have nothing more to say about it... that's all :) Ah yes, I added a condition to detect negative correlation and they're being flagged with a black dot
Definition : Negative correlation or inverse correlation is a relationship between two variables whereby they move in opposite directions.
A negative correlation is a key concept in portfolio construction, as it enables the creation of diversified portfolios that can better withstand portfolio volatility and smooth out returns.
Correlation between two variables can vary widely over time. Stocks and bonds generally have a negative correlation, but in the decade to 2018, their correlation has ranged from -0.8 to 0.2. (Source : www.investopedia.com
See you maybe tomorrow or in a few days for another script/idea.
Be sure to hit the thumbs up to cheer me up as your likes will be the only sunlight I'll get for the next weeks.... because working on building a great offer for you guys.
Dave
____________________________________________________________
- I'm an officially approved PineEditor/LUA/MT4 approved mentor on codementor. You can request a coaching with me if you want and I'll teach you how to build kick-ass indicators and strategies
Jump on a 1 to 1 coaching with me
- You can also hire for a custom dev of your indicator/strategy/bot/chrome extension/python
Correlation Matrix by DaveattHi everyone
A co-pinescripter friend told me this was impossible to do and we bet a free dinner tomorrow. Guess who's going to be invited to a very fancy restaurant tomorrow :) :) :) (hint: not him)
What's the today script is about?
This script is based on this MT4 correlation matrix
Asset correlation is a measure of how investments move in relation to one another and when. ... Under what is known as modern portfolio theory, you can reduce the overall risk in an investment portfolio and even boost your overall returns by investing in asset combinations that are not correlated.
I did it because it wasn't existing before with this format. What I discovered was only correlations shown as plot lines... #this #is #not #pretty
How does it work?
The correlation matrix will not be based on the current asset of the chart BUT will be based on the current timeframe (confusing? if yes, read it again until you'll get it)
- Numbers of bars back: numbers of bars used for the correlation calculation
- High correlation level: Correlation upper threshold. If above, then the correlation will be green
- Low correlation level: Correlation lower threshold. If below, then the correlation will be red
If the correlation is between the high and low levels, then it will be displayed in orange
- FOREX/INDEX: You can choose between displaying the correlation matrix between 3 FOREX or 3 INDEX assets
Also...
So far the scale doesn't respond too well to the matrix so you'll have to adapt the scale manually. I'll publish a V2 if I'll find a way to solve this issue from the code directly #new #challenge
A quick final note on why I'm sharing so much?
It challenges me to think out of the norm, get out of my bubble and explore areas of Pinescript that I still don't know. This "a script a day" challenge allows me to speed up my learning curve on Pinescript by a billion factor (and I get a few interesting gigs as well)
Let's bring this indicator to 100 LIKES guys !!!!! I think it deserves it, don't you think? :)
PS
Before all copy/pasters will add a version with crypto tomorrow, don't bother, I already did it and will post it in a few minutes for FREE :p
____________________________________________________________
Be sure to hit the thumbs up as it shows me that I'm not doing this for nothing and will motivate to deliver more quality content in the future.
- I'm an officially approved PineEditor/LUA/MT4 approved mentor on codementor. You can request a coaching with me if you want and I'll teach you how to build kick-ass indicators and strategies
Jump on a 1 to 1 coaching with me
- You can also hire for a custom dev of your indicator/strategy/bot/chrome extension/python
Light LSMAEstimating the LSMA Without Classics Parameters
I already mentioned various methods in order to estimate the LSMA in the idea i published. The parameter who still appeared on both the previous estimation and the classic LSMA was the sample correlation coefficient. This indicator will use an estimate of the correlation coefficient using the standard score thus providing a totally different approach in the estimation of the LSMA. My motivation for such indicator was to provide a different way to estimate a LSMA.
Standardization
The standard score is a statistical tool used to measure at how many standard deviations o a data point is bellow or above its mean. It can also be used to rescale variables, this conversion process is called standardizing or normalizing and it will be the basis of our estimation.
Calculation : (x - x̄)/o where x̄ is the moving average of x and o the standard deviation.
Estimating the Correlation Coefficient
We will use standardization to estimate the correlation coefficient r . 1 > r > -1 so in (y - x̄)/o we want to find y such that y is always above or below 1 standard deviation of x̄ , i had for first idea to pass the price through a band-stop filter but i found it was better to just use a moving average of period/2 .
Estimating the LSMA
We finally rescale a line through the price like mentioned in my previous idea, for that we standardize a line and we multiply the result by our correlation estimation, next we multiply the previous calculation by the price standard deviation, then we sum this calculation to the price moving average.
Comparison of our estimate in white with a LSMA in red with both period 50 :
Working With Different Independents Variables
Here the independent variable is a line n (which represent the number of data point and thus create a straight line) but a classic LSMA can work with other independent variables, for exemple if a LSMA use the volume as independent variable we need to change our correlation estimate with (ȳ - x̄)/ô where ȳ is the moving average of period length/2 of y, y is equal to : change(close,length)*change(volume,length) , x̄ is the moving average of y of period length , and ô is the standard deviation of y. This is quite rudimentary and if our goal is to provide a easier way to calculate correlation then the product-moment correlation coefficient would be more adapted (but less reactive than the sample correlation) .
Conclusion
I showed a way to estimate the correlation coefficient, of course some tweaking could provide a better estimate but i find the result still quite close to the LSMA.
Partial CorrelationComputes the partial correlation between 2 symbols while removing the influence of a third.
Ex.:
Computes the correlation between AAPL and AMZN while removing the influence of SPX.
Asset Correlation Tool v2Correlation amongst assets is the degree to which they move in tandem. This indicator measures correlation between different assets. Why is that important?
To any investor diversification is a very important technique for reducing risk. The problem is that most misunderstand it. Most people tend to think diversification is achieved simply by investing in a variety of assets instead of just a few.
This is wrong.
The whole point of diversification is to be invested in assets with different growth drivers. A portfolio consisting of +20 highly correlated assets (Your cryptobags, probably) is the OPPOSITE of diversification. This is taking on risk without being compensated for it. Which is contradictory to the fundamental reason for why you do invest in assets.
Proper diversification is achieved when you reduce the correlation between the assets in your portfolio.
HOW TO USE
To use this tool, add it to your favorites and then add it to your chart. It will by default only show the correlation between an altcoin index and the current chart symbol.
If you go to its settings you can add its correlation to the stock market, gold and you can also easily customize it to any security you want.
0.5 to 1.0: Strong positive correlation
Around 0: Little to no correlation
-0.5 to -1.0: Strong negative correlation
Took a few hours to build this one. It would be super helpful if you can take a look at the index I used - I'm convinced there are better and more accurate methods to this one. But best I could come up with
Later I will evolve this one to an oscillator that measures the relation between cross coin correlations and volatility. Inspired by some great work by @cryptorae
If you have any requests or ideas please shoot
Updates v0.2
- Added altcoin index
- Changed some calculations
- Restructed code
Asset Correlation ToolCorrelation amongst assets is the degree to which they move in tandem.
Diversification is a technique for reducing risk. Most people tend to think this is achieved simply by investing in a variety of assets instead of just a few. This is wrong.
Proper diversification is achieved when you reduce the correlation between the assets in your portfolio.
0.5 to 1.0: Strong positive correlation
Around 0: Little to no correlation
-0.5 to -1.0: Strong negative correlation
Took a few hours to build this one. Later I will add an index for crypto (large cap) and I'll play around with different ways of presenting the data.
If you have any requests or ideas please shoot
Kendall Rank Correlation CoefficientKendall Rank Correlation Coefficient script.
This way to measure the ordinal association between two measured quantities described by Maurice Kendall (1938, Biometrika, 30 (1–2): 81–89, "A New Measure of Rank Correlation").
In this script I compare Kendall Coefficient and Pearson Coefficient (using built-in "correlation" function).
Volume Share - Bitcoin Retail % [cryptorae] [NeoButane edit]This is originally @cryptorae's script with modifications. A great explanation of function can be found on their Twitter.
Original comments:
Follow me @cryptorae on twitter
H/T @AureliusBTC and @cryptom173 for tweaks and assistance
Added three more setups:
Correlation oscillator
Raw volume
Percent change for the two sets of volume ("retail" and "nonretail"), independent of each other
The correlation oscillator shows that inverse/lowering correlation can result in price increasing, acting as if oversold; the same can be said when correlation increases.
"Raw" volume is the volume tickers without changing anything about them.
Percent change is the % difference from the current bar and bar .
Color coded the columns based on percent levels; <15%/<25%/<35%/<39%/<55%/>55%. <46% created too much noise for an indicator. 36% - 38.99% is red to alert possible trend changes in the ratio.
(Overly) summarized use of the original script:
The volume bars up -> Common fiat onramp exchanges have good volume that signal an influx of new investors
The volume bars down -> The majority of volume is on big boy exchanges where retail/new investors aren't likely to be trading
Correlate 3 - Correlation IndicatorThe code in contains a simple correlation indicator that can be used as an alternative to Tradingview’s built-in “Correlation Coefficient” indicator. The indicator allows users to correlate up to 3 separate instruments on the same subplot. This allows you, for example, to easily see the correlation of your instrument with stocks, bonds and FX. Alternatively, a user can also see the correlation with sector, industry peers or any other data available in Tradingview.
Features
Level Guides to easily see the key correlation coefficient levels
Multi-instrument:
Correlation Candles [DW]This is a simple study designed to visualize price correlations between securities.
CorrelationGraph shows level of correlation between current source and another one and track current value of it. User can select source for comparison, graph period and number of candles for calculation, enter level of significal correlation (+-0.65 by default). Grapf contains 4 plots: Correlation - current level of correlation, Zero line , +Corr_level - minimum level of significant positive correlation, -Corr_level -maximum level of significant negative correlation between 2 sources.