Public
Edited
May 21, 2024
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function weightedMovingAverage(values, windowSize, decay) {
// Loop through the raw values, which are assumed to be in chronological order
// If they are not chronological you will have a bad time.
return values.map((d, i) => {
// Slice all the values for this window
// This example assumes the data are stored in the 'y' attribute.
const window = values.slice(i - windowSize + 1, i + 1).map((d) => d.y);

// Discount past values based on the increasing decay factor
const means = window.map((d, j) => d * Math.pow(decay, windowSize - j - 1));

// Get what those factors are for each value
const base = window.map((d, j) => Math.pow(decay, windowSize - j - 1));

// Calculate the weighted mean by dividing one into the other
const weightedMean = d3.sum(means) / d3.sum(base);

// Toss the result in an object and return it
return {
x: d.x,
y: weightedMean
};
});
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chicago = await FileAttachment("chicago-homicide-dates.csv").csv()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more