列表中先进先出的配对,当累积总和越过0时。

3

我将尝试实现FIFO配对。

假设我有一个列表,其中包含买入/卖空数量和卖出/平仓数量,如下所示:

x = [100.0, -100.0, 100.0, 100.0, -200.0, 200.0, -100.0, -100.0, 100.0,-100.0]

我正在尝试分离买入和卖出,使它们的总和等于0。
i.e. x[0] is offset with x[1]
x[2] and x[3] is offset with x[4]

我正在尝试获取一个嵌套的列表,其中包含列表x的索引位置,如下所示:

[[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]

如果初始列表是相反的,我期望得到完全相同的结果:
x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0]

基本上,每当累积总和穿过 0 时,我就会重置配对。

非常感谢您的帮助!

我已经实现了部分解决方案,其中列表具有完美的偏移大小,例如:

def find_matching_position(trade_list):
    solutions = list(zip([i for i, x2 in enumerate(trade_list) if x2 == trade_list[0]],
                         [i for i, x2 in enumerate(trade_list) if x2 == trade_list[0] * -1]))

    return [sorted(x) for x in solutions]

x = [100, 100, -100 , 100, -100, -100]

    find_matching_position(x)
    [[0, 2], [1, 4], [3, 5]]

1
你能展示一下你自己解决这个问题的任何努力吗? - Scott Hunter
@ScottHunter 添加了我现在所在的位置。 - Steven G
3个回答

2
你��以尝试这个方法:
x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0]
current_sum = 0
current_sub = 0
t1 = []
t2 = []
t3 = []
for i, a in enumerate(x):
   if a >= 0:
      if (current_sum + a)+current_sub == 0:
          t1.append(i)
          t2.append([t1, t3])
          t1 = []
          t3 = []
          current_sum = 0
          current_sub = 0
       else:
          current_sum += a
          t1.append(i)
   else:
       if current_sum + (current_sub + a) == 0:
           t3.append(i)
           t2.append([t1, t3])
           t1 = []
           t3 = []
           current_sum = 0
           current_sub = 0
       else:
           current_sub += a
           t3.append(i)

print(t2)

输出:

[[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]

有趣的方法,如果以正数开头,运行良好,但反过来就不行了!检查是否有修改。 - Steven G
@StevenG 请查看我的最近修改,现在它可以同时适用于两种情况。 - Ajax1234

1
一些更加紧凑的内容:
def split_seq( seq ):
    result = []
    sum = 0
    subseq = [[],[]]
    for i,a in enumerate(seq):
        sum += a
        subseq[ 0 if a>=0 else 1 ].append( i )
        if sum == 0:
            result.append( subseq )
            subseq = [[],[]]
    return result

0
我尝试的代码(Python 2.7)如下:
x = [100.0, -100.0, 100.0, 100.0, -200.0, 200.0, -100.0, -100.0, 100.0,-100.0]
MasterList, Pos, Neg = [], [], []

for i in range(len(x)):
    if x[i] >= 0:
        Pos.append(i)
    else:
        Neg.append(i)
    if sum([x[n] for n in Pos]) + sum([x[n] for n in Neg]) == 0:
        if Pos[0] < Neg[0]:
            MasterList.append([Pos, Neg])
        else:
            MasterList.append([Neg, Pos])           
        Pos, Neg = [], []

print MasterList

输出:

[[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]

x = [-1, -1, -1, 2, 1, -3, 1, 2] 的输出结果:

[[[0, 1, 2], [3, 4]], [[5], [6, 7]]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接