如何通过数据帧加速极其缓慢的迭代?

2024-10-07 16:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经收集了几个星期的500毫秒股票数据。不,我想遍历每一天的数据,并对其进行迭代,以确定在任何给定的最后一个价格值下,一个特定的lowerbound将被传递多少次,接下来的一天将被传递一个特定的上限。在脚本开始搜索是否达到上界之前,必须传递lowerbound

所以基本上,如果第一行的最后一个价格是10,下一个是9和11,那么代码首先会试图找到一个时刻,当剩下的第i+1…i+2行。。。当到达下界时,一旦到达下界,代码就会在到达上界时切换到查找。如果达到上限,那么成功将添加1,代码再次开始查找下限,再次执行整个过程

这整个过程发生在每一行,因此基本上对于每一行,我们将有一个列来显示在给定行之后的行中成功达到下限和上限的次数

我遇到的问题是,我每天大约有14400行数据,大约有40天,所以大约有576000行数据。迭代绝对需要永远的时间,为了让我对所有的数据都这样做,我需要我的计算机运行几天。我肯定没有用最有效的方法来做这件事,是吗?有没有人能指出一个概念,我可以更有效地重写这段代码?还是我一直在等待它准备我的数据

    range_per = .00069 #the percentage determining lower and upper bound
    data['Success?']=np.nan
    data['Success? Count']=np.nan

    #For every row count how many times the trade in the range would be successful
    for i in range(0,len(data)):
        last_price = data.at[i,'lastPrice']
        lower_bound = last_price -  last_price*range_per
        upper_bound = last_price + last_price*range_per
        lower_bound_reached = False
        upper_bound_reached = False
        success=0

        for b in range(i+1,len(data)):
            last_price = data.at[b,'lastPrice']
            while lower_bound_reached == False:
                if lower_bound - last_price >=0:
                    upper_bound_reached = False
                    lower_bound_reached = True

                else:
                    break
            while (upper_bound_reached == False and lower_bound_reached ==True):
                if upper_bound - last_price <=0:
                    success+=1
                    lower_bound_reached = False
                    upper_bound_reached = True


                else:
                    break
        print('row %s: %s times' %(i, success))
        data['Success? Count'][i] = success
        if success>0:
            data['Success?'][i] = True
        else: 
            data['Success?'][i] = False

Here a a look at the last price row and the two output rows created by the code above


Tags: 数据代码falsetruedatarangeupperlower