gpt4 book ai didi

python - python 中识别 python 数组或列表中最大累积差异的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-05 04:36:06 31 4
gpt4 key购买 nike

假设我有以下列表,对应于及时的股票价格:

prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11]

我想确定以下总体上最大的累积差异,例如最大的返回:

[(1,10), (3,12), (6,13), (4,11)]

累积差 = 9+9+7+7 = 32

现在根据这个结果,我想在这些价格之间分配多头头寸 (1),其余时间分配空头头寸 (0):

prices   = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11]
position = [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]

到目前为止,我设法用这段代码识别了列表中的最大差异:

print(nlargest(20, combinations(prices, 2), key = lambda x: abs(x[0]-x[1])))
[(1, 13), (1, 12), (1, 11), (3, 13), (3, 13), (1, 10), (1, 10), (3, 12), (3, 12), (13, 4)]

但随着时间的推移,我无法考虑它应该“读取”列表而不是在尝试组合时进一步使用前面的元素。

我也试过这个,它以矢量方式识别,唯一最大的区别是:

cummin = np.minimum.accumulate
print(np.max(prices - cummin(prices)))
12

还有这个,这似乎是我最接近的猜测:

l = np.array(list)
a = np.tile(l,(len(l),1))
print(a - a.T)
[[ 0 2 6 9 8 7 4 2 5 7 11 8 5 9 12 7 3 10]
[ -2 0 4 7 6 5 2 0 3 5 9 6 3 7 10 5 1 8]
[ -6 -4 0 3 2 1 -2 -4 -1 1 5 2 -1 3 6 1 -3 4]
[ -9 -7 -3 0 -1 -2 -5 -7 -4 -2 2 -1 -4 0 3 -2 -6 1]
[ -8 -6 -2 1 0 -1 -4 -6 -3 -1 3 0 -3 1 4 -1 -5 2]
[ -7 -5 -1 2 1 0 -3 -5 -2 0 4 1 -2 2 5 0 -4 3]
[ -4 -2 2 5 4 3 0 -2 1 3 7 4 1 5 8 3 -1 6]
[ -2 0 4 7 6 5 2 0 3 5 9 6 3 7 10 5 1 8]
[ -5 -3 1 4 3 2 -1 -3 0 2 6 3 0 4 7 2 -2 5]
[ -7 -5 -1 2 1 0 -3 -5 -2 0 4 1 -2 2 5 0 -4 3]
[-11 -9 -5 -2 -3 -4 -7 -9 -6 -4 0 -3 -6 -2 1 -4 -8 -1]
[ -8 -6 -2 1 0 -1 -4 -6 -3 -1 3 0 -3 1 4 -1 -5 2]
[ -5 -3 1 4 3 2 -1 -3 0 2 6 3 0 4 7 2 -2 5]
[ -9 -7 -3 0 -1 -2 -5 -7 -4 -2 2 -1 -4 0 3 -2 -6 1]
[-12 -10 -6 -3 -4 -5 -8 -10 -7 -5 -1 -4 -7 -3 0 -5 -9 -2]
[ -7 -5 -1 2 1 0 -3 -5 -2 0 4 1 -2 2 5 0 -4 3]
[ -3 -1 3 6 5 4 1 -1 2 4 8 5 2 6 9 4 0 7]
[-10 -8 -4 -1 -2 -3 -6 -8 -5 -3 1 -2 -5 -1 2 -3 -7 0]]

但我无法从这个矩阵中找出这些交易的最佳组合 [(1,10), (3,12), (6,13), (4,11) ]

谁能帮帮我?

最佳答案

您可以使用 itertools.groupby 获得所需的配对作为:

from itertools import groupby
prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11]

incr_pairs = [list(g) for i, g in groupby(zip(prices, prices[1:]), lambda x: x[0] < x[1]) if i]
greatest_diff = [(x[0][0], x[-1][-1]) for x in incr_pairs]

greatest_diff 会给你:

[(1, 10), (3, 12), (6, 13), (4, 11)]

现在要获得累积差异,您可以使用 sum作为:

my_sum = sum(j-i for i, j in greatest_diff)
# where `my_sum` will give you: 32

关于python - python 中识别 python 数组或列表中最大累积差异的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70892197/

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