【问题标题】:How to look back at previous rows from within Pandas dataframe function call?如何从 Pandas 数据框函数调用中回顾前几行?
【发布时间】:2013-01-01 09:46:45
【问题描述】:

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

我有一个包含 OHLC 数据的 Pandas 数据框,并添加了几个 calculated columns,它们标识了我将用作启动头寸的信号的价格模式。

我现在想添加一个进一步的列来跟踪当前的净头寸。我曾尝试使用 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)

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

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')

滚动窗口函数似乎很自然,但据我了解,它们仅作用于单个时间序列或列,因此也不起作用,因为我需要在多个时间点访问多个列的值.

实际上我应该怎么做?

【问题讨论】:

    标签: python dataframe pandas algorithmic-trading quantitative-finance


    【解决方案1】:

    这个问题源于 NumPy。

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

    entered_long 正在返回一个类似数组的对象。 NumPy 拒绝猜测一个数组是真还是假:

    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()
    

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

    def calc_position(df):
      # sum of current positions + any new positions
    
      if entered_long(df).any():  # or .all()
    

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

    【讨论】:

    • 它真的盯着我的脸...谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2020-02-02
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多