Get full access to all Data Science, Machine Learning, and AI courses built for finance professionals.
One-time payment - Lifetime access
Or create a free account to start
A step-by-step guide covering Python, SQL, analytics, and finance applications.
Or create a free account to access more
Get full access to all Data Science, Machine Learning, and AI courses built for finance professionals.
One-time payment - Lifetime access
Or create a free account to start
A step-by-step guide covering Python, SQL, analytics, and finance applications.
Or create a free account to access more
In this article, we will learn how to create a covariance matrix in R. As we know, covariance measures the comovement between two variables i.e. the amount by which the two random variables show movement or change together. In other words, it represents the degree to which two variables are linearly associated.
A covariance matrix becomes useful when we have many variables in a dataset, and we want to know the covariance between each of those variables. It's a square matrix that shows covariances between different variables.
Let's learn about how to create a Covariance Matrix in R and interpret the results.
For our example, we will create the covariance matrix for three stock indices, namely, S&P 500, Dow Jones, and NASDAQ. We will fetch the historical data for these three indices from a package called qrmdata. In the process of creating covariance matrix, we will also show some important data manipulations that we need to perform to get the right results.
Step 1: Install and Load Packages
The first step is to install and load the two packages, qrmdata and xts
1# Install and load the necessary packages
2install.packages(c("qrmdata", "xts"))
3library(qrmdata)
4library(xts)
5Step 2: Load the stock index data
We will now load the stock index data for the three indices from the qrmdata package
1# Load the stock index data
2data("SP500")
3data("DJ")
4data("NASDAQ")
5Step 3: Prepare the data
The data for each index will be loaded in R as xts objects. We need to do a few things to make it ready for creating covariance matrix. The first thing we do is convert each xts object into a dataframe. Next we merge all dataframes into a single dataframe. We update the column names to be SP500, DJ, and NASDAQ. We then clean this data by omitting rows containing NA values.
1# Convert to data frames and add Date as a column
2SP500_df <- data.frame(Date = index(SP500), SP500 = coredata(SP500))
3DJ_df <- data.frame(Date
Step 4: Calculate daily returns
What we have in this data is the daily index values. Covariance is generally calculated on the returns (percentage changes) rather than absolute values. This is important because returns standardize the values and make them comparable. So, our next step is to calculate daily returns on each index.
1# Calculate daily returns
2clean_data$SP500_Returns <- c(NA, diff(log(clean_data$SP500))) * 100
3clean_data
Step 5: Calculate Covariance Matrix
The final step is to create the covariance matrix. We will use the cov() function for this.
1# Calculate the covariance matrix
2cov_mat <- cov(returns, use = "complete.obs")
3
4# Print the covariance matrix
5print(cov_matIn our example, the resulting covariance matrix is as follows:
1> print(cov_mat)
2 SP500_Returns DJ_Returns NASDAQ_Returns
3SP500_Returns 1.351521 1.273071 1.613118
4DJ_Returns 1.273071 1.285778 1.412438
5The numbers on the diagonals are the variances of each index:
1.351521 is the variance of the returns for the SP500 index1.285778 is the variance of the returns for the DJ index2.877315 is the variance of the returns for the NASDAQ indexThe non-diagonal numbers represent the covariances between different indexes:
1.273071 is the covariance between the returns of the SP500 and DJ indices1.613118 is the covariance between the returns of the SP500 and NASDAQ indices1.412438 is the covariance between the returns of the DJ and NASDAQ indicesRemember that a positive covariance indicates that the two indices increase/decrease simultaneously, while a negative number indicates that they move inversely (when one increases, the other decreases).