【问题标题】:is there a way to make a value non-negative in dataframe有没有办法使数据框中的值非负
【发布时间】:2020-05-07 07:34:21
【问题描述】:

我是编码新手,我正在使用 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。

【问题讨论】:

  • 仓位== 0时,你想对股票做什么?您要删除这些行还是要为它们赋予其他值?

标签: python algorithmic-trading cryptocurrency


【解决方案1】:

我不明白你的代码,但我明白你的标题。

要将负值转换为正值,如果小于0,我们可以将它乘以'-1'。所以,写

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

希望这会有所帮助。

【讨论】:

  • 在这之前还有一堆其他的代码。但只是我试图回测我的逻辑,即:如果 MA10 > MA50 我们买入一股,如果 MA10
【解决方案2】:

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

此外,如果您只想在没有零行的情况下进行操作,请执行以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2019-09-12
    • 2019-08-24
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多