I note that "self species ofSize: n" is not generally a good idea. Consider ByteArray, ShortIntegerArray, WordArray. Computing rolling means of these is perfectly sensible, but the results will not fit into an array of the same species. I'd stick with Array. The suggestion about subtracting an old element and adding a new one is great for integers, but for floating-point numbers risks accumulating errors. The On Wed, 8 Apr 2020 at 20:07, Cédrick Béler <cdrick65@gmail.com> wrote:
Hi,
I wanted to do a moving/rolling average on raw data [1]. I havenât find code for that (maybe this is done in polymath though).
So I ended writing that (I thing this is SMA):
SequenceableCollection>>movingAverage: anOrder "Answer the moving or rolling average for anOrder window"
| retval size x y | anOrder <= 0 ifTrue: [ Error signal: 'the order must be positive']. size := self size - anOrder. size negative ifTrue: [ Error signal: 'the collection size is too small']. retval := self species ofSize: size + 1.
x := 1. y := anOrder. [y <= self size ] whileTrue: [ retval at: x put: (self copyFrom: x to: y) average x := x + 1. y := y + 1 ]. ^retval
Not perfect but seems to works quite well (thatâs probably better to remove copyFrom: and use some kind of buffer instead).
Any interest in that ? If any existing code too, Iâll be interested especially for other implementation (weighted, exponential) ?
(#(118 113 105 105 103 99 98 101 100 107) movingAverage: 3) collect: [:v | v asScaledDecimal: 1 ] .
"an Array(112.0s1 107.7s1 104.3s1 102.3s1 100.0s1 99.3s1 99.7s1 102.7s1)"
Cheers, Cédrick
[1] https://www.meilleursbrokers.com/techniques-de-trading/moyennes-mobiles.html (in French but is understandable)