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.
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With