怎么快速计算最近1000个shares的vwap

我要计算单个股票最近1000shares相关的所有trades的vwap(成交量加权平均价),这1000shares可能是100、300、600三个trades的,也可能是30000、100两个trades的。找到参与计算的trades,使得shares总和超过1000,且减掉最远的一个trade,则总shares小于1000,然后算一下它们的vwap。我的代码如下:

attachments-2021-05-I55kLmfQ60a5be08a77ef.png运行了一下,速度不是很快,不知道是否有更快的写法?

请先 登录 后评论

1 个回答

Juntao Wang
defg lastVolPx(price, vol, bound){
    cumVol =  vol.cumsum()
    if(cumVol.tail() <= bound)
        return wavg(price, vol)
    else{
        start = (cumVol <= cumVol.tail() - bound).sum()
        return wavg(price.subarray(start:), vol.subarray(start:))
    }
}

n = 5000000
t =table(rand(string(1..4000), n) as sym, rand(10.0, n) as price, rand(500, n) as vol)
timer select lastVolPx(price, vol, 1000) as lastVolPx from t group by sym
请先 登录 后评论