我正在研究/回测交易系统。
我有一个包含 OHLC 数据的 Pandas 数据框,并添加了几个计算列 https://stackoverflow.com/questions/12376863/adding-calculated-columns-to-a-dataframe-in-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_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()
要解决此问题,请使用any
or all
指定数组为 True 的含义:
def calc_position(df):
# sum of current positions + any new positions
if entered_long(df).any(): # or .all()
The any()
如果其中任何一项,方法将返回 Trueentered_long(df)
是真的。
这all()
如果所有项目都在,方法将返回 Trueentered_long(df)
是真的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)