Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vectorized kdb/q function from c++ loops

Tags:

c++

kdb+

Here's c++ code to calculate pivot highs, containing two nested for loops:

std::vector<double>
pivothigh(const std::vector<double> &src,
          const unsigned int left,
          const unsigned int right) {
    const auto nan = std::numeric_limits<double>::quiet_NaN();
    const auto N = src.size();
    std::vector<double> result(N, nan);
    for (auto i = left; i < N - right; i++) {
        const auto val = src[i];
        bool is_pivot = true;
        for (auto j = i - left; j <= i + right; j++) {
            if (src[j] > val) {
                is_pivot = false;
                break;
            }
        }
        if (is_pivot) {
            result[i] = val;
        }
    }
    return result;
}

How can I convert the above into a vectorized kdb/q function: pivothigh:{[src;left;right] ...}?

The purpose of the above function is to calculate the swing highs of a series of security prices (src), given a minimum number of bars to its left (lbl) and right (lbr). It aims to match the functionality of ta.pivothigh() in Tradingview's Pine Script v5.

like image 870
marital_weeping Avatar asked Sep 03 '26 21:09

marital_weeping


1 Answers

You can try this approach on your data and see if it works for you.

/ find indexes of all elements which are greater than n left neighbours
phl:{[l;n]w:where l=n mmax l;w where w>=n-1};

/ find indexes of all elements which are greater than m right neighbours
phr:{[l;m]w:count[l]-1+where r=m mmax r:reverse l;w where w<=count[l]-m}

pivothigh:{[src;left;right] phl[src;left] inter phr[src;right]}
like image 75
Igor Korkhov Avatar answered Sep 05 '26 10:09

Igor Korkhov