Rajandran R FollowCreator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

How to Create Correlation Matrix Table using Amibroker

1 min read

This article explores how to create a correlation matrix table between Bank Stocks(includes bank nifty in our case) using amibroker.

About Correlation

The correlation between any two stocks (or sets of variables) summarizes a relationship, whether or not there is any real-world connection between the two stocks. The correlation coefficient will always be between -1 and +1. These two extremes are considered perfect correlations. A negative coefficient means that the two stocks,, will move in opposite directions (if one stock increases, the other will decrease); a positive coefficient will mean that the two will move in the same direction (as one increases, the other will increase). And if Correlation is zero(perfectly uncorrelated) or almost zero then both the stock will behave independently

About Correlation Table

[wp_ad_camp_5]

Correlation table is a two-dimensional matrix that shows correlation coefficient between pairs of securities. The cells in the table are color-coded to highlight significantly positive and negative relationships.

Here i had taken randomly some Bank stocks from the NSE Pack and computed the correlation for the pairs using amibroker

Steps to Create Amibroker Correlation Matrix
1)Put the Bank Stocks(or your set of stocks) in Watchlist 0
2)Copy the Below AFL code and save as correlation.afl and save under the path C:program filesamibrokerformulascustomcorrelation.afl
3)Now open New Analysis (use AA-Automatic Analysis if you are using less than 5.4 version)
4)Select correlation AFL file
5)Now Press the Explore Buttom
6)Correlation table is ready

You can also vary the correlation period and can test for different set of stock pairs. This could be useful for pair trading strategy or for diversification of your portfolio by investing in less correlated pairs.so that an investor can reduce portfolio risk simply by holding instruments which are not perfectly correlated. In other words, investors can reduce their exposure to individual asset risk by holding a diversified portfolio of assets.

Rajandran R FollowCreator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Pivot Reversal Strategy is a popular in-built strategy in Tradingview Platform. Here I had attempted to convert the pinescript v5 to Amibroker AFL Code....

The IB Controller is an interface designed to facilitate automatic trading with AmiBroker and Interactive Brokers (IB) TWS (Trader Workstation). It serves as a...

OpenAlgo V1.0 is an open-source algorithmic trading platform to automate your trading strategies using Amibroker, Tradingview, Metatrader, Python etc. Designed with the modern trader...

23 Replies to “How to Create Correlation Matrix Table using Amibroker”

Dear sir

The following error was showing during explore.

WLNum = Param(“
————-^

Error 31.
Syntax error, unexpected $end, expecting ‘)’ or ‘,’

Pl rectify the problem
Thanks in advance

When you are trying to copy the text content from the website… there is always problem with the double quotes…
Delete the Double quotes in your AFL and Replace the double quotes with new one.

Will provide the AFL dowload link soon… that will reduce this kind of problem.

I chanced upon this site and there after the Co-relation Matrix. Good effort. Let me explore a bit.

From 27th April……ONWARDS
Free For Life time ODIN TO AB with All segment Cash, F&O Also Commodity /
//A free utiity which is quite faster than the available tools…
w w w. aamaadmisoftware.com
thanks to SHALABH_TYAGI…

Yeah once I download the zip file it works perfect.

Many Many Thanks for the same.

Do let me know what parameters and how we can the change in th AFL

Many Many Thanks for the same.

Do let me know what parameters and how we can the change in th AFL

@aliasgar
Correlation parameters are defined here. And by default the value is 8 here.

CorrPd = Param(“Correlation Period”,8,1,30,1);

Hai,

I am not getting any errors, at the same time i am not getting any results. tested for the period of up to 60 days. I used MetaStock EOD data; and the symbols will be in numbers than alphabets.

hi , i have enjoyed a lot reading ur blogs, thy r quite amazing. i just wanted to knw that is it possible for u to make the correlation data of all the nifty 50 stocks along with nifty and post it here. tht would be really gr8.

Res’d Sir

This correlation Matrix Table is awesome but is it possible that we can also see the combined charts of two scripts together

I also trade in Commodities & it would be great if we can see the correlated charts of two commodities

Waiting for your reply

Hey Raj,
You Rock!!! I have been calculating the correlation of some pairs in an excel and was wondering how to do this for more pairs without having to do the calculations in an excel. This has come as a dream come true.

Thnx a ton.

Hi,
I tried to explore the filter,but the analysis does not seem to produce any values.I am applying it to all quotes and in the filter have selected my watchlist of stocks.Please help.

Thanks for posting this. Just one comment, you probably want to use Status(“LastBarInRange”) as that will avoid errors or no results where the last backtest was out of alignment with the current Exploration dates.

