diff --git a/extra/math/finance/finance-docs.factor b/extra/math/finance/finance-docs.factor index 9094a5bff6..10deec8a69 100644 --- a/extra/math/finance/finance-docs.factor +++ b/extra/math/finance/finance-docs.factor @@ -9,6 +9,34 @@ HELP: enumerate { $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." } ; diff --git a/extra/math/finance/finance-tests.factor b/extra/math/finance/finance-tests.factor index dce701bb2f..8c98583c84 100644 --- a/extra/math/finance/finance-tests.factor +++ b/extra/math/finance/finance-tests.factor @@ -6,3 +6,9 @@ IN: math.finance.tests [ { 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 + diff --git a/extra/math/finance/finance.factor b/extra/math/finance/finance.factor index ffb02208d3..ce59836442 100644 --- a/extra/math/finance/finance.factor +++ b/extra/math/finance/finance.factor @@ -1,13 +1,20 @@ ! 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 ) >alist ; +: distribute ( amount n -- seq ) + [ / ] keep 0 [ 0 0 ] dip + [ + [ [ dup ] dip + ] dip + [ dup round ] dip 2dup - + [ drop ] dip ] map 3nip ; + : 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 ; @@ -34,4 +41,3 @@ PRIVATE> 2dup tail-slice -rot swap [ length ] keep [ - neg ] dip swap head-slice v- ; -