← Back to Financial Concepts
Portfolio Theory

Correlation Visualizer

Correlation measures linear relationship: +1 = perfect positive, -1 = perfect negative, 0 = uncorrelated. Diversification works best with low correlations.

The Formula

ρ(X,Y) = Cov(X,Y) / (σX × σY)

How It Works

// Calculate correlation between two assets
function correlation(asset1, asset2) {
    const n = asset1.length;
    const mean1 = asset1.reduce((a,b)=>a+b,0)/n;
    const mean2 = asset2.reduce((a,b)=>a+b,0)/n;
    
    let cov = 0, var1 = 0, var2 = 0;
    for (let i = 0; i < n; i++) {
        const d1 = asset1[i] - mean1;
        const d2 = asset2[i] - mean2;
        cov += d1 * d2;
        var1 += d1 * d1;
        var2 += d2 * d2;
    }
    
    return cov / Math.sqrt(var1 * var2);
}

// Build correlation matrix for portfolio
function correlationMatrix(assets) {
    const n = assets.length;
    const matrix = Array(n).fill().map(()=>Array(n));
    
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            matrix[i][j] = correlation(assets[i], assets[j]);
        }
    }
    return matrix;
}