{ $values { "seq" "a sequence" } { "newseq" "a sequence" } }
{ $description "Returns a new sequence where each element is an array of { value, index }" } ;
+HELP: distribute
+{ $values { "amount" "a number of amount" } { "n" "a number of buckets" } { "seq" "a sequence" } }
+{ $description
+ "Distribute 'amount' in 'n' buckets, as equally as possible. Returns a list of 'n' elements that sum to 'amount'.\n"
+}
+{ $examples
+ { $example
+ "USING: math.finance"
+ "3 1 distribute"
+ "{ 3 }" }
+ { $example
+ "USING: math.finance"
+ "3 3 distribute"
+ "{ 1 1 1 }" }
+ { $example
+ "USING: math.finance"
+ "5 3 distribute"
+ "{ 2 1 2 }" }
+ { $example
+ "USING: math.finance"
+ "3 5 distribute"
+ "{ 1 0 1 0 1 }" }
+ { $example
+ "USING: math.finance"
+ "1000 7 distribute"
+ "{ 143 143 143 142 143 143 143 }" }
+} ;
+
HELP: sma
{ $values { "seq" "a sequence" } { "n" "number of periods" } { "newseq" "a sequence" } }
{ $description "Returns the Simple Moving Average with the specified periodicity." } ;
[ { 1 3 1 } ] [ { 1 3 2 6 3 } 2 momentum ] unit-test
+[ { 3 } ] [ 3 1 distribute ] unit-test
+[ { 1 1 1 } ] [ 3 3 distribute ] unit-test
+[ { 2 1 2 } ] [ 5 3 distribute ] unit-test
+[ { 1 0 1 0 1 } ] [ 3 5 distribute ] unit-test
+[ { 143 143 143 142 143 143 143 } ] [ 1000 7 distribute ] unit-test
+
! Copyright (C) 2008 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
-USING: arrays assocs fry kernel grouping math math.statistics math.vectors sequences ;
+USING: arrays assocs kernel grouping sequences shuffle
+math math.functions math.statistics math.vectors ;
IN: math.finance
: enumerate ( seq -- newseq )
<enum> >alist ;
+: distribute ( amount n -- seq )
+ [ / ] keep 0 <array> [ 0 0 ] dip
+ [ + [ [ dup ] dip + ] dip
+ [ dup round ] dip 2dup -
+ [ drop ] dip ] map 3nip ;
+
<PRIVATE
: weighted ( x y a -- z )
PRIVATE>
: ema ( seq n -- newseq )
- a swap first-rest swap '[ [ dup ] 2dip swap rot weighted ] accumulate 2nip ;
+ a swap first-rest swap [ [ dup ] 2dip swap rot weighted ] accumulate 2nip ;
: sma ( seq n -- newseq )
clump [ mean ] map ;
2dup tail-slice -rot swap [ length ] keep
[ - neg ] dip swap head-slice v- ;
-