有条件的变量的累积和

时间:2018-11-05 23:41:59

标签: r

我无法获得剩余的实际实际运行总量。当指示器显示"Buy"时,它应加100;当指示器显示"Sell"时,它应减100。

问题是我的剩余库存量仅在下一个“买入”信号时才添加 显示它何时变为0...。因为我没有任何股票可交易。

indicator   buy_sell_volume    actual_stock_volume_left
Buy         100                  100
Buy         100                  200
Hold         0                   200
Hold         0                   200
Sell       -100                  100
Sell       -100                   0
Sell       -100                   0
Sell       -100                   0
Sell       -100                   0
Buy         100                  100
Buy         100                  200

1 个答案:

答案 0 :(得分:0)

由于您已经对buy_sell_volume字段进行了编码(“ +用于购买,-用于销售),因此不需要基于indicator字段进行任何条件计算。简单的累积计算就可以了。

# initialize new column
df$stock_volume_left <- NA

# assuming you start with 0 stocks, assign 1st value to stocks left
df$stock_volume_left[1] <- max(df$buy_sell_volume[1], 0)

# calculate stocks left 
for(i in 2:nrow(df)) {
  df$stock_volume_left[i] <- max(df$stock_volume_left[i-1] + df$buy_sell_volume[i], 0)
}

   indicator buy_sell_volume stock_volume_left
1        Buy             100               100
2        Buy             100               200
3       Hold               0               200
4       Hold               0               200
5       Sell            -100               100
6       Sell            -100                 0
7       Sell            -100                 0
8       Sell            -100                 0
9       Sell            -100                 0
10       Buy             100               100
11       Buy             100               200