cor()relation
Did you notice the relationship between the two stocks? It seems that when Apple's stock moves up, Microsoft's does as well. One way to capture this kind of relationship is by finding the correlation between the two stocks. Correlation is a measure of association between two things, here, stock prices, and is represented by a number from -1 to 1. A 1 represents perfect positive correlation, a -1 represents perfect negative correlation, and 0 correlation means that the stocks move independently of each other. Correlation is a common metric in finance, and it is useful to know how to calculate it in R.
The cor()
function will calculate the correlation between two vectors, or will create a correlation matrix when given a matrix.
cor(apple, micr)
[1] 0.9477011
cor(apple_micr_matrix)
apple micr
apple 1.0000000 0.9477011
micr 0.9477011 1.0000000
cor(apple, micr)
simply returned the correlation between the two stocks. A large correlation of .9477 hints that Apple and Microsoft's stock prices move closely together. cor(apple_micr_matrix)
returned a matrix that shows all of the possible pairwise correlations. The top left correlation of 1 is the correlation of Apple with itself, which makes sense!
This is a part of the course
“Introduction to R for Finance”
Exercise instructions
- The vectors of stock prices for
apple
,micr
, andibm
are in your workspace. - Calculate the correlation between
apple
andibm
. - Create a matrix of
apple
,micr
, andibm
, in that order, namedstocks
usingcbind()
. - Try to run the code for the correlation of all three stocks. Notice how it fails when using more than 2 vectors!
- Rewrite the failing code to use the
stocks
matrix instead. Correlation matrices are very powerful when you have many stocks!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Correlation of Apple and IBM
# stock matrix
stocks <-
# cor() of all three
cor(apple, micr, ibm)