这是一个通用的矢量化解决方案,使用cumsum替换那些切片的摘要和argmax,以获得用于设置IF-case操作的切片限制的适当索引 –
# Use cumsum to replace sliced summations - Basically all those
# `list_amounts[0]`, `sum(list_amounts[0: 2]))`, `sum(list_amounts[0: 3])`, etc.
c = np.cumsum(list_amounts)
# Use argmax to decide the slicing limits for the intended slicing operations.
# So, this would replace the last number in the slices -
# list_prices[0: 2], list_prices[0: 3], etc.
idx = (c >= BuyAmount).argmax()
# Use the slicing limit to get the slice off list_prices needed as the first
# input to numpy.average
l = list_prices[:idx+1]
# This step gets us the weights. Now, in the weights we have two parts. E.g.
# for the third-IF we have :
# [list_amounts[0],list_amounts[1],BuyAmount - (sum(list_amounts[0: 2]))]
# Here, we would slice off list_amounts limited by `idx`.
# The second part is sliced summation limited by `idx` again.
w = np.r_[list_amounts[:idx], BuyAmount - c[idx-1]]
# Finally, plug-in the two inputs to np.average and get avgprice output.
avgprice = np.average(l,weights=w)
# Get idx element off list_prices as the highprice output.
highprice = list_prices[idx]
我们可以进一步优化以删除连接步骤(使用np.r_)并获得avgprice,就像这样 –
slice1_sum = np.multiply(list_prices[:idx], list_amounts[:idx]).sum()
# or np.dot(list_prices[:idx], list_amounts[:idx])
slice2_sum = list_prices[idx]*(BuyAmount - c[idx-1])
weight_sum = np.sum(list_amounts[:idx]) + BuyAmount - c[idx-1]
avgprice = (slice1_sum+slice2_sum)/weight_sum