ruby
52 lines · 8 steps
A weighted moving average forecaster in Ruby
A class that predicts the next value in a series by blending recent points with normalized weights.
Explained by
highlit
1class WeightedMovingAverageForecaster
2 DEFAULT_WINDOW = 5
3
4 def initialize(window: DEFAULT_WINDOW, weights: nil)
5 @window = window
6 @weights = normalize(weights || default_weights(window))
7
8 unless @weights.size == @window
9 raise ArgumentError, "expected #{@window} weights, got #{@weights.size}"
10 end
11 end
12
13 def forecast(series)
14 return nil if series.size < @window
15
16 recent = series.last(@window)
17 recent.zip(@weights).sum { |value, weight| value * weight }
18 end
19
20 def forecast_next(series, steps:)
21 working = series.dup
22
23 Array.new(steps) do
24 predicted = forecast(working)
25 break [] if predicted.nil?
26
27 working << predicted
28 predicted
29 end
30 end
31
32 def rolling(series)
33 return [] if series.size < @window
34
35 (@window..series.size).map do |upper|
36 forecast(series[0...upper])
37 end
38 end
39
40 private
41
42 def default_weights(window)
43 (1..window).to_a
44 end
45
46 def normalize(weights)
47 total = weights.sum.to_f
48 raise ArgumentError, "weights must sum to a positive value" unless total.positive?
49
50 weights.map { |w| w / total }
51 end
52end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing weights so they sum to one lets the forecast stay on the same scale as the input values.
- 2Feeding a prediction back into the series turns a one-step forecast into a multi-step one.
- 3Validating configuration in the constructor catches mismatched inputs before any forecasting runs.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-weighted-moving-average-forecaster-in-ruby-explained-ruby-6b66/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.