Thats for your input alan. Will take in my future afl codes.

Thanks. A very useful bit of code!

However, you calculate correlation based on price instead of returns (or log returns – see attached link below). In order to calculate correlation based on log return replace ‘Corr = …’ with:

The most common rookie mistake is to calculate correlations based on price levels directly. For simple examples it may seem that the numbers make sense and don’t differ much from using returns, but there is an error factor present which may grow significant in some cases. … Instead of using absolute price levels, you should use log returns. You could argue that using simple percentage returns gives close enough results, but if you’re going to do it, let’s do it right.”

Presently it gives correlation between stocks for 30 days only. Is it possible to tweak it to get the correlation for use defined number of days, say 1 year or 2 years? It would be very useful to select pairs if you can do that.

Hi,

How to correlation NIFTY with watchlist stocks?

I do not receive output from this code? Only stock names are displayed

Dear sir

The following error was showing during explore.

WLNum = Param(“

————-^

Error 31.

Syntax error, unexpected $end, expecting ‘)’ or ‘,’

Pl rectify the problem

Thanks in advance

When you are trying to copy the text content from the website… there is always problem with the double quotes…

Delete the Double quotes in your AFL and Replace the double quotes with new one.

Will provide the AFL dowload link soon… that will reduce this kind of problem.

I chanced upon this site and there after the Co-relation Matrix. Good effort. Let me explore a bit.

From 27th April……ONWARDS

Free For Life time ODIN TO AB with All segment Cash, F&O Also Commodity /

//A free utiity which is quite faster than the available tools…

w w w. aamaadmisoftware.com

thanks to SHALABH_TYAGI…

Yeah once I download the zip file it works perfect.

Many Many Thanks for the same.

Do let me know what parameters and how we can the change in th AFL

Many Many Thanks for the same.

Do let me know what parameters and how we can the change in th AFL

@aliasgar

Correlation parameters are defined here. And by default the value is 8 here.

CorrPd = Param(“Correlation Period”,8,1,30,1);Hai,

I am not getting any errors, at the same time i am not getting any results. tested for the period of up to 60 days. I used MetaStock EOD data; and the symbols will be in numbers than alphabets.

hi , i have enjoyed a lot reading ur blogs, thy r quite amazing. i just wanted to knw that is it possible for u to make the correlation data of all the nifty 50 stocks along with nifty and post it here. tht would be really gr8.

Res’d Sir

This correlation Matrix Table is awesome but is it possible that we can also see the combined charts of two scripts together

I also trade in Commodities & it would be great if we can see the correlated charts of two commodities

Waiting for your reply

Hey Raj,

You Rock!!! I have been calculating the correlation of some pairs in an excel and was wondering how to do this for more pairs without having to do the calculations in an excel. This has come as a dream come true.

Thnx a ton.

Hi,

I tried to explore the filter,but the analysis does not seem to produce any values.I am applying it to all quotes and in the filter have selected my watchlist of stocks.Please help.

Thanks for posting this. Just one comment, you probably want to use Status(“LastBarInRange”) as that will avoid errors or no results where the last backtest was out of alignment with the current Exploration dates.

Thats for your input alan. Will take in my future afl codes.

Thanks. A very useful bit of code!

However, you calculate correlation based on price instead of returns (or log returns – see attached link below). In order to calculate correlation based on log return replace ‘Corr = …’ with:

Corr = Correlation(log(C/Ref(C,-1),log(Var2/Ref(Var2,-1),CorrPd);

Cf., http://www.followingthetrend.com/2012/08/how-to-build-correlation-matrices/

“Never Calculate Correlations Based on Prices

The most common rookie mistake is to calculate correlations based on price levels directly. For simple examples it may seem that the numbers make sense and don’t differ much from using returns, but there is an error factor present which may grow significant in some cases. … Instead of using absolute price levels, you should use log returns. You could argue that using simple percentage returns gives close enough results, but if you’re going to do it, let’s do it right.”

[Edit]

Corr = Correlation(log(C/Ref(C,-1)),log(Var2/Ref(Var2,-1)),CorrPd);

Thanks Andres will explore more on that.

Original article by ‘Herman’ posted here: http://www.amibroker.org/userkb/2007/04/24/creating-a-correlation-table/

give credit where credit is due!

Credit Provided at the end of the article

Presently it gives correlation between stocks for 30 days only. Is it possible to tweak it to get the correlation for use defined number of days, say 1 year or 2 years? It would be very useful to select pairs if you can do that.

Hi,

How to correlation NIFTY with watchlist stocks?

I do not receive output from this code? Only stock names are displayed