Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从dataframe函数调用中查看以前的行?_Python_Dataframe_Pandas_Algorithmic Trading_Quantitative Finance - Fatal编程技术网

Python 如何从dataframe函数调用中查看以前的行?

Python 如何从dataframe函数调用中查看以前的行?,python,dataframe,pandas,algorithmic-trading,quantitative-finance,Python,Dataframe,Pandas,Algorithmic Trading,Quantitative Finance,我正在研究/测试一个交易系统 我有一个包含OHLC数据的Pandas数据框,并添加了几个识别价格模式的数据框,我将使用它们作为启动头寸的信号 我现在想再增加一个专栏,记录当前的净头寸。我曾尝试使用df.apply(),但将数据帧本身作为参数而不是行对象传递,对于后者,我似乎无法回顾前面的行以确定它们是否会导致任何价格模式: open_campaigns = [] Campaign = namedtuple('Campaign', 'open position stop') def calc_p

我正在研究/测试一个交易系统

我有一个包含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)
但是,这将返回以下错误:

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')
滚动窗口函数看起来很自然,但据我所知,它们只作用于单个时间序列或列,因此也不起作用,因为我需要在多个时间点访问多个列的值


事实上,我应该怎么做呢?

这个问题的根源在于NumPy

def entered_long(df):
  return buy_pattern(df) & (df.High > df.High.shift(1))
entered\u 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()
要解决此问题,请使用
any
all
指定数组为真的含义:

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\u long(df)
中的所有项目都是真的,
all()
方法将返回真的。

它真的盯着我看了。。。谢谢:)