To compute the covariance matrix of a set of assets, you first need to have the historical returns for each asset. Let’s assume that we have N assets, and we have T time periods of historical returns for each asset. The assets’ returns can be organized into a T × N matrix R, with each row corresponding to the returns for all assets at a specific time period. Let ri represent the return vector of the i-th asset.
Now, let’s define the covariance matrix. The (i, j) element of the covariance matrix represents the covariance between the returns of asset i and asset j.
The formula for the covariance between two assets i and j is:
$$\operatorname{Cov}(r_i, r_j) = \frac{1}{T-1}\sum_{t=1}^{T}(r_{i,t}-\bar{r}_i)(r_{j,t}-\bar{r}_j),$$
where ri, t is the return of asset i at time t, and r̄i and r̄j are the mean returns of assets i and j, respectively. Note that we use T − 1 instead of T to account for the "degrees of freedom" when estimating the covariance from a sample.
Now, you can compute the covariance matrix Σ as follows:
$$\Sigma = \begin{bmatrix}\operatorname{Cov}(r_1, r_1) & \cdots & \operatorname{Cov}(r_1, r_N)\\ \vdots & \ddots & \vdots\\ \operatorname{Cov}(r_N, r_1) & \cdots & \operatorname{Cov}(r_N, r_N)\end{bmatrix}.$$
For example, consider two assets, Asset A and Asset B, with the following monthly returns:
Asset A: 0.05, 0.02, 0.10, -0.01
Asset B: 0.03, -0.01, 0.15, -0.02
Calculating the mean returns for each asset:
r̄A = 0.04, r̄B = 0.0375.
Let’s compute the covariance matrix for Asset A and Asset B:
$$\begin{aligned}
\Sigma = & \frac{1}{3}\begin{bmatrix}(0.05-0.04)(0.05-0.04) & (0.05-0.04)(0.03-0.0375)\\ (0.05-0.04)(0.03-0.0375) & (0.03-0.0375)(0.03-0.0375)\end{bmatrix} \\
& + \frac{1}{3}\begin{bmatrix}(0.02-0.04)(0.02-0.04) & (0.02-0.04)(-0.01-0.0375)\\ (0.02-0.04)(-0.01-0.0375) & (-0.01-0.0375)(-0.01-0.0375)\end{bmatrix} \\
& + \frac{1}{3}\begin{bmatrix}(0.10-0.04)(0.10-0.04) & (0.10-0.04)(0.15-0.0375)\\ (0.10-0.04)(0.15-0.0375) & (0.15-0.0375)(0.15-0.0375)\end{bmatrix} \\
& + \frac{1}{3}\begin{bmatrix}(-0.01-0.04)(-0.01-0.04) & (-0.01-0.04)(-0.02-0.0375)\\ (-0.01-0.04)(-0.02-0.0375) & (-0.02-0.0375)(-0.02-0.0375)\end{bmatrix}.\end{aligned}$$
Computing the entries of the covariance matrix, we get:
$$\Sigma = \begin{bmatrix}0.002033 & 0.003458\\ 0.003458 & 0.005075\end{bmatrix}.$$
And there you have it! The covariance matrix for assets A and B. Note that the diagonal elements of the covariance matrix represent the variance of each asset’s returns. In practice, you would likely be dealing with many more assets and larger return datasets, and you can make use of software such as Python’s NumPy library or MATLAB to compute the covariance matrix efficiently.