我如何在KDB+中按符号从表中获取累积加权平均价格,考虑所有先前的记录?

huangapple go评论48阅读模式
英文:

How can I get accumulating weighted-average prices in KDB+ by symbol from a table, taking into account all previous records?

问题

我想从一个表中获取按sym累积加权平均价格,这意味着不仅考虑前一个记录,还要考虑所有之前的记录。

期望输出:

q)show t:([]sym:`a`a`b`b;size:(2;6;7;5);price:(2;10;4;9);avgPrice:(2;8;4;6.083))
sym size price avgPrice
-----------------------
a   2    2     2
a   6    10    8
a   2    3     7
b   7    4     4
b   5    9     6.083
所以对于第二行:(2*2+10*6)/(2+6)=8
所以对于第三行:(2*2+10*6+2*3)/(2+6+2)=7
所以对于第四行:(7*4+5*9)/(7+5)=6.083

任何帮助都将不胜感激。提前感谢。

英文:

I would like get accumulating weighted-average prices by sym from a table, meaning taking account of not just the previous record but all previous records.

Input

q)show t:([]sym:`a`a`a`b`b;size:(2;6;2;7;5);price:(2;10;3;4;9))
sym size price
--------------
a   2    2
a   6    10
a   2    3
b   7    4
b   5    9

Desired Output:

q)show t:([]sym:`a`a`b`b;size:(2;6;7;5);price:(2;10;4;9);avgPrice:(2;8;4;6.083))
sym size price avgPrice
-----------------------
a   2    2     2
a   6    10    8
a   2    3     7
b   7    4     4
b   5    9     6.083
so for the second row: (2*2+10*6)/(2+6)=8
so for the third row: (2*2+10*6+2*3)/(2+6+2)=7
so for the forth row: (7*4+5*9)/(7+5)=6.083

Any help would be appreciated.
Thanks in advance.

答案1

得分: 4

更新平均价格:(价格总和*数量总和)%数量总和 通过符号从表t中
符号 数量 价格 平均价格

a 2 2 2
a 6 10 8
a 2 3 7
b 7 4 4
b 5 9 6.083333

英文:
update avgPrice:(sums price*size)%sums size by sym from t
sym size price avgPrice
-----------------------
a   2    2     2
a   6    10    8
a   2    3     7
b   7    4     4
b   5    9     6.083333

huangapple
  • 本文由 发表于 2023年6月1日 19:43:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定