gpt4 book ai didi

python - 如何构建一个检测 2 个列表上交叉点的函数

转载 作者:行者123 更新时间:2023-12-01 01:35:03 25 4
gpt4 key购买 nike

我有一个作业,我必须编写一个可以检测两个列表中交叉点的函数。功能是分析财务数据。例如,我有两个价格(移动平均线)列表作为输入,作为输出,我想要两个单独的列表,1 个是这些价格(移动平均线)相交的时间(即时间指数),1 个确定哪个列表更高在交叉点(即较高的指数)。我无法想出正确的语法来在 python 上定义上述标准。到目前为止我还没有写任何东西,因为我被困住了。有没有人做过类似的事情,有什么建议吗?

附加信息,作业涉及移动平均线以及检查移动平均线何时相交。我已经能够编写一个检测移动平均线的函数,但我陷入了这一部分。抱歉缺少代码和信息。我很确定这里不鼓励复制粘贴整个分配标准,因此我尝试解释我的问题是什么。

    Identify cross-over indices for two equal-length lists of prices (here: moving averages)

Parameters:
prices1, prices2: lists of prices (ordered by time)

Returns:
list of crossover points

Each item in the returned list is a list [time_index, higher_index], where:
- time_index is the crossover time index (when it happends
- higher_index indicates which price becomes higher at timeIndex: either 1 for first list or 2 for second list

There are no crossovers before both price lists have values that are not None.
You can start making comparisons from the point at which both have number values.

Example use:
>>> p1 = [1, 2, 4, 5]
>>> p2 = [0, 2.5, 5, 3]
>>> cross_overs(p1, p2)
[[1, 2], [3, 1]]
>>> p1 = [None, 2.5, 3.5, 4.5, 4.5, 3.5, 2.5, 1.5, 3.5, 3.5]
>>> p2 = [None, None, 3.0, 4.0, 4.333333333333333, 4.0, 3.0, 2.0, 3.0, 2.6666666666666665]
>>> cross_overs(p1, p2)
[[5, 2], [8, 1]]
"""

对于第一部分(即识别何时发生交叉点,这是我尝试过的。但正如你所看到的,我得到的结果是不正确的。

def cross_overs(prices1, prices2):
times_index = list(set(prices1).intersection(set(prices2)))
print (times_index)

(input)
p1 = [1, 2, 4, 5]
p2 = [0, 2.5, 5, 3]
cross_overs(p1, p2)

(output)
[5]

最佳答案

这是针对您的问题的解决方案,并附有解释该过程的注释:

def cross_over(p1, p2):
p1_none_index = 0
p2_none_index = 0

# Find indices of last occurences of None in both lists.
try:
p1_none_index = len(p1) - p1[::-1].index(None)
except ValueError:
pass

try:
p2_none_index = len(p2) - p2[::-1].index(None)
except ValueError:
pass

# Take the maximum index of these indices.
startingIndex = max(0, max(p1_none_index, p2_none_index))
crossOvers = []

#Take the difference of each pair.
subtraction = [0] * startingIndex + [p1[i]-p2[i] for i in range(startingIndex,len(p1),1)]

#Check using product, to track positive or negative sign changes in order to see if there is a crossover point.
for i in range(1,len(subtraction),1):
if subtraction[i] * subtraction[i-1] < 0:
if subtraction[i] > 0:
crossOvers.append([i,1])
else:
crossOvers.append([i,2])
return crossOvers

使用您提供的数据运行它:

第一:

p1 = [1, 2, 4, 5]
p2 = [0, 2.5, 5, 3]

crossOvers = cross_over(p1, p2)
print(crossOvers)

结果:

[[1, 2], [3, 1]]

第二:

p1 = [None, 2.5, 3.5, 4.5, 4.5, 3.5, 2.5, 1.5, 3.5, 3.5]
p2 = [None, None, 3.0, 4.0, 4.333333333333333, 4.0, 3.0, 2.0, 3.0, 2.6666666666666665]

crossOvers = cross_over(p1, p2)
print(crossOvers)

结果:

[[5, 2], [8, 1]]

关于python - 如何构建一个检测 2 个列表上交叉点的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52465855/

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