How do I simulate correlated returns I can reproduce?
Generate reproducible random returns with a seeded generator, impose a target correlation matrix with a Cholesky factor, and check the correlations and volatilities of the simulated returns.
After this lesson, you can simulate daily returns with chosen correlations and volatilities and reproduce them in a later run.
How do I draw the same random numbers again?
np.random.default_rng(42) starts a random number generator from the seed 42, and a second generator from the same seed gives the same draws. .standard_normal((10000, 3)) draws 10,000 rows and three columns from a normal distribution with a mean of 0 and a standard deviation of 1, one column per made-up stock, AAA, BBB and CCC. np.array_equal checks that two arrays agree in every cell.
The following box draws the numbers twice from the same seed.
A generator that is not restarted continues its sequence, so a second call on it gives new draws.
How do I give the draws a target correlation?
Multiplying each row of independent draws by the transpose of the Cholesky factor of the target correlation matrix gives draws with that correlation, and multiplying each column by a volatility gives returns. AAA’s correlation with BBB is 0.6, so BBB’s return takes 0.6 of AAA’s draw and 0.8 of its own.
\[
C = L L^\top, \qquad y_t = z_t L^\top
\]
Here \(C\) is the target correlation matrix, \(L\) its Cholesky factor, a lower triangular matrix, \(z_t\) the row of three independent draws on day \(t\) and \(y_t\) the correlated draws. For BBB, \(y_{t,\text{BBB}} = 0.6\,z_{t,\text{AAA}} + 0.8\,z_{t,\text{BBB}}\).
np.linalg.cholesky(target) returns \(L\), @ multiplies matrices and .T transposes, as in the lesson on portfolio returns. Multiplying by volatility scales each column, as in the lesson on broadcasting, here to daily volatilities of 1%, 2% and 1.5%, so the returns are in percent.
The following box computes the Cholesky factor and the returns.
BBB’s return on day 1 is \(2 \times (0.6 \times 0.305 + 0.8 \times (-1.040)) = -1.298\%\). A correlation matrix must be positive definite for cholesky to work, and correlations between −1 and 1 alone do not guarantee that.
How close are the sample correlations and volatilities?
The sample correlations are 0.607, 0.310 and 0.217 against targets of 0.6, 0.3 and 0.2, and the sample volatilities are 1.008%, 2.014% and 1.511%. The gaps come from the finite number of draws.
np.corrcoef(returns, rowvar=False) correlates the columns, and np.std(returns, axis=0, ddof=1) gives the sample standard deviation of each column.
The following box prints the sample correlations and volatilities.
Compute the sample correlations of the first 100 days. You should see 0.343 for BBB and CCC, further from the target of 0.2, because 100 days vary more than 10,000.