Created
January 31, 2015 00:33
-
-
Save eldritchideen/b8edcea93ced80b03f53 to your computer and use it in GitHub Desktop.
Moving Average in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn average [coll] | |
(/ (reduce + coll) | |
(count coll))) | |
(defn ma [period coll] | |
(lazy-cat (repeat (dec period) nil) | |
(map average (partition period 1 coll)))) |
Another interesting implementation from StackOverflow
(defn moving-average
"Calculates the moving average of values with the given period.
Returns a lazy seq, works with infinite input sequences.
Does not include initial zeros in the output."
[period values]
(let [gen (fn gen [last-sum values-old values-new]
(if (empty? values-new)
nil
(let [num-out (first values-old)
num-in (first values-new)
new-sum (+ last-sum (- num-out) num-in)]
(lazy-seq
(cons new-sum
(gen new-sum
(next values-old)
(next values-new)))))))]
(if (< (count (take period values)) period)
nil
(map #(/ % period)
(gen (apply + (take (dec period) values))
(cons 0 values)
(drop (dec period) values))))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Validated it against the following python pandas code:
Clojure result