Python 如何在数据帧上有效地应用一系列条件-库存回溯测试
我正在尝试将一系列条件和操作应用到pandas数据帧上(请参阅下面的数据帧,包括VTI、upper、lower等)。我试图使用apply,但在使用时遇到了很多问题。)。我当前的解决方案(工作得很好)依赖于在数据帧中迭代的for循环。但我的感觉是,这是一个低效的方式来完成我的模拟。如果能在我的代码设计上得到帮助,我将不胜感激Python 如何在数据帧上有效地应用一系列条件-库存回溯测试,python,pandas,finance,Python,Pandas,Finance,我正在尝试将一系列条件和操作应用到pandas数据帧上(请参阅下面的数据帧,包括VTI、upper、lower等)。我试图使用apply,但在使用时遇到了很多问题。)。我当前的解决方案(工作得很好)依赖于在数据帧中迭代的for循环。但我的感觉是,这是一个低效的方式来完成我的模拟。如果能在我的代码设计上得到帮助,我将不胜感激 VTI upper lower sell buy AboveUpper BelowUpper BelowLower date tokens order 0 44.58
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
如果我想运行一组条件和forloop,如下面所示,并且仅当行满足所提供的条件时才运行下面的函数(get row data函数),我该如何做
我的直觉告诉我使用.apply(),但我不清楚在这种情况下如何使用它。如果将所有if和for循环结合起来,那么就有很多行。下面的代码实际上输出了一个全新的数据帧。我想知道是否有更有效/更好的方法来考虑这个模拟/股票回溯测试过程的设计
Get row data(获取行数据)只是从数据框中获取关键数据,并基于全局数据计算某些信息(例如我已经拥有多少资本,我已经拥有多少股票),然后给出一个列表。我将所有这些列表附加到一个我称之为公文包的数据框中
我已经给出了使用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)
##这仅适用于算法的sell部分
如果val['sell']==True且tokens==maxtokens:
打印“无出售标志”
如果val['sell']==True且令牌
一般来说,您需要评估给定行的所需结果取决于集合中“较高”的数据的方式。如果可以基于较高行中的输入数据创建给定行的输出,则可以使用类似于apply
的方法节省一些时间和精力。但是,如果给定行的期望输出取决于前几行的输出,那么您的问题本质上是有序的,因此,您不可能比for
循环做得更好,即使您最终得到的代码更干净。啊,我明白了。我认为是后一个问题。我的输出确实依赖于前几行的输出,因此可以对其进行排序。