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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more