gpt4 book ai didi

python - numpy 是否为此积累了正确的东西?

转载 作者:行者123 更新时间:2023-11-28 18:30:24 26 4
gpt4 key购买 nike

我有一个 pandas.Series 整数,如下所示:

1959-09-22    191.0
1959-09-23 196.0
1959-09-24 222.0
1959-09-25 232.0
1959-09-28 232.0
1959-09-29 242.0
1959-09-30 241.0
1959-10-01 247.0
1959-10-02 251.0
1959-10-05 275.0
1959-10-06 294.0
1959-10-07 313.0
1959-10-08 332.0
1959-10-09 343.0
1959-10-12 346.0
1959-10-13 344.0
1959-10-14 351.0
1959-10-15 336.0
1959-10-16 330.0
1959-10-19 319.0
1959-10-20 329.0
1959-10-21 356.0
1959-10-22 374.0

我想做的是处理这个列表,使连续整数之间的差异永远不会小于 10%。如果是,则保留最后一个值,直到与当前值的差异超过 10%。

最符合 Python 风格的方法是什么?

作为一些背景,这是一个财务头寸列表,其想法是通过不交易整体头寸的微小差异来降低交易成本。

最佳答案

这是一种也支持前向填充的方法-

def process_close_diffs(arr,percent_close,FORWARD_FILL=False):
# Get thresholds for each element starting from the second element until last
thresh = (percent_close/100.0)*(arr[:-1])

# Get the differentiations betwen consecutive elements
diffs = np.abs(np.diff(arr))

# See which elements are more than or equal to the thresh and
# select those with with boolean indexing.
# Additionally for the optional FORWARD_FILL criteria, use cumulative
# summation on the mask to create a replicated kind of array, which when
# indexed into the mask selected elements would give us forward-filled array
mask = np.append(True,diffs >= thresh)
if FORWARD_FILL:
return (arr[np.where(mask)[0]])[mask.cumsum()-1]
else:
return arr[mask]

sample 运行-

In [215]: data
Out[215]: array([25, 29, 27, 27, 17, 14, 7, 20, 21, 5])

In [216]: process_close_diffs(data,40) # Using 40% to see noticeable changes
Out[216]: array([25, 7, 20, 5])

In [217]: process_close_diffs(data,40,FORWARD_FILL=True)
Out[217]: array([25, 25, 25, 25, 25, 25, 7, 20, 20, 5])

关于python - numpy 是否为此积累了正确的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37974141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com