Skip to content

Instantly share code, notes, and snippets.

@BasThomas
Last active April 4, 2023 10:16
Show Gist options
  • Save BasThomas/d049f845d688dac5c06ca68af1f3ca1b to your computer and use it in GitHub Desktop.
Save BasThomas/d049f845d688dac5c06ca68af1f3ca1b to your computer and use it in GitHub Desktop.
Calculate a moving average in Swift (Swift 4.1)
extension Collection where Element == Int, Index == Int {
/// Calculates a moving average.
/// - Parameter period: the period to calculate averages for.
/// - Warning: the supplied `period` must be larger than 1.
/// - Warning: the supplied `period` should not exceed the collection's `count`.
/// - Returns: a dictionary of indexes and averages.
func movingAverage(period: Int) -> [Int: Float] {
precondition(period > 1)
precondition(count > period)
let result = (0..<self.count).compactMap { index -> (Int, Float)? in
if (0..<period).contains(index) { return nil }
let range = index - period..<index
let sum = self[range].reduce(0, +)
let result = Float(sum) / Float(period)
return (index, result)
}
return Dictionary(uniqueKeysWithValues: result)
}
}
@BasThomas
Copy link
Author

BasThomas commented Mar 26, 2018

Usage:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
let result = numbers.movingAverage(period: 10)

let mapped = result
    .sorted { $0.key < $1.key }
    .map { $0.value }

screen shot 2018-03-26 at 10 54 27

@sultan-arshi
Copy link

it should have another parameter for moving index/window some thing describe in the moving Mean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment