如何回顾Pandas数据帧函数调用中的前几行?

ult*_*909 2 python algorithmic-trading quantitative-finance dataframe pandas

我正在研究/回测交易系统.

我有一个包含OHLC数据的Pandas数据框,并添加了几个计算列,用于识别我将用作启动头寸信号的价格模式.

我现在想添加一个能够跟踪当前净头寸的列.我已经尝试使用df.apply(),但是将数据帧本身作为参数而不是行对象传递,因为后者我似乎无法回顾之前的行以确定它们是否导致任何价格模式:

open_campaigns = []
Campaign = namedtuple('Campaign', 'open position stop')

def calc_position(df):
  # sum of current positions + any new positions

  if entered_long(df):
    open_campaigns.add(
        Campaign(
            calc_long_open(df.High.shift(1)), 
            calc_position_size(df), 
            calc_long_isl(df)
        )
    )

  return sum(campaign.position for campaign in open_campaigns)

def entered_long(df):
  return buy_pattern(df) & (df.High > df.High.shift(1))

df["Position"] = df.apply(lambda row: calc_position(df), axis=1)
Run Code Online (Sandbox Code Playgroud)

但是,这会返回以下错误:

ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', u'occurred at index 1997-07-16 08:00:00')
Run Code Online (Sandbox Code Playgroud)

滚动窗口函数似乎很自然,但据我所知,它们只作用于单个时间序列或列,因此无法工作,因为我需要在多个时间点访问多列的值.

我该怎么做呢?

unu*_*tbu 5

这个问题源于NumPy.

def entered_long(df):
  return buy_pattern(df) & (df.High > df.High.shift(1))
Run Code Online (Sandbox Code Playgroud)

entered_long返回一个类似数组的对象.NumPy拒绝猜测数组是True还是False:

In [48]: x = np.array([ True,  True,  True], dtype=bool)

In [49]: bool(x)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)

要解决此问题,请使用anyall指定数组为True的含义:

def calc_position(df):
  # sum of current positions + any new positions

  if entered_long(df).any():  # or .all()
Run Code Online (Sandbox Code Playgroud)

any()如果任何项目entered_long(df)为True ,则该方法将返回True.all()如果所有项目entered_long(df)都为True ,则该方法将返回True.