I am trying to compute pairwise correlations over rolling windows for n= 40 variables where all rolled pairwise correlations for 2 given variables are saved in a new variable.
My dataset has the following structure:
Date V1 V2 V3 . . .
01/01/2009 0.3 0.6 0.5
02/01/2009 0.1 0.5 0.2
03/01/2009 0.7 0.1 0.1
.
.
.
The following code does the trick. However, it fails to ignore the lower diagonal of the correlation matrix (it estimates twice the correlation between vars + once the 1s on the diagonal):
ds (Date), not
gl vars `r(varlist)'
local i = 0
local j = 0
foreach current_variable1 in $vars {
local i = `i'+1
foreach current_variable2 in $vars {
local j = `j'+1
if (`j' > `i') {
mvcorr `current_variable1' `current_variable2', ///
generate(corr_`current_variable1'_`current_variable2') window(60) force
}
}
}
In particular the if
condition on (j > i
) intended to capture the doubled calculation of each pairwise correlation fails to do so. Including the if
condition in the mvcorr
yields only the error message 'no observations'
.
What could be the solution for this issue?
@William Lisowski debugged your code in a comment, but you can simplify the whole procedure.
Create the tuples beforehand using the user-written command
tuples
(ssc install tuples
).@William's advice leads to the same result: