Skip to content

Instantly share code, notes, and snippets.

@yashi
Created January 16, 2024 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yashi/709a9e452d84c89cd23b0c0367a0acb5 to your computer and use it in GitHub Desktop.
Save yashi/709a9e452d84c89cd23b0c0367a0acb5 to your computer and use it in GitHub Desktop.
Take rolling mean by using boost::accumulators
#include <iostream>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
#include <boost/accumulators/statistics/stats.hpp>
namespace ba = boost::accumulators;
int main() {
// Set the window size
size_t window_size = 3;
// Initialize accumulator
ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>> acc(
ba::tag::rolling_window::window_size = window_size
);
// Sample data points
std::vector<double> prices = {4166.82, 4117.37, 4137.23, 4186.77, 4247.68, 4217.04, 4224.16};
// Calculate and print rolling mean for each data point
for (double price : prices) {
acc(price);
std::cout << "Rolling Mean: " << ba::rolling_mean(acc) << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment