@thi.ng/transducers-stats
Version:
Transducers for statistical / technical analysis
29 lines (28 loc) • 798 B
JavaScript
import { isNumber } from "@thi.ng/checks/is-number";
import { comp } from "@thi.ng/transducers/comp";
import { iterator1 } from "@thi.ng/transducers/iterator";
import { map } from "@thi.ng/transducers/map";
import { partition } from "@thi.ng/transducers/partition";
import { range } from "@thi.ng/transducers/range";
import { dot } from "./dot.js";
function wma(weights, src) {
if (src) {
return iterator1(wma(weights), src);
}
let period, wsum;
if (isNumber(weights)) {
period = weights | 0;
weights = [...range(1, period + 1)];
wsum = period * (period + 1) / 2;
} else {
period = weights.length;
wsum = weights.reduce((acc, x) => acc + x, 0);
}
return comp(
partition(period, 1),
map((window) => dot(window, weights) / wsum)
);
}
export {
wma
};