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)
This exercise is part of the course
Introduction to R for Finance
Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.
In this chapter, you will learn all about vectors and matrices using historical stock prices for companies like Apple and IBM. You will then be able to feel confident creating, naming, manipulating, and selecting from vectors and matrices.
Exercise 1: What is a vector?Exercise 2: c()ombineExercise 3: Coerce itExercise 4: Vector names()Exercise 5: Visualize your vectorExercise 6: Vector manipulationExercise 7: Weighted average (1)Exercise 8: Weighted average (2)Exercise 9: Weighted average (3)Exercise 10: Vector subsettingExercise 11: Matrix - a 2D vectorExercise 12: Create a matrix!Exercise 13: Matrix <- bind vectorsExercise 14: Visualize your matrixExercise 15: cor()relationExercise 16: Matrix subsettingWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.