有一种方法可以使值在数据帧中为非负数

问题描述 投票:0回答:1

我是编码的新手,我正在使用python熊猫练习制作算法交易机器人。这是我的代码。

for date in BTCtest.index:
  if BTCtest.loc[date,'Shares'] == 0:
    BTCtest.loc[date,'Shares'] = max(0,-5)
  if BTCtest.loc[date, 'MA10'] > BTCtest.loc[date, 'MA50']:
    BTCtest.loc[date, 'Shares'] = 1
  elif BTCtest.loc[date, 'MA10'] < BTCtest.loc[date, 'MA50']:
    BTCtest.loc[date, 'Shares'] = -1

BTCtest['Position'] = BTCtest['Shares'].cumsum()
BTCtest['Close1'] = BTCtest['Close'].shift(-1)
BTCtest['Profit'] = [BTCtest.loc[date, 'Close1'] - BTCtest.loc[date, 'Close'] if BTCtest.loc[date, 'Shares']==1 else 0 for date in BTCtest.index]
BTCtest['Profit'].plot()
print (BTCtest)

plt.axhline(y=0, color='red')

这是我的代码,当位置为0时,我尝试不添加共享。我尝试过

if BTCtest.loc[date,'Shares'] == 0:
    BTCtest.loc[date,'Shares'] = 0
if BTCtest.loc[date,'Shares'] == 0:
    max(BTCtest.loc[date,'Shares'],-1)

下面是到目前为止的结果。enter image description here我不希望自己的排名低于0。

python algorithmic-trading cryptocurrency
1个回答
0
投票

您应该使用.apply函数,而不是遍历索引。它将真正简化您的代码,这是最佳实践。

此外,如果您现在只想使用零行,请执行以下操作:

BTCtest[BTCtest['Position'] == 0].apply(myfunction, axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.