Average correlation of the values of a watchlist vs Index

My objective is that looking at all the values that are in a watchlist, in this case it is a watchlist that integrates all the values that are in the SPX, that looks at each one of these values and calculates the correlation of each one of them vs the spx and then makes me the average of the correlation of all values. I have the following code, but nothing comes out:

CorrLB = Param("Lookback", 756, 50, 756, 1);

wlnumber = 14; // GetOption("FilterIncludeWatchlist");
symlist = GetCategorySymbols(categoryWatchlist, wlnumber);

nm = Name();
spx = Foreign("^SPX", "Close");
spxLogC = log(spx / Ref(spx, -1));

Filter = Status("lastbarinrange");
SetSortColumns(1);

totalCorr = 0;
count = 0;

for (i = 0; (sym = StrExtract(symlist, i)) != ""; i++) {
    FrgClose = Foreign(sym, "C");
    FrgLogC = log(FrgClose / Ref(FrgClose, -1));
    Corr = Correlation(spxLogC, FrgLogC, CorrLB);
    totalCorr += Corr;
    count++;
}

avgCorr = totalCorr / count;

Title = "Correlación media de los valores en la watchlist con SPX: " + NumToStr(avgCorr, 4);

// Guarda la correlación media en un archivo compuesto
AddToComposite(avgCorr, "~AvgCorrelationWithSPX", "V");

_SECTION_BEGIN("Avg Correlation with SPX");
Plot(avgCorr, "Avg Correlation with SPX", colorBlue, styleLine | styleThick);
_SECTION_END();

I create this one, but the indicator appears empty again.... anybody can help me?

// Crear una función personalizada para calcular la correlación media
function CalcAvgCorrelation(symlist, index, lookback) {
    spx = Foreign("^SPX", "Close");
    spxLogC = log(spx / Ref(spx, -1));

    totalCorr = 0;
    count = 0;

    for (i = 0; (sym = StrExtract(symlist, i)) != ""; i++) {
        staticVarName = "Close_" + sym;
        FrgClose = StaticVarGet(staticVarName);

        if (FrgClose == 0) {
            FrgClose = Foreign(sym, "C");
            StaticVarSet(staticVarName, FrgClose);
        }

        FrgLogC = log(FrgClose / Ref(FrgClose, -1));
        Corr = Correlation(spxLogC, FrgLogC, lookback);
        totalCorr += Corr;
        count++;
    }

    return totalCorr / count;
}

// Parámetros y configuración
CorrLB = Param("Lookback", 60, 50, 756, 1);
wlnumber = 14;
symlist = GetCategorySymbols(categoryWatchlist, wlnumber);


indice = Foreign("^SPX", "Close");
// Calcular la correlación media en tiempo real
avgCorr = CalcAvgCorrelation(symlist, indice, CorrLB);

// Título y gráfico
Title = "Correlación media de los valores en la watchlist con SPX: " + NumToStr(avgCorr, 4);
Plot(avgCorr, "Avg Correlation with SPX", colorBlue, styleLine | styleThick);

You should be using composites and scan or StaticVarAdd and scan.

https://www.amibroker.com/guide/a_addtocomposite.html

You can use #pragma sequence to run pre-scan automatically.
Using Foreign sequentially in loop is bad idea as you don't benefit from multiple threads.

Thanks Tomasz, this is the code, and works!!!!

#pragma version(5.72)
#pragma noautofill
#pragma seq(1, 2)

function CalcAvgCorrelation(symlist, indexClose, lookback) {
    spxLogC = log(indexClose / Ref(indexClose, -1));
    count = 0;

    for (i = 0; (sym = StrExtract(symlist, i)) != ""; i++) {
        FrgClose = Foreign(sym, "C");
        FrgLogC = log(FrgClose / Ref(FrgClose, -1));
        Corr = Correlation(spxLogC, FrgLogC, lookback);

        // Añadir la correlación utilizando StaticVarAdd
        StaticVarAdd("TotalCorrelation", Corr);
        count++;
    }
    StaticVarSet("SymbolCount", count);
}

if (Status("action") == actionScan) {
    CorrLB = Param("Lookback", 60, 50, 756, 1);
    wlnumber = Param("Watchlist Number", 14, 0, 63, 1);

    symlist = GetCategorySymbols(categoryWatchlist, wlnumber);
    printf("Watchlist number: %g\n", wlnumber);
        printf("Symbols in watchlist: %s\n", symlist);

    // Obtener el cierre del índice
    indice = Foreign("^SPX", "close");

    // Calcular la correlación media en tiempo real
    CalcAvgCorrelation(symlist, indice, CorrLB);
}

// Obtener los resultados de las correlaciones desde StaticVar
totalCorrelations = StaticVarGet("TotalCorrelation");
symbolCount = StaticVarGet("SymbolCount");

// Calcular la correlación media
avgCorr = totalCorrelations / symbolCount;

// Título y gráfico
Title = "Correlación media de los valores en la watchlist con SPX: " + NumToStr(avgCorr, 4);
Plot(avgCorr, "Avg Correlation with SPX", colorBlue, styleLine | styleThick);

2 Likes

I don’t know how it “works” since you are using non existing pragmas

1 Like

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.