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

时间:2020-05-07 07:34:21

标签: python algorithmic-trading cryptocurrency

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

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。

2 个答案:

答案 0 :(得分:0)

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

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

BTCtest[BTCtest['Position'] == 0].apply(myfunction, axis=1)

答案 1 :(得分:0)

我不了解您的代码,但我了解您的标题。

要将负值转换为正值,如果它小于0,我们可以将其乘以“ -1”。因此,写

numberr=int(input("Enter a number: "))
if numberr<0:
    numberr*=-1
print(numberr)

希望这会有所帮助。