mcovarTopN

Syntax

mcovarTopN(X, Y, S, window, top, [ascending=true], [tiesMethod='oldest'])

Please see mTopN for the parameters and windowing logic.

Details

Within a sliding window of given length (measured by the number of elements), the function stably sorts X and Y by S in the order specified by ascending, then calculates the moving covariance of the first top pairs of elements in X and Y.

Returns

The result is of type DOUBLE, with the same form as the input parameters.

Examples

Using IBM stock as an example, simulate index return rates, stock return rates, and trading volumes for six consecutive trading days:

symbol = take(`IBM, 6)
tradeDate = 2024.01.02 2024.01.03 2024.01.04 2024.01.05 2024.01.08 2024.01.09
indexRet = [0.6, 1.1, -0.2, 0.9, 1.3, 0.4]
stockRet = [0.9, 1.7, -0.1, 1.4, 1.9, 0.8]
tradeVolume = [520, 860, 610, 940, 650, 880]

stockDaily = table(symbol, tradeDate, indexRet, stockRet, tradeVolume)
stockDaily;

Output:

symbol tradeDate indexRet stockRet tradeVolume
IBM 2024.01.02 0.6 0.9 520
IBM 2024.01.03 1.1 1.7 860
IBM 2024.01.04 -0.2 -0.1 610
IBM 2024.01.05 0.9 1.4 940
IBM 2024.01.08 1.3 1.9 650
IBM 2024.01.09 0.4 0.8 880

Over the most recent four trading days, select the top two trading days by trading volume and calculate the covariance of stockRet and indexRet:

mcovarTopN(X=indexRet, Y=stockRet, S=tradeVolume, window=4, top=2, ascending=false)
// Output: [ , 0.2, 1.17, 0.03, 0.03, 0.15]
  • tradeVolume is used to select the most active trading days;
  • For the data on 2024.01.09, the two trading days with the highest trading volume in the most recent four-day window correspond to the samples (0.9, 1.4) and (0.4, 0.8), whose covariance is 0.15.

Related function: mcovar