我正在尝试回溯一项股票交易策略。我想每次cf_net > 0
买入100股,并在cf_net < 0
时平仓。这个周期是每5分钟一次。
我有一个名为cf_slice
的熊猫数据框,其中包含('1. open', cf_now, cf_then, cf_net, long)
。数据集为100个长度。在cf_net > 0
时,我想将100个份额添加到名为current_pos
的新数据框中。另外,我想计算('1. open' x current_pos)
并插入到名为value
的数据框中。理想情况下,我想为每笔真实交易计算100股,如果错误则平仓。我想在短边进行设置,但是如果您可以在长边方面帮助我,我可以管理短边。
Open = 282.91, 282.95, 282.87, 282.90, 283.02
cf_net = 1047, -1894, -2214, 3122, 3649
long = True, False, False, True, True
我尝试了numpy数组,并使用for循环遍历熊猫。我能够隔离多头/空头数据,但我正在努力的是增加和关闭整个头寸。
cf_slice = (data.loc[:, ['1. open', 'cf_now', 'cf_then', 'cf_net', 'long']])
current_pos = 0
shares = 0
long_cost = 0
long_credit = 0
short_cost = 0
short_credit = 0
net_profit = 0
for cf in cf_slice.cf_net:
# open long
if cf > 0 and current_pos >= 0:
current_pos += 1
shares += 100
# close long
elif cf < 0 and current_pos > 0:
current_pos = 0
shares = 0
# open short
elif cf < 0 and current_pos <= 0:
current_pos -= 1
shares -= 100
# close short
elif cf > 0 and current_pos < 0:
current_pos = 0
shares = 0
print(cf, current_pos, shares)
此代码似乎可以正确计数股票和当前头寸。但是,如何合并计算1. open
x当前位置?
我需要知道随着头寸增加并最终平仓的头寸价值。