3
$\begingroup$

Lets say that you have the correlation of x,y and you have the standard deviations of x and y , how would you then find the covariance of x,y using the correlation of x,y and and the standard deviation of x,y .

The reason I would like to know this is I would like to take a correlation matrix and the standard deviations of all of the variables and use it to create a covariance matrix .

Thank you for your time , your help will be greatly appreciated

$\endgroup$

2 Answers 2

6
$\begingroup$

here is how to get covariance matrix from correlations:
enter image description here

$\endgroup$
2
$\begingroup$

The relationship between covariance, standard deviation and correlation is:

$$ corr(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y}$$

So to construct your matrix you will have the variances in the diagonal:

$$ cov(x,x) = corr(x,x) \times \sigma_x \times \sigma_x = 1 \times \sigma_x^2 = \sigma_x^2 $$

And for the covariances:

$$ cov(x,y) = corr(x,y) \times \sigma_x \times \sigma_y $$

Here is an example with the calculations in python:

import numpy as np
import pandas as pd
x = np.random.randint(1,4,20)
y = np.random.randint(1,4,20)
pd.DataFrame({'x': x, 'y': y}).describe()

enter image description here

std_x, std_y = pd.DataFrame({'x': x, 'y': y}).describe().loc['std']
corr_xy = np.corrcoef(x,y)[0][1]
print(f"Correlation between x and y: {corr_xy}")
var_x = std_x**2
print(f"Variance of x: {var_x}")
var_y = std_y**2
print(f"Variance of y: {var_y}")
cov_xy = corr_xy * std_x * std_y
print(f"Covariance between x and y: {cov_xy}")

Which would output:

Correlation between x and y: -0.20037977722310454
Variance of x: 0.6421052631578946
Variance of y: 0.7263157894736844
Covariance between x and y: -0.13684210526315793

Altought you could get these values directly with Numpy:

cov = np.cov(x,y)
print(cov)

[[ 0.64210526 -0.13684211]
[-0.13684211 0.72631579]]

Or using pandas:

pd.DataFrame({'x': x, 'y': y}).cov()

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.