如何有效地在熊猫数据框架上应用一长串条件 - 库存回溯测试

时间:2014-03-05 15:06:21

标签: python pandas finance

我正在尝试将一长串条件和操作应用到pandas数据框中(请参阅下面的数据框,包括VTI,上部,下部等)。我试图使用apply,但是我在这方面遇到了很多麻烦。)我当前的解决方案(完美地工作)依赖于迭代遍历数据帧的for循环。但我的感觉是,这是完成模拟的低效方法。我很感激有关代码设计的帮助。

  VTI upper lower sell   buy AboveUpper BelowUpper BelowLower date tokens order
0 44.58 NaN NaN  False   False   False   False   False   2001-06-15  5    0
1 44.29 NaN NaN  False   False   False   False   False   2001-06-18  5    1
2 44.42 NaN NaN  False   False   False   False   False   2001-06-19  5    2
3 44.88 NaN NaN  False   False   False   False   False   2001-06-20  5    3
4 45.24 NaN NaN  False   False   False   False   False   2001-06-21  5    4

如果我想运行一系列条件和forloops(如下所示)并运行下面的函数(获取行数据函数),只有当行符合提供的条件时,我该怎么做?

我的直觉说使用.apply()但我不清楚在这种情况下如何做到这一点。所有if和for循环组合在一起,就是很多行。下面实际输出一个全新的数据帧。我想知道是否有更有效/更好的方法来考虑这种模拟/库存回测过程的设计。

获取行数据只是从数据框中获取关键数据,并根据全局变量计算某些信息(比如我已经有多少资金,已经有多少股票)并吐出一个列表。我将所有这些列表附加到我称之为投资组合的数据框中。

我已经使用for循环给出了一段代码片段。

 ##This is only for the sell portion of the algorithm
 if val['sell'] == True and tokens == maxtokens: 
        print 'nothign to sell'


if val['sell'] == True and tokens < maxtokens: 
    print 'sellprice', price

    #CHOOSE THE MOST EXPENSIVE POSITION AND SELL IT#
    portfolio = sorted(portfolio, key = lambda x: x[0], reverse = True)
    soldpositions = [position for position in portfolio if position[7] == 'sold']
    soldpositions = sorted(portfolio, key=lambda x: x[1], reverse = True)


    for position in portfolio:

        #Position must exist 
        if position[9] == True:
            print 'position b4 sold', position

            #Position's price must be LOWER than current price 
            #AND the difference between the position's price and current price must be greater than sellbuybuffer
            if abs(position[0] - price) <= sellbuybuffer:
                print 'does not meet sellbuybuffer' 

            if position[0] < price and abs(position[0] - price) >= sellbuybuffer:
                status = 'sold'

                #This is if we have no sold positions yet 
                if len(soldpositions) == 0:
                   get_row_data(price, date, position, totalstocks, capital, status, tokens)

0 个答案:

没有答案